repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
devineniraghava/Ventilation_Efficiency_2
|
[
"3918d5335e3d7df0492088a05acfd9d9c7958a20"
] |
[
"results_plot.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 5 15:32:00 2020\n\n@author: Devineni\n\"\"\"\n\nimport pandas as pd\nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\nfrom uncertainties import ufloat_fromstr\nfrom uncertainties import ufloat\n\nimport xlrd\n\nimport pymysql\nfrom sqlalchemy import create_engine\n\ndef prRed(skk): print(\"\\033[31;1;m {}\\033[00m\" .format(skk)) \nimport datetime as dt\n\nc = ['#179C7D','#F29400','#1F82C0','#E2001A','#B1C800']\n# c = ['#179C7D','#F29400','#1F82C0']*4\n#%%\nimport datetime\nimport matplotlib.dates as mdates\n\nimport matplotlib.units as munits\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 7,4.5\nplt.rcParams[\"font.family\"] = \"calibri\"\nplt.rcParams[\"font.weight\"] = \"normal\"\nplt.rcParams[\"font.size\"] = 10\n\nfont = {'family': 'calibri',\n 'color': 'black',\n 'weight': 'normal',\n 'size': 16,\n }\ndf = pd.read_excel(\"C:/Users/Devineni/OneDrive - bwedu/MA_Raghavakrishna/1_Evaluation/results/results_final.xlsx\", sheet_name=\"plotting\")\ndf1 = df.iloc[:8] \ndf2 = df.iloc[8:]\n \n\n#%%\ndef autolabel(rects):\n \"\"\"Attach a text label above each bar in *rects*, displaying its height.\"\"\"\n for rect in rects:\n height = rect.get_height()\n ax.annotate('{:.0f}%'.format(round(height,0)),\n xy=(rect.get_x() + rect.get_width() / 4, height),\n xytext=(0, 3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='bottom')\n \n\nbdf = pd.read_excel(\"C:/Users/Devineni/OneDrive - bwedu/MA_Raghavakrishna/1_Evaluation/results/results_final.xlsx\", sheet_name=\"barplot\")\nbdf1 = bdf.iloc[:8] \nbdf2 = bdf.iloc[8:]\nktbdf = bdf.loc[16:]\nrbdf = bdf.loc[0:15]\n\n\n#%% Ea Bar plot\nfrom matplotlib.lines import Line2D\n\nfig, ax = plt.subplots()\nfor i in range(0,len(rbdf),4):\n rects1 = ax.bar(rbdf[\"Measurement\"].to_numpy()[i:i+2], rbdf[\"Ea%\"].to_numpy()[i:i+2],yerr=rbdf[\"std%\"].to_numpy()[i:i+2],align='center',color = ['#1F77B4','#FF7F0E'],ecolor='black',capsize=10, edgecolor = c[4])\n rects2 = ax.bar(rbdf[\"Measurement\"].to_numpy()[i+2:i+4], rbdf[\"Ea%\"].to_numpy()[i+2:i+4],yerr=rbdf[\"std%\"].to_numpy()[i+2:i+4],align='center',color = ['#1F77B4','#FF7F0E'],ecolor='black',capsize=10)\n autolabel(rects1)\n autolabel(rects2)\n\nrects3 = ax.bar(ktbdf[\"Measurement\"].to_numpy()[0:2], ktbdf[\"Ea%\"].to_numpy()[0:2],yerr=ktbdf[\"std%\"].to_numpy()[0:2],align='center',color = '#FF7F0E',ecolor='black',capsize=10, edgecolor = c[4])\nrects4 = ax.bar(ktbdf[\"Measurement\"].to_numpy()[2:4], ktbdf[\"Ea%\"].to_numpy()[2:4],yerr=ktbdf[\"std%\"].to_numpy()[2:4],align='center',color = '#FF7F0E',ecolor='black',capsize=10)\nautolabel(rects3)\nautolabel(rects4)\n\n\nlegend_elements = [Line2D([0], [0], marker='o', color='w', label='Balanced case',markerfacecolor='#1F77B4', markersize=10),\n Line2D([0], [0], marker='o', color='w', label='Exhaust case',markerfacecolor='#FF7F0E', markersize=10),\n Line2D([0], [0], color=c[4], label='summer',markerfacecolor='#FF7F0E', markersize=10),\n \n ]\n\nax.legend(handles=legend_elements, loc='upper right', labelspacing = 1)\n\n\nax.set_ylabel('Global Air Exchange Efficiency ea')\nax.set_xticks(bdf[\"Measurement\"].to_numpy())\nax.set_xticklabels(bdf[\"Measurement\"].to_numpy(), rotation='vertical')\nax.set_title('ESHL ea comparison for Summer and Winter (All Sensors)')\n# ax.yaxis.grid(b=True, color='#C0C0C0', linestyle='-')\n\nax.axhline(y=50, color = c[0], linestyle='dashed')\n\nfig = plt.gcf() # get current figure\n# fig.set_size_inches(22, 9)\n# when saving, specify the DPI\nplt.tight_layout()\nplt.savefig(\"myplot.png\", dpi = 100)\n\n# Save the figure and show\nplt.tight_layout()\n \n\nplt.show() \n \n# path = \"C:/Users/Devineni/OneDrive - bwedu/MA_Raghavakrishna/1_Evaluation/python_files/plots/Ea_plots/\"\n# plt.savefig(path+\"Ea_bar_plot.png\", dpi = 300, bbox_inches='tight')\n\n\n\n\n\n\n \n \n \n \n \n#%% Temperature effect on Ea\n\nfrom uncertainties import unumpy\nfig, ax = plt.subplots()\n\nfor line in range(0,df1.shape[0]):\n ax.text((df1[\"Delta T\"][line]+0.025), (df1[\"Ea\"][line]), df1[\"Measurement\"][line], horizontalalignment='center', size=12, color='black', weight='normal') \n \n \ndf1.plot.scatter(\"Delta T\",\"Ea\", ax = ax)\n \nfor i in range(4):\n plt.errorbar(df1.iloc[[i,i+4],:][\"Delta T\"].to_numpy(), df1.iloc[[i,i+4],:][\"Ea\"].to_numpy(),df1.iloc[[i,i+4],:][\"std\"].to_numpy(), capsize = 4, label = df1.iloc[i][\"Measurement\"][2:6])\nplt.ylim(0.2,0.8)\nax.axhline(0.5,color = c[0], linestyle='dashed')\n\nplt.legend()\n\nplt.show() \n \n# path = \"C:/Users/Devineni/OneDrive - bwedu/MA_Raghavakrishna/1_Evaluation/python_files/plots/Ea_plots/\"\n# plt.savefig(path+\"del_T_vs_Ea_Herdern.png\", dpi = 300, bbox_inches='tight')\n\n\n #%%%\nfig, ax = plt.subplots()\n\nfor line in range(0,df2.shape[0]):\n ax.text((df2.iloc[line,:][\"Delta T\"]+0.025), (df2.iloc[line,:][\"Ea\"]), df2.iloc[line,:][\"Measurement\"], horizontalalignment='center', size=12, color='black', weight='normal') \n \n \ndf2.plot.scatter(\"Delta T\",\"Ea\", ax = ax)\n \nfor i in range(6):\n plt.errorbar(df2.iloc[[i,i+6],:][\"Delta T\"].to_numpy(), df2.iloc[[i,i+6],:][\"Ea\"].to_numpy(), df2.iloc[[i,i+6],:][\"std\"].to_numpy(), capsize =4, label = df2.iloc[i][\"Measurement\"][2:6])\nplt.ylim(0.2,0.8)\nplt.xlim(-25,15)\nplt.legend()\nplt.show() \n\n\n# path = \"C:/Users/Devineni/OneDrive - bwedu/MA_Raghavakrishna/1_Evaluation/python_files/plots/Ea_plots/\"\n# plt.savefig(path+\"del_T_vs_Ea_ESHL.png\", dpi = 300, bbox_inches='tight') \n\n\n#%% 1) NTC vs Air age Herdern\nfig, ax = plt.subplots()\nax.plot(np.array([0,5]),np.array([0,5]), color = c[0] , label = \"Mixed ventilation\", linestyle='dashed')\n\n\nfor i in range(len(df1)):\n if \"W_\" in df1.iloc[i,:][\"Measurement\"]:\n plt.scatter(df1.iloc[[i],:][\"NTC\"].to_numpy(), df1.iloc[[i],:][\"tau\"].to_numpy(), color = df1.iloc[i,:][\"color\"] , marker=(5, 2), label = \"winter\")\n else:\n plt.scatter(df1.iloc[[i],:][\"NTC\"].to_numpy(), df1.iloc[[i],:][\"tau\"].to_numpy(), color = df1.iloc[i,:][\"color\"] , label = \"summer\")\n\n# syntax to not repeat lables\nhandles, labels = plt.gca().get_legend_handles_labels()\nby_label = dict(zip(labels, handles))\nplt.legend(by_label.values(), by_label.keys())\n\n# path = \"C:/Users/Devineni/OneDrive - bwedu/MA_Raghavakrishna/1_Evaluation/python_files/plots/Ea_plots/\"\n# plt.savefig(path+\"NTC_vs_tau_herdern.png\", dpi = 300, bbox_inches='tight')\n\n#%% 2) NTC vs Air age ESHL\nfig, ax = plt.subplots()\nax.plot(np.array([0,5]),np.array([0,5]), color = c[0] , label = \"Mixed ventilation\", linestyle='dashed')\n\n\nfor i in range(len(df2)):\n if \"W_\" in df2.iloc[i,:][\"Measurement\"]:\n plt.scatter(df2.iloc[[i],:][\"NTC\"].to_numpy(), df2.iloc[[i],:][\"tau\"].to_numpy(), color = df2.iloc[i,:][\"color\"] , marker=(5, 2), label = \"winter\")\n else:\n plt.scatter(df2.iloc[[i],:][\"NTC\"].to_numpy(), df2.iloc[[i],:][\"tau\"].to_numpy(), color = df2.iloc[i,:][\"color\"] , label = \"summer\")\n\n# syntax to not repeat lables\nhandles, labels = plt.gca().get_legend_handles_labels()\nby_label = dict(zip(labels, handles))\nplt.legend(by_label.values(), by_label.keys())\n\n# path = \"C:/Users/Devineni/OneDrive - bwedu/MA_Raghavakrishna/1_Evaluation/python_files/plots/Ea_plots/\"\n# plt.savefig(path+\"NTC_vs_tau_ESHL.png\", dpi = 300, bbox_inches='tight')\n\n#%% 3) ACH vs Air age Herdern and ESHL\n#%%% curve plot\nfig, ax = plt.subplots()\nx = np.linspace(0.15,2.75,100)\n\ny = 1/(x)\ny1 = 1/(2*x)\nax.plot(x,y1, color = c[3], linestyle='dashed')\n\nax.plot(x,y, color = c[0], linestyle='dashed')\n\n\nax.axvline(0.6, color = 'silver', linestyle='dotted', label = \"DIN EN 15251\")\nax.axvline(0.42, color = '#1F82C0', linestyle='dotted', label = \"Herdern DIN 1946-6\" )\nax.axvline(0.48, color = '#002060', linestyle='dotted', label = \"ESHL DIN 1946-6\")\n\n\nfor i in range(len(df)):\n if \"Herdern\" in df.iloc[i,:][\"Measurement\"]:\n if \"W_\" in df.iloc[i,:][\"Measurement\"]:\n plt.scatter(df.iloc[[i],:][\"ACH\"].to_numpy(), df.iloc[[i],:][\"tau\"].to_numpy(), color = df.iloc[i,:][\"color\"] , marker=(5, 2), label = \"Herdern winter\")\n else:\n plt.scatter(df.iloc[[i],:][\"ACH\"].to_numpy(), df.iloc[[i],:][\"tau\"].to_numpy(), color = df.iloc[i,:][\"color\"] , label = \"Herdern summer\")\n else:\n if \"W_\" in df.iloc[i,:][\"Measurement\"]:\n plt.scatter(df.iloc[[i],:][\"ACH\"].to_numpy(), df.iloc[[i],:][\"tau\"].to_numpy(), color = df.iloc[i,:][\"color\"] , marker=(5, 2), label = \"ESHL winter\")\n else:\n plt.scatter(df.iloc[[i],:][\"ACH\"].to_numpy(), df.iloc[[i],:][\"tau\"].to_numpy(), color = df.iloc[i,:][\"color\"] , label = \"ESHL summer\")\n# for line in range(0,df.shape[0]):\n# ax.text((df[\"ACH\"][line]), (df[\"tau\"][line]), df[\"Measurement\"][line], horizontalalignment='center', size=12, color='black', weight='normal') \n \n\n# syntax to not repeat lables\nhandles, labels = plt.gca().get_legend_handles_labels()\nby_label = dict(zip(labels, handles))\nplt.legend(by_label.values(), by_label.keys())\n\n# path = \"C:/Users/Devineni/OneDrive - bwedu/MA_Raghavakrishna/1_Evaluation/python_files/plots/Ea_plots/\"\n# plt.savefig(path+\"ACH_vs_tau_herdern_eshl.png\", dpi = 300, bbox_inches='tight')\n\n#%%% log - plot\nfig, ax = plt.subplots()\nx = np.linspace(0.15,2.75,100)\n\ny = 1/(x)\ny1 = 1/(2*x)\nax.plot(x,y1, color = c[3], linestyle='dashed')\n\nax.plot(x,y, color = c[0], linestyle='dashed')\n\nax.axvline(0.2, color = 'silver')\nax.axvline(0.4, color = 'silver')\nax.axvline(0.6, color = 'silver', linestyle='dotted', label = \"DIN EN 15251\")\nax.axvline(0.42, color = '#1F82C0', linestyle='dotted', label = \"Herdern DIN 1946-6\" )\nax.axvline(0.48, color = '#002060', linestyle='dotted', label = \"ESHL DIN 1946-6\")\nax.axvline(0.8, color = 'silver')\nax.axvline(1, color = 'silver')\nax.axvline(2, color = 'silver')\nax.axvline(3, color = 'silver')\n\nplt.yscale('log')\nplt.xscale('log')\nfor i in range(len(df)):\n if \"Herdern\" in df.iloc[i,:][\"Measurement\"]:\n if \"W_\" in df.iloc[i,:][\"Measurement\"]:\n plt.scatter(df.iloc[[i],:][\"ACH\"].to_numpy(), df.iloc[[i],:][\"tau\"].to_numpy(), color = df.iloc[i,:][\"color\"] , marker=(5, 2), label = \"Herdern winter\")\n else:\n plt.scatter(df.iloc[[i],:][\"ACH\"].to_numpy(), df.iloc[[i],:][\"tau\"].to_numpy(), color = df.iloc[i,:][\"color\"] , label = \"Herdern summer\")\n else:\n if \"W_\" in df.iloc[i,:][\"Measurement\"]:\n plt.scatter(df.iloc[[i],:][\"ACH\"].to_numpy(), df.iloc[[i],:][\"tau\"].to_numpy(), color = df.iloc[i,:][\"color\"] , marker=(5, 2), label = \"ESHL winter\")\n else:\n plt.scatter(df.iloc[[i],:][\"ACH\"].to_numpy(), df.iloc[[i],:][\"tau\"].to_numpy(), color = df.iloc[i,:][\"color\"] , label = \"ESHL summer\")\n# syntax to not repeat lables\nhandles, labels = plt.gca().get_legend_handles_labels()\nby_label = dict(zip(labels, handles))\nplt.legend(by_label.values(), by_label.keys(), loc = \"lower left\")\n\n# path = \"C:/Users/Devineni/OneDrive - bwedu/MA_Raghavakrishna/1_Evaluation/python_files/plots/Ea_plots/\"\n# plt.savefig(path+\"ACH_vs_tau_log.png\", dpi = 300, bbox_inches='tight')\n\n\n\n\n\n#%% ACH vs EAi\n\nfig, ax = plt.subplots()\n\nax.axvline(0.6, color = 'silver', linestyle='dotted', label = \"DIN EN 15251\")\nax.axvline(0.42, color = '#1F82C0', linestyle='dotted', label = \"Herdern DIN 1946-6\" )\nax.axvline(0.48, color = '#002060', linestyle='dotted', label = \"ESHL DIN 1946-6\")\nax.axhline(50,color = c[0], linestyle='dashed')\n\n\nfor i in range(len(df)):\n if \"Herdern\" in df.iloc[i,:][\"Measurement\"]:\n if \"W_\" in df.iloc[i,:][\"Measurement\"]:\n plt.scatter(df.iloc[[i],:][\"ACH\"].to_numpy(), df.iloc[[i],:][\"Ea%\"].to_numpy(), color = df.iloc[i,:][\"color\"] , marker=(5, 2), label = \"Herdern winter\")\n else:\n plt.scatter(df.iloc[[i],:][\"ACH\"].to_numpy(), df.iloc[[i],:][\"Ea%\"].to_numpy(), color = df.iloc[i,:][\"color\"] , label = \"Herdern summer\")\n else:\n if \"W_\" in df.iloc[i,:][\"Measurement\"]:\n plt.scatter(df.iloc[[i],:][\"ACH\"].to_numpy(), df.iloc[[i],:][\"Ea%\"].to_numpy(), color = df.iloc[i,:][\"color\"] , marker=(5, 2), label = \"ESHL winter\")\n else:\n plt.scatter(df.iloc[[i],:][\"ACH\"].to_numpy(), df.iloc[[i],:][\"Ea%\"].to_numpy(), color = df.iloc[i,:][\"color\"] , label = \"ESHL summer\")\n\n\n\nfrom scipy.optimize import curve_fit\nspl_data = df.loc[:,[\"Measurement\",\"ACH\",\"Ea\"]]\nspl_data1 = spl_data.iloc[:8] \nspl_data2 = spl_data.iloc[8:]\nspl_data1 = spl_data1.sort_values(by=['ACH'])\nspl_data2 = spl_data2.sort_values(by=['ACH'])\n\ndef func(x, a, b):\n return a * pow(x,-b) \nxdata = spl_data1[\"ACH\"].to_numpy()\nydata = spl_data1[\"Ea\"].to_numpy()\n\npopt, pcov = curve_fit(func, xdata, ydata)\nx = np.linspace(0.15,2.75,100)\ny = popt[0]*pow(x,-popt[1])\n\nplt.plot(x, y*100, '#1F82C0', label = r'$\\mathrm{\\varepsilon}^{\\mathrm{a}}$' +\" Herdern\")\n\n\nxdata = spl_data2[\"ACH\"].to_numpy()\nydata = spl_data2[\"Ea\"].to_numpy()\n\n\npopt, pcov = curve_fit(func, xdata, ydata)\nx = np.linspace(0.15,2.75,100)\ny = popt[0]*pow(x,-popt[1])\n\nplt.plot(x, y*100, '#002060')\n\n\n\n\n\nplt.ylim(0,100)\n# syntax to not repeat lables\nhandles, labels = plt.gca().get_legend_handles_labels()\nby_label = dict(zip(labels, handles))\nplt.legend(by_label.values(), by_label.keys())\n\n# path = \"C:/Users/Devineni/OneDrive - bwedu/MA_Raghavakrishna/1_Evaluation/python_files/plots/Ea_plots/\"\n# plt.savefig(path+\"ACH_vs_Eai.png\", dpi = 300, bbox_inches='tight')\n\n\n\n#%%\n#%% Temperature effect on Ea\n\n\n\n\n\n\n\n\n\n\n\n\n\n#%%\n\n\n\n\n\n\n\n\n\n\n\n "
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.gca",
"matplotlib.pyplot.tight_layout",
"pandas.read_excel",
"numpy.linspace",
"matplotlib.pyplot.ylim",
"matplotlib.lines.Line2D",
"matplotlib.pyplot.yscale",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.gcf",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.xscale",
"numpy.array",
"matplotlib.pyplot.show",
"scipy.optimize.curve_fit"
]
] |
levozavr/finance-ml
|
[
"efc23e664821861fa03bb91fc94448b6fb14636e"
] |
[
"ml_model/vector_model_mnist.py"
] |
[
"from keras.datasets import mnist\nfrom keras.models import Model\nfrom keras.layers import Input, Dense\nfrom PreProcessors.csv_pre_processor_vector import PreProcessor\nimport matplotlib.pyplot as plt\n\n\nbatch_size = 200\nnum_epochs = 200\nhidden_size = 512\n\nPP = PreProcessor('../index/avg_index.csv')\nPP.start(grade=20)\n\"\"\"\ntrain_x: обучающие данные содержащие в себе вектор 20X1\ntrain_y: обучающие данные(предсказания) содержащие в себе 7-дневные тренды\"\"\"\n\nX_train, Y_train = PP.get_train()\n\"\"\"\ntest_x: тренировачные данные содержащие в себе вектор 20X1\ntest_y: тренировачные данные(предсказания) содержащие в себе 7-дневные тренды\"\"\"\n\nX_test, Y_test = PP.get_test()\n\ninp = Input(shape=(20,))\nhidden_1 = Dense(hidden_size, activation='relu')(inp)\nhidden_2 = Dense(hidden_size, activation='relu')(hidden_1)\nout = Dense(3, activation='softmax')(hidden_2)\n\nmodel = Model(input=inp, output=out)\n\nif __name__ == \"__main__\":\n model.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\n history = model.fit(X_train, Y_train,\n batch_size=batch_size, epochs=num_epochs,\n verbose=1)\n\n scores = model.evaluate(X_test, Y_test, verbose=1)\n\n\n print(\"Точность работы на тестовых данных: %.2f%%\" % (scores[1]*100))\n plt.plot(history.history['acc'])\n plt.show()\n\n"
] |
[
[
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show"
]
] |
tbenthompson/BIE_book
|
[
"dcbbd7f0777ebf4a35d70737643e67138d9d684b"
] |
[
"tectosaur2/hmatrix/toy_aca.py"
] |
[
"import numpy as np\n\n\ndef ACA_plus(\n n_rows,\n n_cols,\n calc_rows,\n calc_cols,\n eps,\n row_dim=3,\n col_dim=3,\n max_iter=None,\n verbose=False,\n Iref0=None,\n Jref0=None,\n):\n \"\"\"\n Run the ACA+ plus algorithm on a matrix implicitly defined by the\n row and column computation functions passed as arguments.\n\n :param n_rows:\n :param n_cols:\n :param calc_rows: A function that accepts two parameters (Istart, Iend)\n specifying the first and last row desired and returns a numpy array\n with shape (Iend-Istart, N_col) with the corresponding rows of the\n input matrix\n :param calc_cols: A function that accepts two parameters (Jstart, Jend)\n specifying the first and last column desired and returns a numpy array\n with shape (N_rows, Jend-Jstart) with the corresponding columns of the\n input matrix\n :param eps: The tolerance of the approximation. The convergence condition is\n in terms of the difference in Frobenius norm between the target matrix\n and the approximation\n :param max_iter:\n :param verbose: Should we print information at each iteration. Just included\n for demonstration here.\n\n :return U_ACA: The left-hand approximation matrix.\n :return V_ACA: The right-hand approximation matrix.\n \"\"\"\n\n us = [] # The left vectors of the approximation\n vs = [] # The right vectors of the approximation\n prevIstar = [] # Previously used i^* pivots\n prevJstar = [] # Previously used j^* pivots\n\n # a quick helper function that will help find the largest entry in\n # an array while excluding some list of `disallowed` entries.\n def argmax_not_in_list(arr, disallowed):\n arg_sorted = arr.argsort()\n max_idx = arg_sorted.shape[0] - 1\n while True:\n if arg_sorted[max_idx] in disallowed:\n max_idx -= 1\n else:\n break\n return arg_sorted[max_idx]\n\n # A function that will return a contiguous block of rows of the\n # residual matrix\n def calc_residual_rows(Istart, Iend):\n # First calculate the rows of the original matrix.\n out = calc_rows(Istart, Iend).copy()\n # Then subtract the current terms of the approximation\n for i in range(len(us)):\n out -= us[i][Istart:Iend][:, None] * vs[i][None, :]\n return out\n\n # See above, except this function calculates a block of columns.\n def calc_residual_cols(Jstart, Jend):\n out = calc_cols(Jstart, Jend).copy()\n for i in range(len(us)):\n out -= vs[i][Jstart:Jend][None, :] * us[i][:, None]\n return out\n\n # A function for finding a reference row and updating\n # it with respect to the already constructed approximation.\n def reset_reference_row(Iref):\n # When a row gets used in the approximation, we will need to\n # reset to use a different reference row. Just, increment!\n while True:\n Iref = (Iref + row_dim) % n_rows\n Iref -= Iref % row_dim\n if Iref not in prevIstar:\n break\n\n # Grab the \"row\" (actually three rows corresponding to the\n # x, y, and z components for a single observation point)\n return calc_residual_rows(Iref, Iref + row_dim), Iref\n\n # Same function as above but for the reference column\n def reset_reference_col(Jref):\n while True:\n Jref = (Jref + col_dim) % n_cols\n Jref -= Jref % col_dim\n if Jref not in prevJstar:\n break\n\n return calc_residual_cols(Jref, Jref + col_dim), Jref\n\n # If we haven't converged before running for max_iter, we'll stop anyway.\n if max_iter is None:\n max_iter = np.min([n_rows, n_cols])\n else:\n max_iter = np.min([n_rows, n_cols, max_iter])\n\n # Create a buffer for storing the R_{i^*,j} and R_{i, j^*}\n RIstar = np.zeros(n_cols)\n RJstar = np.zeros(n_rows)\n\n # Choose our starting random reference row and column.\n # These will get incremented by row_dim/col_dim inside reset_reference_row\n # so pre-subtract that.\n Iref = Iref0\n if Iref is None:\n Iref = np.random.randint(n_rows)\n Iref -= row_dim\n Jref = Jref0\n if Jref is None:\n Jref = np.random.randint(n_cols)\n Jref -= col_dim\n\n # And collect the corresponding blocks of rows/columns\n RIref, Iref = reset_reference_row(Iref)\n RJref, Jref = reset_reference_col(Jref)\n\n for k in range(max_iter):\n if verbose:\n print(Iref, RIref[0, :5])\n print(Jref, RJref[:5, 0])\n\n # These two lines find the column in RIref with the largest entry (step 1 above).\n maxabsRIref = np.max(np.abs(RIref), axis=0)\n Jstar = argmax_not_in_list(maxabsRIref, prevJstar)\n\n # And these two find the row in RJref with the largest entry (step 1 above).\n maxabsRJref = np.max(np.abs(RJref), axis=1)\n Istar = argmax_not_in_list(maxabsRJref, prevIstar)\n\n # Check if we should pivot first based on row or based on column (step 2 above)\n Jstar_val = maxabsRIref[Jstar]\n Istar_val = maxabsRJref[Istar]\n if Istar_val > Jstar_val:\n # If we pivot first on the row, then calculate the corresponding row\n # of the residual matrix.\n RIstar[:] = calc_residual_rows(Istar, Istar + 1)[0]\n\n # Then find the largest entry in that row vector to identify which\n # column to pivot on. (See step 3 above)\n Jstar = argmax_not_in_list(np.abs(RIstar), prevJstar)\n\n # Calculate the corresponding residual column!\n RJstar[:] = calc_residual_cols(Jstar, Jstar + 1)[:, 0]\n else:\n # If we pivot first on the column, then calculate the corresponding column\n # of the residual matrix.\n RJstar[:] = calc_residual_cols(Jstar, Jstar + 1)[:, 0]\n\n # Then find the largest entry in that row vector to identify which\n # column to pivot on. (See step 3 above)\n Istar = argmax_not_in_list(np.abs(RJstar), prevIstar)\n\n # Calculate the corresponding residual row!\n RIstar[:] = calc_residual_rows(Istar, Istar + 1)[0]\n\n # Record the pivot row and column so that we don't re-use them.\n prevIstar.append(Istar)\n prevJstar.append(Jstar)\n\n # Add the new rank-1 outer product to the approximation (see step 4 above)\n vs.append(RIstar / RIstar[Jstar])\n us.append(RJstar.copy())\n\n # How \"large\" was this update to the approximation?\n step_size = np.sqrt(np.sum(us[-1] ** 2) * np.sum(vs[-1] ** 2))\n if verbose:\n print(\n f\"pivot row={Istar:4d}, pivot col={Jstar:4d}, \"\n f\"step size={step_size:1.3e}, \"\n f\"tolerance={eps:1.3e}\"\n )\n\n # The convergence criteria will simply be whether the Frobenius norm of the\n # step is smaller than the user provided tolerance.\n if step_size < eps:\n break\n\n # We also break here if this is the last iteration to avoid wasting effort\n # updating the reference row/column\n if k == max_iter - 1:\n break\n\n # If we didn't converge, let's prep the reference residual row and\n # column for the next iteration:\n\n # If we pivoted on the reference row, then choose a new reference row.\n # Remember that we are using a x,y,z vector \"row\" or\n # set of row_dim rows in an algebraic sense.\n if Iref <= Istar < Iref + row_dim:\n RIref, Iref = reset_reference_row(Iref)\n else:\n # If we didn't change the reference row of the residual matrix \"R\",\n # update the row to account for the new components of the approximation.\n RIref -= us[-1][Iref : Iref + row_dim][:, None] * vs[-1][None, :]\n\n # If we pivoted on the reference column, then choose a new reference column.\n # Remember that we are using a x,y,z vector \"column\" or\n # set of col_dim columns in an algebraic sense.\n if Jref <= Jstar < Jref + col_dim:\n RJref, Jref = reset_reference_col(Jref)\n else:\n # If we didn't change the reference column of the residual matrix \"R\",\n # update the column to account for the new components of the approximation.\n RJref -= vs[-1][Jref : Jref + col_dim][None, :] * us[-1][:, None]\n\n # Return the left and right approximation matrices.\n # The approximate is such that:\n # M ~ U_ACA.dot(V_ACA)\n U_ACA = np.array(us).T\n V_ACA = np.array(vs)\n\n return U_ACA, V_ACA\n\n\ndef SVD_recompress(U_ACA, V_ACA, eps):\n \"\"\"\n Recompress an ACA matrix approximation via SVD.\n\n :param U_ACA: The left-hand approximation matrix.\n :param V_ACA: The right-hand approximation matrix.\n :param eps: The tolerance of the approximation. The convergence condition is\n in terms of the difference in Frobenius norm between the target matrix\n and the approximation.\n\n :return U_SVD: The SVD recompressed left-hand approximation matrix.\n :return V_SVD: The SVD recompressed right-hand approximation matrix.\n \"\"\"\n UQ, UR = np.linalg.qr(U_ACA)\n VQ, VR = np.linalg.qr(V_ACA.T)\n W, SIG, Z = np.linalg.svd(UR.dot(VR.T))\n\n frob_K = np.sqrt(np.cumsum(SIG[::-1] ** 2))[::-1]\n r = np.argmax(frob_K < eps)\n\n U = UQ.dot(W[:, :r] * SIG[:r])\n V = Z[:r, :].dot(VQ.T)\n return U, V\n"
] |
[
[
"numpy.abs",
"numpy.min",
"numpy.cumsum",
"numpy.argmax",
"numpy.linalg.qr",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"numpy.random.randint"
]
] |
Lucas-BLP/ScriptProfilerPy
|
[
"21a243629bb4f13e1b39e87a509bc9677df82694"
] |
[
"example_testfile_STP_test.py"
] |
[
"import pandas as pd\n\nfrom datetime import datetime\nimport shutil\nfrom speed_testpy import ScriptProfilerPy\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import LinearLocator\nspeed_test_restime = []\nspeed_test_lines = []\nspeedtest_startimefile = datetime.now()\nglobal speedtest_startime\nspeedtest_startime = datetime.now()\ndef STP_check(passed_line, speedtest_startime):\n speed_test_restime.append((datetime.now()-speedtest_startime).total_seconds())\n speed_test_lines.append(passed_line)\n speedtest_startime = datetime.now()\nimport numpy as np\nSTP_check(1, speedtest_startime)\nspeedtest_startime = datetime.now()\nimport matplotlib.pyplot as plt\nSTP_check(2, speedtest_startime)\nspeedtest_startime = datetime.now()\n# This file will be use for the speedtest\nSTP_check(3, speedtest_startime)\nspeedtest_startime = datetime.now()\nts = pd.Series(np.random.randn(1000),\n index=pd.date_range(\"1/1/2000\", periods=1000))\nts\nts = np.exp(ts.cumsum())\nSTP_check(10, speedtest_startime)\nspeedtest_startime = datetime.now()\ndf = pd.DataFrame(np.random.randn(1000, 4),\n index=ts.index, columns=list(\"ABCD\"))\ndf\ndf.head()\nSTP_check(16, speedtest_startime)\nspeedtest_startime = datetime.now()\ndf.head()\nSTP_check(17, speedtest_startime)\nspeedtest_startime = datetime.now()\nfor i in df.index:\n df.tail()\ndf.head()\ndf.head()\nSTP_check(21, speedtest_startime)\nspeedtest_startime = datetime.now()\ndf.tail()\nSTP_check(22, speedtest_startime)\nspeedtest_startime = datetime.now()\ndf.head()\nSTP_check(23, speedtest_startime)\nspeedtest_startime = datetime.now()\ndf.head()\nSTP_check(25, speedtest_startime)\nspeedtest_startime = datetime.now()\ndf.tail()\nSTP_check(27, speedtest_startime)\nspeedtest_startime = datetime.now()\nfor i in df.index:\n df.tail()\ndf.tail()\ndf.tail()\nSTP_check(32, speedtest_startime)\nspeedtest_startime = datetime.now()\nfor i in df.index:\n df.tail()\nts = pd.Series(np.random.randn(1000),\n index=pd.date_range(\"1/1/2000\", periods=1000))\nts\nts = np.exp(ts.cumsum())\nSTP_check(54, speedtest_startime)\nspeedtest_startime = datetime.now()\ndf = pd.DataFrame(np.random.randn(1000, 4),\n index=ts.index, columns=list(\"ABCD\"))\ndf\ndf.head()\nSTP_check(58, speedtest_startime)\nspeedtest_startime = datetime.now()\ndf.head()\nSTP_check(59, speedtest_startime)\nspeedtest_startime = datetime.now()\ndf.head()\nSTP_check(60, speedtest_startime)\nspeedtest_startime = datetime.now()\ndf.head()\nSTP_check(61, speedtest_startime)\nspeedtest_startime = datetime.now()\ndf.head()\nSTP_check(62, speedtest_startime)\nspeedtest_startime = datetime.now()\ndf.head()\nSTP_check(63, speedtest_startime)\nspeedtest_startime = datetime.now()\nfor i in df.index:\n df.tail()\ndf.head()\ndf.head()\nSTP_check(67, speedtest_startime)\nspeedtest_startime = datetime.now()\ndf.tail()\nSTP_check(68, speedtest_startime)\nspeedtest_startime = datetime.now()\nfor i in df.index:\n df.tail()\ndf.tail()\ndf.tail()\nSTP_check(72, speedtest_startime)\nspeedtest_startime = datetime.now()\nfor i in df.index:\n df.tail()\nts = pd.Series(np.random.randn(1000),\n index=pd.date_range(\"1/1/2000\", periods=1000))\nts\nts = np.exp(ts.cumsum())\nSTP_check(78, speedtest_startime)\nspeedtest_startime = datetime.now()\ndf = pd.DataFrame(np.random.randn(1000, 4),\n index=ts.index, columns=list(\"ABCD\"))\ndf\ndf.head()\nSTP_check(82, speedtest_startime)\nspeedtest_startime = datetime.now()\ndf.head()\nSTP_check(83, speedtest_startime)\nspeedtest_startime = datetime.now()\nfor i in df.index:\n df.tail()\ndf.head()\ndf.head()\nSTP_check(87, speedtest_startime)\nspeedtest_startime = datetime.now()\ndf.tail()\nSTP_check(88, speedtest_startime)\nspeedtest_startime = datetime.now()\nfor i in df.index:\n df.tail()\ndf.tail()\ndf.tail()\nSTP_check(92, speedtest_startime)\nspeedtest_startime = datetime.now()\nfor i in df.index:\n df.tail()\nts = pd.Series(np.random.randn(1000),\n index=pd.date_range(\"1/1/2000\", periods=1000))\nts\nts = np.exp(ts.cumsum())\nSTP_check(98, speedtest_startime)\nspeedtest_startime = datetime.now()\ndf = pd.DataFrame(np.random.randn(1000, 4),\n index=ts.index, columns=list(\"ABCD\"))\ndf\ndf.head()\nSTP_check(102, speedtest_startime)\nspeedtest_startime = datetime.now()\ndf.head()\nSTP_check(103, speedtest_startime)\nspeedtest_startime = datetime.now()\nfor i in df.index:\n df.tail()\ndf.head()\ndf.head()\nSTP_check(107, speedtest_startime)\nspeedtest_startime = datetime.now()\ndf.tail()\nSTP_check(108, speedtest_startime)\nspeedtest_startime = datetime.now()\nfor i in df.index:\n df.tail()\ndf.tail()\ndf.tail()\nSTP_check(112, speedtest_startime)\nspeedtest_startime = datetime.now()\nfor i in df.index:\n df.tail()\n\nplt.figure()\nx = speed_test_lines[::-1]\nrestime = speed_test_restime[::-1]\nx_pos = [i for i, _ in enumerate(x)]\nplt.barh(x_pos, restime, color='green')\ntimerun = np.round((speedtest_startime - speedtest_startimefile).total_seconds(),3)\nplt.ylabel('Code Lines')\nplt.yticks(fontsize=8)\nplt.xlabel(f\"Time (seconds), Script execution: {timerun}'s\")\nplt.title('Code profile')\nplt.yticks(x_pos, x)\nplt.show()\n"
] |
[
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.barh",
"numpy.random.randn",
"pandas.date_range",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] |
amazon-picking-challenge/team_pfn
|
[
"2f76524b067d816d8407f6c4fae4e6d33939c024"
] |
[
"script/coord_transformer.py"
] |
[
"#!/usr/bin/env python\n\n# Copyright 2016 Preferred Networks, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# node name 'coord_transformer'\n# provide 4 services 'forget_calibration', 'update_calibration', 'global2bin' and 'bin2global'\nimport numpy as np\nimport math\nimport conv_bin_coord\nimport rospy\nfrom std_msgs.msg import Bool\nfrom std_msgs.msg import String\nfrom geometry_msgs.msg import Twist, Vector3, Point\nfrom apc2016.srv import *\nfrom apc2016.msg import FanucTwist\nfrom util import camera_to_global, camera_to_global_right, camera_to_global_right_all\n\nclass coordinate_transform:\n def __init__(self):\n self.is_calibrated = False\n self.point_1 = np.asarray([1250,40,1057])\n self.point_2 = np.asarray([1250,-830,1057])\n self.service_f = rospy.Service('forget_calibration', Success, self.forget_calibration)\n self.service_u = rospy.Service('update_calibration', CalibrationUpdate, self.update_calibration)\n self.service_c = rospy.Service('check_is_calibrated', CalibData, self.check_is_calibration)\n self.service_b = rospy.Service('bin2global', CoordinateTransform, self.bin2global)\n self.service_g = rospy.Service('global2bin', CoordinateTransform, self.global2bin)\n self.service_a = rospy.Service('adjustglobal', CoordinateTransform, self.adjustglobal)\n self.service_c2g = rospy.Service('camera2global', CameraCoordinateTransform, self.camera2global)\n self.service_c2g = rospy.Service('camera2global_right', CameraCoordinateTransform, self.camera2global_right)\n self.service_c2ga = rospy.Service('camera2global_right_all', CameraCoordinateTransformAll, self.camera2global_right_all)\n self.c = conv_bin_coord.conv_bin_coord()\n def forget_calibration(self, req):\n self.is_calibrated = False\n return SuccessResponse(success=True)\n\n def check_is_calibration(self, req):\n if self.is_calibrated == True:\n p_1 = Point(self.point_1[0],self.point_1[1],self.point_1[2])\n p_2 = Point(self.point_2[0],self.point_2[1],self.point_2[2])\n else:\n p_1 = Point(0,0,0)\n p_2 = Point(0,0,0)\n return CalibDataResponse(success=self.is_calibrated, upper_left = p_1, upper_right = p_2)\n\n def update_calibration(self, req):\n self.point_1[0] = req.upper_left.x\n self.point_1[1] = req.upper_left.y\n self.point_1[2] = req.upper_left.z\n self.point_2[0] = req.upper_right.x\n self.point_2[1] = req.upper_right.y\n self.point_2[2] = req.upper_right.z\n self.is_calibrated = True\n return CalibrationUpdateResponse(success=True)\n\n def bin2global(self, req):\n if req.bin not in ['bin_' + j for j in 'ABCDEFGHIJKL']:\n rospy.loginfo('Invalid bin name')\n return CoordinateTransformResponse(point = req.point, is_calibrated = self.is_calibrated, success=False)\n \n if self.is_calibrated == False:\n return CoordinateTransformResponse(point = req.point, is_calibrated = self.is_calibrated, success=False)\n\n point = self.c.conv_from_bin_coord_to_global_coord(self.twist2array(req.point), req.bin, self.point_1, self.point_2)\n return CoordinateTransformResponse(point = self.array2twist(point), is_calibrated = self.is_calibrated, success=True)\n\n def global2bin(self, req):\n if req.bin not in ['bin_' + j for j in 'ABCDEFGHIJKL']:\n rospy.loginfo('Invalid bin name')\n return CoordinateTransformResponse(point = req.point, is_calibrated = self.is_calibrated, success=False)\n \n point = self.c.conv_to_bin_coord_from_global_coord(self.twist2array(req.point), req.bin, self.point_1, self.point_2)\n return CoordinateTransformResponse(point = self.array2twist(point), is_calibrated = self.is_calibrated, success=True)\n \n def camera2global(self, req):\n ret = np.zeros(6).astype('f')\n ret[:3] = camera_to_global(self.twist2array(req.point)[:3], self.twist2array(req.xyzwpr))\n return CameraCoordinateTransformResponse(point = self.array2twist(ret))\n \n \n def camera2global_right(self, req):\n ret = np.zeros(6).astype('f')\n ret[:3] = camera_to_global_right(self.twist2array(req.point)[:3], self.twist2array(req.xyzwpr))\n return CameraCoordinateTransformResponse(point = self.array2twist(ret))\n \n def camera2global_right_all(self, req):\n n = len(req.x)\n rospy.loginfo(\"camera2global_right_all called, len = %d\"%n)\n points = np.zeros((3, n)).astype(\"f\")\n points[0,:] = req.x\n points[1,:] = req.y\n points[2,:] = req.z\n ret = camera_to_global_right(points, self.twist2array(req.xyzwpr))\n rospy.loginfo(\"camera2global_right_all finished\")\n return CameraCoordinateTransformAllResponse(x = ret[0,:].tolist(), y = ret[1,:].tolist(), z = ret[2,:].tolist())\n \n \n def adjustglobal(self,req):\n point = self.c.adjustglobal(self.twist2array(req.point), self.point_1, self.point_2)\n return CoordinateTransformResponse(point = self.array2twist(point), is_calibrated = self.is_calibrated, success=True)\n\n def twist2array(self,t):\n return np.asarray( [t.linear.x, t.linear.y, t.linear.z, t.angular.x, t.angular.y, t.angular.z])\n\n def array2twist(self,t):\n return Twist(Vector3(t[0],t[1],t[2]), Vector3(t[3],t[4],t[5]))\nif __name__ == \"__main__\":\n rospy.init_node('coord_transformer')\n coordinate_transform()\n rospy.spin()\n"
] |
[
[
"numpy.asarray",
"numpy.zeros"
]
] |
patrick-ubc/Huawei_HiFly_Drone
|
[
"5dae1b56f49c2b86c3b852bbc5e3a63e84ccd490"
] |
[
"ros_atlas/handProcessor.py"
] |
[
"import sys\nimport time\nimport numpy as np\nimport rospy\n\nsys.path.append(\"lib/\")\n\nfrom core.BasePostprocessor import Postprocessor\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom rospy.exceptions import ROSException, ROSSerializationException, ROSInterruptException\n\nclass HandPostprocessNode(Postprocessor):\n def __init__(self):\n super().__init__()\n \n def deconstruct_ros_msg(self, msg):\n array_1 = np.array(msg.array1.list)\n array_2 = np.reshape(np.array(msg.array2.list), (1, 10))\n array_3 = np.reshape(np.array(msg.array3.list), (1, 10))\n array_4 = np.reshape(np.array(msg.array4.list), (1, 10, 4))\n return [array_1, array_2, array_3, array_4]\n \n def run(self, processor, img_format):\n while not rospy.is_shutdown():\n st = time.time()\n if not self.message_queue.empty():\n try:\n message = self.message_queue.get()\n model_output = self.deconstruct_ros_msg(message)\n frame = CvBridge().imgmsg_to_cv2(message.img)\n\n postprocessed = processor.postprocess(frame=frame, outputs=model_output) \n\n # Publish postprocess image for visualization\n postprocessed = CvBridge().cv2_to_imgmsg(postprocessed, img_format)\n self.postprocess_pub.publish(postprocessed)\n self.pub_counter += 1\n rospy.loginfo(f\"[{self.pub_counter}]: Published postprocess output to {self._postprocess_topic}\")\n\n self.postprocess_pub_rate.sleep() \n self._iteration_times.append(time.time() - st) \n \n except CvBridgeError as err:\n rospy.logerr(\"Ran into exception when converting Image type with CvBridge.\")\n raise err\n except ROSSerializationException as err:\n rospy.logerr(\"Ran into exception when serializing message for publish. See error below:\")\n raise err\n except ROSException as err:\n raise err\n except ROSInterruptException as err:\n rospy.loginfo(\"ROS Interrupt.\")\n raise err\n else:\n continue\n\nif __name__ == \"__main__\":\n hand_postprocess_node = HandPostprocessNode()\n hd_processor = hand_postprocess_node.load_processor(model_name=\"hand_detection\")\n hand_postprocess_node.init()\n try:\n hand_postprocess_node.run(hd_processor, 'rgb8')\n except KeyboardInterrupt as e:\n rospy.signal_shutdown(\"Shutting down Postprocessor. Keyboard terminate\")"
] |
[
[
"numpy.array"
]
] |
misaka3/generativemagic
|
[
"58f24a9fd95c94828281ed6c1267d570ee7c7b10"
] |
[
"generativemagic/effects/simple_effects.py"
] |
[
"import numpy as np\n\nfrom generativemagic.effect import Effect, DECK_TOP\n\n\nclass InjectAt(Effect):\n \"\"\"Injects a chosen cards at the top or bottom of the deck.\n This is a simple palming or putting the deck on top of the chosen cards.\n\n Why does it not allow to put anywhere? Because this is a simple movement to put on top or bottom.\"\"\"\n\n def __init__(self, at: int):\n self.__at = at\n\n def apply(self, sequence, chosen=None):\n if self.__at == DECK_TOP:\n return np.insert(sequence, 0, chosen)\n return np.insert(sequence, len(sequence), chosen)\n\n def __repr__(self):\n return f\"InjectAt({self.__at})\"\n"
] |
[
[
"numpy.insert"
]
] |
crazydemo/Progressive-Multi-stage-Feature-Mix-for-Person-Re-Identification
|
[
"e451c30ee5ac8dffa0f043f06cf26d2992a89294"
] |
[
"models/progressive_networks.py"
] |
[
"# encoding: utf-8\nimport copy\nimport itertools\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport torch.utils.model_zoo as model_zoo\nimport random\nfrom scipy.spatial.distance import cdist\nfrom sklearn.preprocessing import normalize\nfrom torch import nn, optim\nfrom torch.utils.data import dataloader\nfrom torchvision import transforms\nfrom torchvision.models.resnet import Bottleneck, resnet50\nfrom torchvision.transforms import functional\n\nfrom .resnet import ResNet\n\n\ndef weights_init_kaiming(m):\n classname = m.__class__.__name__\n if classname.find('Linear') != -1:\n nn.init.kaiming_normal_(m.weight, a=0, mode='fan_out')\n nn.init.constant_(m.bias, 0.0)\n elif classname.find('Conv') != -1:\n nn.init.kaiming_normal_(m.weight, a=0, mode='fan_in')\n if m.bias is not None:\n nn.init.constant_(m.bias, 0.0)\n elif classname.find('BatchNorm') != -1:\n if m.affine:\n nn.init.normal_(m.weight, 1.0, 0.02)\n nn.init.constant_(m.bias, 0.0)\n\n\ndef weights_init_classifier(m):\n classname = m.__class__.__name__\n if classname.find('Linear') != -1:\n nn.init.normal_(m.weight, std=0.001)\n if m.bias:\n nn.init.constant_(m.bias, 0.0)\n\n\nclass SELayer(nn.Module):\n def __init__(self, channel, reduction=16):\n super(SELayer, self).__init__()\n self.avg_pool = nn.AdaptiveAvgPool2d(1)\n self.fc = nn.Sequential(\n nn.Linear(channel, channel // reduction),\n nn.ReLU(inplace=True),\n nn.Linear(channel // reduction, channel),\n nn.Sigmoid()\n )\n\n def forward(self, x):\n b, c, _, _ = x.size()\n y = self.avg_pool(x).view(b, c)\n y = self.fc(y).view(b, c, 1, 1)\n return x * y\n\n\nclass ResNetBuilder(nn.Module):\n in_planes = 2048\n\n def __init__(self, num_classes=None, last_stride=1, pretrained=False):\n super().__init__()\n self.base = ResNet(last_stride)\n if pretrained:\n model_url = 'https://download.pytorch.org/models/resnet50-19c8e357.pth'\n self.base.load_param(model_zoo.load_url(model_url))\n\n self.num_classes = num_classes\n if num_classes is not None:\n self.bottleneck = nn.Sequential(\n nn.Linear(self.in_planes, 512),\n nn.BatchNorm1d(512),\n nn.LeakyReLU(0.1),\n nn.Dropout(p=0.5)\n )\n self.bottleneck.apply(weights_init_kaiming)\n self.classifier = nn.Linear(512, self.num_classes)\n self.classifier.apply(weights_init_classifier)\n\n def forward(self, x):\n global_feat = self.base(x)\n global_feat = F.avg_pool2d(global_feat, global_feat.shape[2:]) # (b, 2048, 1, 1)\n global_feat = global_feat.view(global_feat.shape[0], -1)\n if self.training and self.num_classes is not None:\n feat = self.bottleneck(global_feat)\n cls_score = self.classifier(feat)\n return [global_feat], [cls_score]\n else:\n return global_feat\n\n def get_optim_policy(self):\n base_param_group = self.base.parameters()\n if self.num_classes is not None:\n add_param_group = itertools.chain(self.bottleneck.parameters(), self.classifier.parameters())\n return [\n {'params': base_param_group},\n {'params': add_param_group}\n ]\n else:\n return [\n {'params': base_param_group}\n ]\n\n\nclass CutMixBatchDrop(nn.Module):\n def __init__(self, h_ratio, w_ratio):\n super(CutMixBatchDrop, self).__init__()\n self.h_ratio = h_ratio\n self.w_ratio = w_ratio\n\n def forward(self, x, cam, y, step, k, randy=None):\n '''\n :param x: feature map with shape[N,2048,24,8]\n :param cam: grad cam map with shape[N,24,8]\n :param y: gt of x, [N,1]\n :return: x_new = mask*x1 + (1-mask)*x2\n '''\n if self.training:\n bs, c, h, w = x.size()\n mask = torch.ones(x.size()).cuda()\n\n '''get mask'''\n _, f_h, f_w = cam.size()\n cam_patchs_row = torch.split(cam, step[0], 1)\n patchs_row = torch.stack(cam_patchs_row, 1)\n cam_patchs_col = torch.split(patchs_row, step[1], 3)\n patchs_col = torch.cat(cam_patchs_col, 1)\n patchs = patchs_col.sum(dim=[2, 3]) # N*12\n patchs, patchs_idxs = patchs.sort(1, True)\n\n for i in range(bs):\n for idx in patchs_idxs[i, 0:k]:\n if idx < 8:\n mask[i, :, idx * step[0]:idx * step[0] + step[0], 0:2] = 0\n elif idx < 16:\n mask[i, :, (idx - 8) * step[0]:(idx - 8) * step[0] + step[0], 2:4] = 0\n elif idx < 24:\n mask[i, :, (idx - 16) * step[0]:(idx - 16) * step[0] + step[0], 4:6] = 0\n else:\n mask[i, :, (idx - 24) * step[0]:(idx - 24) * step[0] + step[0], 6:8] = 0\n\n '''CutMix'''\n lamda = k * step[0] * step[1] / (h * w)\n bs, c, h, w = x.size()\n if randy is not None:\n rand_idx = randy\n y2 = y[randy]\n else:\n idx = list(range(bs))\n rand_idx = []\n for i in range(bs // 4):\n idx_part = idx[i * 4:(i + 1) * 4]\n temp = list(set(idx) - set(idx_part))\n rand_idx += [random.choice(temp) for k in range(4)]\n x2 = x[rand_idx, :, :, :]\n x_new = (mask * x + (torch.ones(mask.size()).cuda() - mask) * x2)\n return x_new, rand_idx, lamda\n\n\nclass GetGrad():\n def __init__(self):\n pass\n\n def get_grad(self, grad):\n self.grad = grad\n\n def __call__(self, x):\n x.register_hook(self.get_grad)\n\n\n\ndef gradCAM(gradfeature, scores, idxs):\n getGrad = GetGrad()\n getGrad(gradfeature)\n feature = gradfeature.detach()\n bs, c, h, w = feature.size()\n output_gradCam = []\n if torch.cuda.is_available():\n score = torch.tensor(0, dtype=torch.float).cuda()\n else:\n score = torch.tensor(0, dtype=torch.float)\n for i in range(bs):\n score += scores[i, idxs[i]]\n\n score.backward(retain_graph=True)\n grad = getGrad.grad.detach()\n\n weight = grad.mean(2)\n weight = weight.mean(2)\n cam_cv = []\n for i in range(bs):\n grad_cam = weight[i].reshape(1, c).mm(feature[i].reshape((c, h * w)))\n grad_cam = grad_cam.reshape(h, w)\n grad_cam = F.relu(grad_cam)\n output_gradCam.append(grad_cam)\n\n cam_img = grad_cam.cpu().detach().numpy()\n cam_img = cam_img - np.min(cam_img)\n cam_img = cam_img / np.max(cam_img)\n cam_img = np.uint8(255 * cam_img)\n cam_cv.append(cam_img)\n cam_cv = np.array(cam_cv)\n output_gradCam = torch.stack(output_gradCam, dim=0)\n return output_gradCam, cam_cv\n\n\nclass BFE(nn.Module):\n def __init__(self, num_classes, width_ratio=0.5, height_ratio=0.5):\n super(BFE, self).__init__()\n resnet = resnet50(pretrained=True)\n self.backbone = nn.Sequential(\n resnet.conv1,\n resnet.bn1,\n resnet.relu,\n resnet.maxpool,\n resnet.layer1, # res_conv2\n resnet.layer2, # res_conv3\n resnet.layer3, # res_conv4\n )\n self.res_part = nn.Sequential(\n Bottleneck(1024, 512, stride=1, downsample=nn.Sequential(\n nn.Conv2d(1024, 2048, kernel_size=1, stride=1, bias=False),\n nn.BatchNorm2d(2048),\n )),\n Bottleneck(2048, 512),\n Bottleneck(2048, 512),\n )\n self.res_part.load_state_dict(resnet.layer4.state_dict())\n reduction = nn.Sequential(\n nn.Conv2d(2048, 512, 1),\n nn.BatchNorm2d(512),\n nn.ReLU()\n )\n # stage 1\n self.global_avgpool = nn.AdaptiveAvgPool2d((1, 1))\n self.global_softmax = nn.Linear(512, num_classes)\n self.global_softmax.apply(weights_init_kaiming)\n self.global_reduction = copy.deepcopy(reduction)\n self.global_reduction.apply(weights_init_kaiming)\n\n # stage 2\n self.res_part2 = Bottleneck(2048, 512)\n self.part_maxpool = nn.AdaptiveMaxPool2d((1, 1))\n\n # stage 2\n self.cutmix_batch_drop1 = CutMixBatchDrop(height_ratio, width_ratio)\n self.reduction1 = nn.Sequential(\n nn.Linear(2048, 512, 1),\n nn.BatchNorm1d(512),\n nn.ReLU()\n )\n self.reduction1.apply(weights_init_kaiming)\n self.softmax1 = nn.Linear(512, num_classes)\n self.softmax1.apply(weights_init_kaiming)\n\n # stage 3\n self.cutmix_batch_drop2 = CutMixBatchDrop(height_ratio, width_ratio)\n self.reduction2 = nn.Sequential(\n nn.Linear(2048, 512, 1),\n nn.BatchNorm1d(512),\n nn.ReLU()\n )\n self.reduction2.apply(weights_init_kaiming)\n self.softmax2 = nn.Linear(512, num_classes)\n self.softmax2.apply(weights_init_kaiming)\n\n def forward(self, x, y=None):\n \"\"\"\n :param x: input image tensor of (N, C, H, W)\n :return: (prediction, triplet_losses, softmax_losses)\n \"\"\"\n x = self.backbone(x)\n x = self.res_part(x)\n\n predict = []\n triplet_features = []\n softmax_features = []\n\n # stage 1\n glob = self.global_avgpool(x)\n global_triplet_feature = self.global_reduction(glob).squeeze()\n global_softmax_class = self.global_softmax(global_triplet_feature)\n softmax_features.append(global_softmax_class)\n triplet_features.append(global_triplet_feature)\n predict.append(global_triplet_feature)\n\n # stage 2\n x_part = self.res_part2(x)\n x_part1 = x_part\n x_part2 = x_part\n\n # stage 2\n if self.training:\n gradcam, _ = gradCAM(x, global_softmax_class, y)\n x_part1, idx_cutmix1, lamda = self.cutmix_batch_drop1(x_part1, gradcam, y, [3, 2], 3)\n cutmix1_triplet_feature = self.part_maxpool(x_part1).squeeze() # N*2048\n cutmix1_feature = self.reduction1(cutmix1_triplet_feature) # N*1024\n cutmix1_softmax_feature = self.softmax1(cutmix1_feature) # N*num_class/751\n triplet_features.append(cutmix1_feature)\n softmax_features.append(cutmix1_softmax_feature)\n predict.append(cutmix1_feature)\n\n # stage 3\n if self.training:\n gradcam, _ = gradCAM(x_part1, cutmix1_softmax_feature, y)\n x_part2, idx_cutmix2, lamda = self.cutmix_batch_drop1(x_part2, gradcam, y, [3, 2], 3)\n cutmix2_triplet_feature = self.part_maxpool(x_part2).squeeze() # N*2048\n cutmix2_feature = self.reduction2(cutmix2_triplet_feature) # N*1024\n cutmix2_softmax_feature = self.softmax2(cutmix2_feature) # N*num_class/751\n triplet_features.append(cutmix2_feature)\n softmax_features.append(cutmix2_softmax_feature)\n predict.append(cutmix2_feature)\n\n if self.training:\n return triplet_features, softmax_features\n else:\n return torch.cat(predict, 1)\n\n def get_optim_policy(self):\n params = [\n {'params': self.backbone.parameters()},\n {'params': self.res_part.parameters()},\n {'params': self.global_reduction.parameters()},\n {'params': self.global_softmax.parameters()},\n {'params': self.res_part2.parameters()},\n {'params': self.reduction1.parameters()},\n {'params': self.softmax1.parameters()},\n {'params': self.reduction2.parameters()},\n {'params': self.softmax2.parameters()},\n ]\n return params\n\n\nclass Resnet(nn.Module):\n def __init__(self, num_classes, resnet=None):\n super(Resnet, self).__init__()\n if not resnet:\n resnet = resnet50(pretrained=True)\n self.backbone = nn.Sequential(\n resnet.conv1,\n resnet.bn1,\n resnet.relu,\n resnet.maxpool,\n resnet.layer1, # res_conv2\n resnet.layer2, # res_conv3\n resnet.layer3, # res_conv4\n resnet.layer4\n )\n self.global_avgpool = nn.AdaptiveAvgPool2d((1, 1))\n self.softmax = nn.Linear(2048, num_classes)\n\n def forward(self, x):\n \"\"\"\n :param x: input image tensor of (N, C, H, W)\n :return: (prediction, triplet_losses, softmax_losses)\n \"\"\"\n x = self.backbone(x)\n\n x = self.global_avgpool(x).squeeze()\n feature = self.softmax(x)\n if self.training:\n return [], [feature]\n else:\n return feature\n\n def get_optim_policy(self):\n return self.parameters()\n\n\nclass IDE(nn.Module):\n def __init__(self, num_classes, resnet=None):\n super(IDE, self).__init__()\n if not resnet:\n resnet = resnet50(pretrained=True)\n self.backbone = nn.Sequential(\n resnet.conv1,\n resnet.bn1,\n resnet.relu,\n resnet.maxpool,\n resnet.layer1, # res_conv2\n resnet.layer2, # res_conv3\n resnet.layer3, # res_conv4\n resnet.layer4\n )\n self.global_avgpool = nn.AvgPool2d(kernel_size=(12, 4))\n\n def forward(self, x):\n \"\"\"\n :param x: input image tensor of (N, C, H, W)\n :return: (prediction, triplet_losses, softmax_losses)\n \"\"\"\n x = self.backbone(x)\n\n feature = self.global_avgpool(x).squeeze()\n if self.training:\n return [feature], []\n else:\n return feature\n\n def get_optim_policy(self):\n return self.parameters()"
] |
[
[
"torch.cat",
"numpy.max",
"torch.cuda.is_available",
"torch.split",
"torch.utils.model_zoo.load_url",
"torch.nn.AdaptiveMaxPool2d",
"torch.nn.Dropout",
"numpy.uint8",
"torch.tensor",
"torch.nn.Sigmoid",
"torch.nn.functional.relu",
"torch.nn.Sequential",
"torch.nn.BatchNorm1d",
"numpy.min",
"torch.nn.init.constant_",
"torch.nn.functional.avg_pool2d",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.nn.AvgPool2d",
"torch.nn.init.normal_",
"torch.nn.LeakyReLU",
"torch.nn.BatchNorm2d",
"torch.stack",
"numpy.array",
"torch.nn.AdaptiveAvgPool2d",
"torch.nn.ReLU",
"torch.nn.init.kaiming_normal_"
]
] |
rangsimanketkaew/sGDML
|
[
"3f06e0de33462afdfaecb310ac2d4e073b6ed2cf"
] |
[
"sgdml/cli.py"
] |
[
"#!/usr/bin/python\n\n# MIT License\n#\n# Copyright (c) 2018-2021 Stefan Chmiela\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nfrom __future__ import print_function\n\nimport logging\nimport multiprocessing as mp\nimport argparse\nimport os\nimport shutil\nimport sys\nimport traceback\nimport time\n\nimport numpy as np\nimport scipy as sp\n\ntry:\n import torch\nexcept ImportError:\n _has_torch = False\nelse:\n _has_torch = True\n\ntry:\n import ase\nexcept ImportError:\n _has_ase = False\nelse:\n _has_ase = True\n\nfrom . import __version__, DONE, NOT_DONE, MAX_PRINT_WIDTH\nfrom .predict import GDMLPredict\nfrom .train import GDMLTrain\nfrom .utils import io, ui\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nPACKAGE_NAME = 'sgdml'\n\nlog = logging.getLogger(__name__)\n\n\nclass AssistantError(Exception):\n pass\n\n\ndef _print_splash(max_processes=None, use_torch=False):\n\n logo_str = r\"\"\" __________ __ _____\n _____/ ____/ __ \\/ |/ / /\n / ___/ / __/ / / / /|_/ / /\n (__ ) /_/ / /_/ / / / / /___\n/____/\\____/_____/_/ /_/_____/\"\"\"\n\n can_update, latest_version = _check_update()\n\n version_str = __version__\n version_str += (\n ' ' + ui.yellow_back_str(' Latest: ' + latest_version + ' ')\n if can_update\n else ''\n )\n\n # TODO: does this import test work in python3?\n max_processes_str = (\n ''\n if max_processes is None or max_processes >= mp.cpu_count()\n else ' [using {}]'.format(max_processes)\n )\n hardware_str = 'found {:d} CPU(s){}'.format(mp.cpu_count(), max_processes_str)\n\n if use_torch and _has_torch and torch.cuda.is_available():\n num_gpu = torch.cuda.device_count()\n if num_gpu > 0:\n hardware_str += ' / {:d} GPU(s)'.format(num_gpu)\n\n logo_str_split = logo_str.splitlines()\n print('\\n'.join(logo_str_split[:-1]))\n ui.print_two_column_str(logo_str_split[-1] + ' ' + version_str, hardware_str)\n\n # Print update notice.\n if can_update:\n print(\n '\\n'\n + ui.yellow_back_str(' UPDATE AVAILABLE ')\n + '\\n'\n + '-' * MAX_PRINT_WIDTH\n )\n print(\n 'A new stable release version {} of this software is available.'.format(\n latest_version\n )\n )\n print(\n 'You can update your installation by running \\'pip install sgdml --upgrade\\'.'\n )\n\n\ndef _check_update():\n\n try:\n from urllib.request import urlopen\n except ImportError:\n from urllib2 import urlopen\n\n base_url = 'http://www.quantum-machine.org/gdml/'\n url = '%supdate.php?v=%s' % (base_url, __version__)\n\n can_update, must_update = '0', '0'\n latest_version = ''\n try:\n response = urlopen(url, timeout=1)\n can_update, must_update, latest_version = response.read().decode().split(',')\n response.close()\n except:\n pass\n\n return can_update == '1', latest_version\n\n\ndef _print_dataset_properties(dataset, title_str='Dataset properties'):\n\n print(ui.white_bold_str(title_str))\n\n n_mols, n_atoms, _ = dataset['R'].shape\n print(' {:<18} \\'{}\\''.format('Name:', ui.unicode_str(dataset['name'])))\n print(' {:<18} \\'{}\\''.format('Theory level:', ui.unicode_str(dataset['theory'])))\n print(' {:<18} {:<d}'.format('Atoms:', n_atoms))\n\n print(' {:<18} {:,} data points'.format('Size:', n_mols))\n\n ui.print_lattice(dataset['lattice'] if 'lattice' in dataset else None)\n\n if 'E' in dataset:\n\n e_unit = 'unknown unit'\n if 'e_unit' in dataset:\n e_unit = ui.unicode_str(dataset['e_unit'])\n\n print(' Energies [{}]'.format(e_unit))\n if 'E_min' in dataset and 'E_max' in dataset:\n E_min, E_max = dataset['E_min'], dataset['E_max']\n else:\n E_min, E_max = np.min(dataset['E']), np.max(dataset['E'])\n E_range_str = ui.gen_range_str(E_min, E_max)\n ui.print_two_column_str(' {:<16} {}'.format('Range:', E_range_str), 'min |-- range --| max')\n\n E_mean = dataset['E_mean'] if 'E_mean' in dataset else np.mean(dataset['E'])\n print(' {:<16} {:<.3f}'.format('Mean:', E_mean))\n\n E_var = dataset['E_var'] if 'E_var' in dataset else np.var(dataset['E'])\n print(' {:<16} {:<.3f}'.format('Variance:', E_var))\n else:\n print(' {:<18} {}'.format('Energies:', 'n/a'))\n\n f_unit = 'unknown unit'\n if 'r_unit' in dataset and 'e_unit' in dataset:\n f_unit = (\n ui.unicode_str(dataset['e_unit']) + '/' + ui.unicode_str(dataset['r_unit'])\n )\n\n print(' Forces [{}]'.format(f_unit))\n\n if 'F_min' in dataset and 'F_max' in dataset:\n F_min, F_max = dataset['F_min'], dataset['F_max']\n else:\n F_min, F_max = np.min(dataset['F'].ravel()), np.max(dataset['F'].ravel())\n F_range_str = ui.gen_range_str(F_min, F_max)\n ui.print_two_column_str(' {:<16} {}'.format('Range:', F_range_str), 'min |-- range --| max')\n\n F_mean = dataset['F_mean'] if 'F_mean' in dataset else np.mean(dataset['F'].ravel())\n print(' {:<16} {:<.3f}'.format('Mean:', F_mean))\n\n F_var = dataset['F_var'] if 'F_var' in dataset else np.var(dataset['F'].ravel())\n print(' {:<16} {:<.3f}'.format('Variance:', F_var))\n\n print(' {:<18} {}'.format('Fingerprint:', ui.unicode_str(dataset['md5'])))\n\n # if 'code_version' in dataset:\n # print(' {:<18} sGDML {}'.format('Created with:', ui.unicode_str(dataset['code_version'])))\n\n idx = np.random.choice(n_mols, 1)[0]\n r = dataset['R'][idx, :, :]\n e = np.squeeze(dataset['E'][idx]) if 'E' in dataset else None\n f = dataset['F'][idx, :, :]\n lattice = dataset['lattice'] if 'lattice' in dataset else None\n\n print(\n '\\n'\n + ui.white_bold_str('Example geometry')\n + ' (no. {:,}, chosen randomly)'.format(idx + 1)\n )\n xyz_info_str = 'Copy & paste the string below into Jmol (www.jmol.org), Avogadro (www.avogadro.cc), etc. to visualize one of the geometries from this dataset. A new example will be drawn on each run.'\n xyz_info_str = ui.wrap_str(xyz_info_str, width=MAX_PRINT_WIDTH - 2)\n xyz_info_str = ui.indent_str(xyz_info_str, 2)\n print(xyz_info_str + '\\n')\n\n xyz_str = io.generate_xyz_str(r, dataset['z'], e=e, f=f, lattice=lattice)\n xyz_str = ui.indent_str(xyz_str, 2)\n\n cut_str = '---- COPY HERE '\n cut_str_reps = int(np.floor((MAX_PRINT_WIDTH - 6) / len(cut_str)))\n cutline_str = ui.gray_str(' -' + cut_str * cut_str_reps + '-----')\n\n print(cutline_str)\n print(xyz_str)\n print(cutline_str)\n\n\ndef _print_task_properties(\n use_sym, use_cprsn, use_E, use_E_cstr, title_str='Task properties'\n):\n\n print(ui.white_bold_str(title_str))\n\n # print(' {:<18} {}'.format('Solver:', ui.unicode_str('[solver name]')))\n # print(' {:<16} {}'.format('Tolerance:', '[tol]'))\n\n energy_fix_str = (\n (\n 'kernel constraints (+E)'\n if use_E_cstr\n else 'global integration constant recovery'\n )\n if use_E\n else 'none'\n )\n print(' {:<16} {}'.format('Energy handling:', energy_fix_str))\n\n print(\n ' {:<16} {}'.format(\n 'Symmetries:', 'include (sGDML)' if use_sym else 'ignore (GDML)'\n )\n )\n print(\n ' {:<16} {}'.format(\n 'Compression:', 'requested' if use_cprsn else 'not requested'\n )\n )\n\n\ndef _print_model_properties(model, title_str='Model properties'):\n\n print(ui.white_bold_str(title_str))\n\n print(' {:<18}'.format('Dataset'))\n print(' {:<16} \\'{}\\''.format('Name:', ui.unicode_str(model['dataset_name'])))\n print(' {:<16} \\'{}\\''.format('Theory level:', ui.unicode_str(model['dataset_theory'])))\n\n n_atoms = len(model['z'])\n print(' {:<16} {:<d}'.format('Atoms:', n_atoms))\n\n ui.print_lattice(model['lattice'] if 'lattice' in model else None, inset=True)\n\n print(' {:<18} {:<d}'.format('Symmetries:', len(model['perms'])))\n\n _, cprsn_keep_idxs = np.unique(\n np.sort(model['perms'], axis=0), axis=1, return_index=True\n )\n n_atoms_kept = cprsn_keep_idxs.shape[0]\n print(\n ' {:<18} {}'.format(\n 'Compression:',\n '{:<d} effective atoms'.format(n_atoms_kept)\n if 'use_cprsn' in model and model['use_cprsn']\n else 'n/a',\n )\n )\n\n print(' {:<18}'.format('Hyper-parameters'))\n print(' {:<16} {:<d}'.format('Length scale:', model['sig']))\n\n if 'lam' in model:\n print(' {:<16} {:<.0e}'.format('Regularization:', model['lam']))\n\n if 'solver_name' in model:\n print(' {:<18}'.format('Solver'))\n print(' {:<16} \\'{}\\''.format('Type:', model['solver_name']))\n\n if model['solver_name'] == 'cg':\n\n if 'solver_tol' in model:\n ui.print_two_column_str(' {:<16} {:<.0e}'.format('Tolerance:', model['solver_tol']), 'iterate until: norm(K*alpha - y) <= tol*norm(y) = {:<.0e}'.format(model['solver_tol']*model['norm_y_train']))\n\n if 'solver_resid' in model:\n is_conv = model['solver_resid'] <= model['solver_tol']*model['norm_y_train']\n print(' {:<16} {:<.0e}{}'.format('Converged to:', model['solver_resid'], '' if is_conv else ' (NOT CONVERGED)'))\n\n if 'solver_iters' in model:\n print(' {:<16} {:<d}'.format('Iterations:', model['solver_iters']))\n\n if 'n_inducing_pts_init' in model and 'inducing_pts_idxs' in model:\n n_inducing_pts_final = len(model['inducing_pts_idxs']) // (3*n_atoms)\n increased_str = ' (increased to {:<d})'.format(n_inducing_pts_final) if model['n_inducing_pts_init'] < n_inducing_pts_final else ''\n print(' {:<16} {:<d}{}'.format('Inducing points:', model['n_inducing_pts_init'], increased_str))\n else:\n print(' {:<18} {}'.format('Solver:', 'unknown'))\n\n\n n_train = len(model['idxs_train'])\n ui.print_two_column_str(\n ' {:<18} {:,} points'.format('Trained on:', n_train),\n 'from \\'' + ui.unicode_str(model['md5_train']) + '\\'',\n )\n\n if model['use_E']:\n e_err = model['e_err'].item()\n f_err = model['f_err'].item()\n\n n_valid = len(model['idxs_valid'])\n is_valid = not np.isnan(f_err['mae']) and not np.isnan(f_err['rmse'])\n ui.print_two_column_str(\n ' {:<18} {}{:,} points'.format(\n 'Validated on:', '' if is_valid else '[pending] ', n_valid\n ),\n 'from \\'' + ui.unicode_str(model['md5_valid']) + '\\'',\n )\n\n n_test = int(model['n_test'])\n is_test = n_test > 0\n if is_test:\n ui.print_two_column_str(\n ' {:<18} {:,} points'.format('Tested on:', n_test),\n 'from \\'' + ui.unicode_str(model['md5_test']) + '\\'',\n )\n else:\n print(' {:<18} {}'.format('Test:', '[pending]'))\n\n e_unit = 'unknown unit'\n f_unit = 'unknown unit'\n if 'r_unit' in model and 'e_unit' in model:\n e_unit = model['e_unit']\n f_unit = ui.unicode_str(model['e_unit']) + '/' + ui.unicode_str(model['r_unit'])\n\n if is_valid:\n action_str = 'Validation' if not is_valid else 'Expected test'\n print(' {:<18}'.format('{} errors (MAE/RMSE)'.format(action_str)))\n if model['use_E']:\n print(\n ' {:<16} {:>.4f}/{:>.4f} [{}]'.format(\n 'Energy:', e_err['mae'], e_err['rmse'], e_unit\n )\n )\n print(\n ' {:<16} {:>.4f}/{:>.4f} [{}]'.format(\n 'Forces:', f_err['mae'], f_err['rmse'], f_unit\n )\n )\n\ndef _print_next_step(prev_step, task_dir=None, model_dir=None, model_files=None, dataset_path=None):\n\n if prev_step == 'create':\n\n assert task_dir is not None\n\n ui.print_step_title(\n 'NEXT STEP', '{} train {} <valid_dataset_file>'.format(PACKAGE_NAME, task_dir), underscore=False\n )\n\n elif prev_step == 'train' or prev_step == 'validate' or prev_step == 'resume':\n\n assert model_dir is not None and model_files is not None\n\n if dataset_path is None:\n dataset_path = '<test_dataset_file>'\n\n n_models = len(model_files)\n if n_models == 1:\n model_file_path = os.path.join(model_dir, model_files[0])\n ui.print_step_title(\n 'NEXT STEP',\n '{} test {} {} [<n_test>]'.format(\n PACKAGE_NAME, model_file_path, dataset_path\n ),\n underscore=False,\n )\n else:\n ui.print_step_title(\n 'NEXT STEP',\n '{} select {}'.format(PACKAGE_NAME, model_dir),\n underscore=False,\n )\n\n elif prev_step == 'select':\n\n assert model_files is not None \n\n ui.print_step_title(\n 'NEXT STEP',\n '{} test {} <test_dataset_file> [<n_test>]'.format(PACKAGE_NAME, model_files[0]),\n underscore=False,\n )\n\n else:\n raise AssistantError(\n 'Unexpected previous step string.'\n )\n\n\ndef all(\n dataset,\n valid_dataset,\n test_dataset,\n n_train,\n n_valid,\n n_test,\n sigs,\n gdml,\n use_E,\n use_E_cstr,\n use_cprsn,\n overwrite,\n max_processes,\n use_torch,\n solver,\n n_inducing_pts_init,\n interact_cut_off,\n task_dir=None,\n model_file=None,\n **kwargs\n):\n\n print(\n '\\n' + ui.white_back_str(' STEP 0 ') + ' Dataset(s)\\n' + '-' * MAX_PRINT_WIDTH\n )\n\n _, dataset_extracted = dataset\n _print_dataset_properties(dataset_extracted, title_str='Properties')\n\n if valid_dataset is None:\n valid_dataset = dataset\n else:\n _, valid_dataset_extracted = valid_dataset\n print()\n _print_dataset_properties(\n valid_dataset_extracted, title_str='Properties (validation)'\n )\n\n if not np.array_equal(dataset_extracted['z'], valid_dataset_extracted['z']):\n raise AssistantError(\n 'Atom composition or order in validation dataset does not match the one in bulk dataset.'\n )\n\n if test_dataset is None:\n test_dataset = dataset\n else:\n _, test_dataset_extracted = test_dataset\n _print_dataset_properties(test_dataset_extracted, title_str='Properties (test)')\n\n if not np.array_equal(dataset_extracted['z'], test_dataset_extracted['z']):\n raise AssistantError(\n 'Atom composition or order in test dataset does not match the one in bulk dataset.'\n )\n\n ui.print_step_title('STEP 1', 'Cross-validation task creation')\n task_dir = create(\n dataset,\n valid_dataset,\n n_train,\n n_valid,\n sigs,\n gdml,\n use_E,\n use_E_cstr,\n use_cprsn,\n overwrite,\n max_processes,\n task_dir,\n solver=solver,\n n_inducing_pts_init=n_inducing_pts_init,\n interact_cut_off=interact_cut_off,\n **kwargs\n )\n\n ui.print_step_title('STEP 2', 'Training and validation')\n task_dir_arg = io.is_dir_with_file_type(task_dir, 'task')\n model_dir_or_file_path = train(\n task_dir_arg, valid_dataset, overwrite, max_processes, use_torch, **kwargs\n )\n\n model_dir_arg = io.is_dir_with_file_type(\n model_dir_or_file_path, 'model', or_file=True\n )\n\n ui.print_step_title('STEP 3', 'Hyper-parameter selection')\n model_file_name = select(\n model_dir_arg, overwrite, max_processes, model_file, **kwargs\n )\n\n ui.print_step_title('STEP 4', 'Testing')\n model_dir_arg = io.is_dir_with_file_type(model_file_name, 'model', or_file=True)\n test(\n model_dir_arg,\n test_dataset,\n n_test,\n overwrite=False,\n max_processes=max_processes,\n use_torch=use_torch,\n **kwargs\n )\n\n print(\n '\\n'\n + ui.color_str(' DONE ', fore_color=ui.BLACK, back_color=ui.GREEN, bold=True)\n + ' Training assistant finished sucessfully.'\n )\n print(' This is your model file: \\'{}\\''.format(model_file_name))\n\n\n# if training job exists and is a subset of the requested cv range, add new tasks\n# otherwise, if new range is different or smaller, fail\ndef create( # noqa: C901\n dataset,\n valid_dataset,\n n_train,\n n_valid,\n sigs,\n gdml,\n use_E,\n use_E_cstr,\n use_cprsn,\n overwrite,\n max_processes,\n task_dir=None,\n solver='analytic',\n n_inducing_pts_init=None,\n interact_cut_off=None,\n command=None,\n **kwargs\n):\n\n has_valid_dataset = not (valid_dataset is None or valid_dataset == dataset)\n\n dataset_path, dataset = dataset\n n_data = dataset['F'].shape[0]\n\n func_called_directly = (\n command == 'create'\n ) # has this function been called from command line or from 'all'?\n if func_called_directly:\n ui.print_step_title('TASK CREATION')\n _print_dataset_properties(dataset)\n print()\n\n _print_task_properties(\n use_sym=not gdml, use_cprsn=use_cprsn, use_E=use_E, use_E_cstr=use_E_cstr\n )\n print()\n\n if n_data < n_train:\n raise AssistantError(\n 'Dataset only contains {} points, can not train on {}.'.format(\n n_data, n_train\n )\n )\n\n if not has_valid_dataset:\n valid_dataset_path, valid_dataset = dataset_path, dataset\n if n_data - n_train < n_valid:\n raise AssistantError(\n 'Dataset only contains {} points, can not train on {} and validate on {}.'.format(\n n_data, n_train, n_valid\n )\n )\n else:\n valid_dataset_path, valid_dataset = valid_dataset\n n_valid_data = valid_dataset['R'].shape[0]\n if n_valid_data < n_valid:\n raise AssistantError(\n 'Validation dataset only contains {} points, can not validate on {}.'.format(\n n_data, n_valid\n )\n )\n\n if sigs is None:\n log.info(\n 'Kernel hyper-parameter sigma was automatically set to range \\'10:10:100\\'.'\n )\n sigs = list(range(10, 100, 10)) # default range\n\n if task_dir is None:\n task_dir = io.train_dir_name(\n dataset,\n n_train,\n use_sym=not gdml,\n use_cprsn=use_cprsn,\n use_E=use_E,\n use_E_cstr=use_E_cstr,\n )\n\n task_file_names = []\n if os.path.exists(task_dir):\n if overwrite:\n log.info('Overwriting existing training directory.')\n shutil.rmtree(task_dir, ignore_errors=True)\n os.makedirs(task_dir)\n else:\n if io.is_task_dir_resumeable(\n task_dir, dataset, valid_dataset, n_train, n_valid, sigs, gdml\n ):\n log.info(\n 'Resuming existing hyper-parameter search in \\'{}\\'.'.format(\n task_dir\n )\n )\n\n # Get all task file names.\n try:\n _, task_file_names = io.is_dir_with_file_type(task_dir, 'task')\n except Exception:\n pass\n else:\n raise AssistantError(\n 'Unfinished hyper-parameter search found in \\'{}\\'.\\n'.format(\n task_dir\n )\n + 'Run \\'%s %s -o %s %d %d -s %s\\' to overwrite.'\n % (\n PACKAGE_NAME,\n command,\n dataset_path,\n n_train,\n n_valid,\n ' '.join(str(s) for s in sigs),\n )\n )\n else:\n os.makedirs(task_dir)\n\n if task_file_names:\n\n with np.load(\n os.path.join(task_dir, task_file_names[0]), allow_pickle=True\n ) as task:\n tmpl_task = dict(task)\n else:\n if not use_E:\n log.info(\n 'Energy labels will be ignored for training.\\n'\n + 'Note: If available in the dataset file, the energy labels will however still be used to generate stratified training, test and validation datasets. Otherwise a random sampling is used.'\n )\n\n if 'E' not in dataset:\n log.warning(\n 'Training dataset will be sampled with no guidance from energy labels (i.e. randomly)!'\n )\n\n if 'E' not in valid_dataset:\n log.warning(\n 'Validation dataset will be sampled with no guidance from energy labels (i.e. randomly)!\\n'\n + 'Note: Larger validation datasets are recommended due to slower convergence of the error.'\n )\n\n if ('lattice' in dataset) ^ ('lattice' in valid_dataset):\n log.error('One of the datasets specifies lattice vectors and one does not!')\n # TODO: stop program?\n\n if 'lattice' in dataset or 'lattice' in valid_dataset:\n log.info(\n 'Lattice vectors found in dataset: applying periodic boundary conditions.'\n )\n\n gdml_train = GDMLTrain(max_processes=max_processes)\n try:\n tmpl_task = gdml_train.create_task(\n dataset,\n n_train,\n valid_dataset,\n n_valid,\n sig=1,\n use_sym=not gdml,\n use_E=use_E,\n use_E_cstr=use_E_cstr,\n use_cprsn=use_cprsn,\n solver=solver,\n n_inducing_pts_init=n_inducing_pts_init,\n interact_cut_off=interact_cut_off,\n callback=ui.callback,\n ) # template task\n except:\n print()\n log.critical(traceback.format_exc())\n sys.exit()\n\n n_written = 0\n for sig in sigs:\n tmpl_task['sig'] = sig\n task_file_name = io.task_file_name(tmpl_task)\n task_path = os.path.join(task_dir, task_file_name)\n\n if os.path.isfile(task_path):\n log.warning('Skipping existing task \\'{}\\'.'.format(task_file_name))\n else:\n np.savez_compressed(task_path, **tmpl_task)\n n_written += 1\n if n_written > 0:\n log.done(\n 'Writing {:d}/{:d} task(s) with {} training points each.'.format(\n n_written, len(sigs), tmpl_task['R_train'].shape[0]\n )\n )\n\n if func_called_directly:\n _print_next_step('create', task_dir=task_dir)\n\n return task_dir\n\ndef train(\n task_dir, valid_dataset, overwrite, max_processes, use_torch, command=None, **kwargs\n):\n\n task_dir, task_file_names = task_dir\n n_tasks = len(task_file_names)\n\n func_called_directly = (\n command == 'train'\n ) # has this function been called from command line or from 'all'?\n if func_called_directly:\n ui.print_step_title('MODEL TRAINING')\n\n def cprsn_callback(n_atoms, n_atoms_kept):\n log.info(\n '{:d} out of {:d} atoms remain after compression.\\n'.format(\n n_atoms_kept, n_atoms\n )\n + 'Note: Compression reduces the size of the optimization problem the cost of prediction accuracy!'\n )\n\n unconv_model_file = '_unconv_model.npz'\n unconv_model_path = os.path.join(task_dir, unconv_model_file)\n\n def save_progr_callback(\n unconv_model,\n ): # saves current (unconverged) model during iterative training\n\n np.savez_compressed(unconv_model_path, **unconv_model)\n\n try:\n gdml_train = GDMLTrain(max_processes=max_processes, use_torch=use_torch)\n except:\n print()\n log.critical(traceback.format_exc())\n sys.exit()\n\n prev_valid_err = -1\n\n for i, task_file_name in enumerate(task_file_names):\n if n_tasks > 1:\n if i > 0:\n print()\n print(ui.white_bold_str('Task {:d} of {:d}'.format(i + 1, n_tasks)))\n\n task_file_path = os.path.join(task_dir, task_file_name)\n with np.load(task_file_path, allow_pickle=True) as task:\n\n model_file_name = io.model_file_name(task, is_extended=False)\n model_file_path = os.path.join(task_dir, model_file_name)\n\n if not overwrite and os.path.isfile(model_file_path):\n log.warning(\n 'Skipping exising model \\'{}\\'.'.format(model_file_name)\n + (\n '\\nRun \\'{} train -o {}\\' to overwrite.'.format(\n PACKAGE_NAME, task_file_path\n )\n if func_called_directly\n else ''\n )\n )\n continue\n\n try:\n model = gdml_train.train(\n task, cprsn_callback, save_progr_callback, ui.callback\n )\n except:\n print()\n log.critical(traceback.format_exc())\n sys.exit()\n else:\n if func_called_directly:\n log.done('Writing model to file \\'{}\\''.format(model_file_path))\n np.savez_compressed(model_file_path, **model)\n\n # Delete temporary model, if one exists.\n unconv_model_exists = os.path.isfile(unconv_model_path)\n if unconv_model_exists:\n os.remove(unconv_model_path)\n\n # Delete template model, if one exists.\n templ_model_path = os.path.join(task_dir, 'm0.npz')\n templ_model_exists = os.path.isfile(templ_model_path)\n if templ_model_exists:\n os.remove(templ_model_path)\n\n # Validate model.\n model_dir = (task_dir, [model_file_name])\n valid_errs = test(\n model_dir,\n valid_dataset,\n -1, # n_test = -1 -> validation mode\n overwrite,\n max_processes,\n use_torch,\n command,\n **kwargs\n )\n\n if prev_valid_err != -1 and prev_valid_err < valid_errs[0]:\n print()\n log.warning(\n 'Skipping remaining training tasks, as validation error is rising again.'\n )\n break\n\n prev_valid_err = valid_errs[0]\n\n model_dir_or_file_path = model_file_path if n_tasks == 1 else task_dir\n if func_called_directly:\n\n model_dir_arg = io.is_dir_with_file_type(model_dir_or_file_path, 'model', or_file=True)\n model_dir, model_files = model_dir_arg\n _print_next_step('train', model_dir=model_dir, model_files=model_files)\n\n return model_dir_or_file_path # model directory or file\n\n\ndef _batch(iterable, n=1):\n l = len(iterable)\n for ndx in range(0, l, n):\n yield iterable[ndx : min(ndx + n, l)]\n\n\ndef _online_err(err, size, n, mae_n_sum, rmse_n_sum):\n\n err = np.abs(err)\n\n mae_n_sum += np.sum(err) / size\n mae = mae_n_sum / n\n\n rmse_n_sum += np.sum(err ** 2) / size\n rmse = np.sqrt(rmse_n_sum / n)\n\n return mae, mae_n_sum, rmse, rmse_n_sum\n\n\ndef resume(model, dataset, valid_dataset, overwrite, max_processes, use_torch, command=None, **kwargs):\n\n model_path, model = model\n dataset_path, dataset = dataset\n\n valid_dataset_arg = valid_dataset\n valid_dataset_path, valid_dataset = valid_dataset\n\n ui.print_step_title('RESUME TRAINING')\n _print_model_properties(model, title_str='Model properties (before)')\n print()\n\n if dataset['md5'] != model['md5_train']:\n raise AssistantError(\n 'Fingerprint of provided training dataset does not match the one specified in model file.'\n )\n if valid_dataset['md5'] != model['md5_valid']:\n raise AssistantError(\n 'Fingerprint of provided validation dataset does not match the one specified in model file.'\n )\n\n if model['solver_name'] == 'analytic':\n raise AssistantError(\n 'This model was trained using the analytic solver and is thus converged to a higher accuracy than the iterative solver can provide!'\n )\n elif 'solver_resid' in model and 'solver_tol' in model:\n if model['solver_resid'] <= model['solver_tol']*model['norm_y_train']:\n log.warning('Model is already converged to the specified tolerance.')\n\n gdml_train = GDMLTrain(max_processes=max_processes, use_torch=use_torch)\n try:\n task = gdml_train.create_task_from_model(\n model,\n dataset,\n )\n except:\n print()\n log.critical(traceback.format_exc())\n sys.exit()\n del gdml_train\n\n n_train = len(model['idxs_train'])\n\n use_sym = model['perms'].shape[0] > 1\n use_E = 'e_err' in model\n use_E_cstr = 'alphas_E' in model\n\n task_dir = 'resume_' + io.train_dir_name(\n dataset,\n n_train,\n use_sym=use_sym,\n use_cprsn=False, # fix me\n use_E=use_E,\n use_E_cstr=use_E_cstr,\n )\n\n if os.path.exists(task_dir):\n if overwrite:\n log.info('Overwriting existing training directory.')\n shutil.rmtree(task_dir, ignore_errors=True)\n os.makedirs(task_dir)\n else:\n raise AssistantError(\n 'Task directory already exists: \\'{}\\'.\\n'.format(\n task_dir\n )\n + 'Run \\'%s %s %s %s %s -o\\' to overwrite.'\n % (\n PACKAGE_NAME,\n command,\n model_path,\n dataset_path,\n valid_dataset_path,\n )\n )\n else:\n os.makedirs(task_dir)\n\n # try to safe task file\n task_file_name = io.task_file_name(task)\n task_path = os.path.join(task_dir, task_file_name)\n if os.path.isfile(task_path):\n raise AssistantError(\n 'Task file with same name already exists!'\n )\n else:\n np.savez_compressed(task_path, **task)\n\n task_dir_arg = io.is_dir_with_file_type(task_path, 'task', or_file=True)\n model_dir_or_file_path = train(\n task_dir_arg, valid_dataset_arg, overwrite, max_processes, use_torch, **kwargs\n )\n\n model_dir, model_files = io.is_dir_with_file_type(model_path, 'model', or_file=True)\n _print_next_step('resume', model_dir=model_dir, model_files=model_files)\n\ndef validate(\n model_dir,\n valid_dataset,\n overwrite,\n max_processes,\n use_torch,\n command=None,\n **kwargs\n):\n\n dataset_path_extracted, dataset_extracted = valid_dataset\n\n func_called_directly = (\n command == 'validate'\n ) # has this function been called from command line or from 'all'?\n if func_called_directly:\n ui.print_step_title('MODEL VALIDATION')\n _print_dataset_properties(dataset_extracted)\n\n test(\n model_dir,\n valid_dataset,\n -1, # n_test = -1 -> validation mode\n overwrite,\n max_processes,\n use_torch,\n command,\n **kwargs\n )\n\n if func_called_directly:\n\n model_dir, model_files = model_dir\n n_models = len(model_files)\n _print_next_step('validate', model_dir=model_dir, model_files=model_files)\n\n\ndef test(\n model_dir,\n test_dataset,\n n_test,\n overwrite,\n max_processes,\n use_torch,\n command=None,\n **kwargs\n): # noqa: C901\n\n # NOTE: this function runs a validation if n_test < 0 and test with all points if n_test == 0\n\n model_dir, model_file_names = model_dir\n n_models = len(model_file_names)\n\n n_test = 0 if n_test is None else n_test\n is_validation = n_test < 0\n is_test = n_test >= 0\n\n # NEW: turn me back on!\n # if (\n # is_validation and n_models == 1\n # ): # validation mode with only one model to validate\n # log.warning('Skipping validation step as there is only one model to validate.')\n # return\n\n dataset_path, dataset = test_dataset\n\n func_called_directly = (\n command == 'test'\n ) # has this function been called from command line or from 'all'?\n if func_called_directly:\n ui.print_step_title('MODEL TEST')\n _print_dataset_properties(dataset)\n\n F_rmse = [] # NEW\n\n # NEW\n\n DEBUG_WRITE = False\n\n if DEBUG_WRITE:\n if os.path.exists('test_pred.xyz'):\n os.remove('test_pred.xyz')\n if os.path.exists('test_ref.xyz'):\n os.remove('test_ref.xyz')\n if os.path.exists('test_diff.xyz'):\n os.remove('test_diff.xyz')\n\n # NEW\n\n num_workers, batch_size = 0, 0\n gdml_train = None\n for i, model_file_name in enumerate(model_file_names):\n\n model_path = os.path.join(model_dir, model_file_name)\n _, model = io.is_file_type(model_path, 'model')\n\n if i == 0 and command != 'all':\n print()\n _print_model_properties(model)\n print()\n\n if not np.array_equal(model['z'], dataset['z']):\n raise AssistantError(\n 'Atom composition or order in dataset does not match the one in model.'\n )\n\n if ('lattice' in model) is not ('lattice' in dataset):\n if 'lattice' in model:\n raise AssistantError(\n 'Model contains lattice vectors, but dataset does not.'\n )\n elif 'lattice' in dataset:\n raise AssistantError(\n 'Dataset contains lattice vectors, but model does not.'\n )\n\n if model['use_E']:\n e_err = model['e_err'].item()\n f_err = model['f_err'].item()\n\n is_model_validated = not (np.isnan(f_err['mae']) or np.isnan(f_err['rmse']))\n\n if n_models > 1:\n if i > 0:\n print()\n print(\n ui.white_bold_str(\n '%s model %d of %d'\n % ('Testing' if is_test else 'Validating', i + 1, n_models)\n )\n )\n\n if is_validation:\n if is_model_validated and not overwrite:\n log.warning(\n 'Skipping already validated model \\'{}\\'.'.format(model_file_name)\n + (\n '\\nRun \\'{} validate -o {} {}\\' to overwrite.'.format(\n PACKAGE_NAME, model_path, dataset_path\n )\n if command == 'test'\n else ''\n )\n )\n continue\n\n if dataset['md5'] != model['md5_valid']:\n raise AssistantError(\n 'Fingerprint of provided validation dataset does not match the one specified in model file.'\n )\n\n test_idxs = model['idxs_valid']\n if is_test:\n\n # exclude training and/or test sets from validation set if necessary\n excl_idxs = np.empty((0,), dtype=np.uint)\n if dataset['md5'] == model['md5_train']:\n excl_idxs = np.concatenate([excl_idxs, model['idxs_train']]).astype(\n np.uint\n )\n if dataset['md5'] == model['md5_valid']:\n excl_idxs = np.concatenate([excl_idxs, model['idxs_valid']]).astype(\n np.uint\n )\n\n n_data = dataset['F'].shape[0]\n n_data_eff = n_data - len(excl_idxs)\n\n if (\n n_test == 0 and n_data_eff != 0\n ): # test on all data points that have not been used for training or testing\n n_test = n_data_eff\n log.info(\n 'Test set size was automatically set to {:,} points.'.format(n_test)\n )\n\n if n_test == 0 or n_data_eff == 0:\n log.warning('Skipping! No unused points for test in provided dataset.')\n return\n elif n_data_eff < n_test:\n n_test = n_data_eff\n log.warning(\n 'Test size reduced to {:d}. Not enough unused points in provided dataset.'.format(\n n_test\n )\n )\n\n if 'E' in dataset:\n if gdml_train is None:\n gdml_train = GDMLTrain(max_processes=max_processes)\n test_idxs = gdml_train.draw_strat_sample(\n dataset['E'], n_test, excl_idxs=excl_idxs\n )\n else:\n test_idxs = np.delete(np.arange(n_data), excl_idxs)\n\n log.warning(\n 'Test dataset will be sampled with no guidance from energy labels (randomly)!\\n'\n + 'Note: Larger test datasets are recommended due to slower convergence of the error.'\n )\n # shuffle to improve convergence of online error\n np.random.shuffle(test_idxs)\n\n # NEW\n if DEBUG_WRITE:\n test_idxs = np.sort(test_idxs)\n\n z = dataset['z']\n R = dataset['R'][test_idxs, :, :]\n F = dataset['F'][test_idxs, :, :]\n\n if model['use_E']:\n E = dataset['E'][test_idxs]\n\n try:\n gdml_predict = GDMLPredict(\n model, max_processes=max_processes, use_torch=use_torch\n )\n except:\n print()\n log.critical(traceback.format_exc())\n sys.exit()\n\n b_size = min(1000, len(test_idxs))\n\n if not use_torch:\n if num_workers == 0 or batch_size == 0:\n ui.callback(NOT_DONE, disp_str='Optimizing parallelism')\n\n gps, is_from_cache = gdml_predict.prepare_parallel(\n n_bulk=b_size, return_is_from_cache=True\n )\n num_workers, batch_size, bulk_mp = (\n gdml_predict.num_workers,\n gdml_predict.chunk_size,\n gdml_predict.bulk_mp,\n )\n\n ui.callback(\n DONE,\n disp_str='Optimizing parallelism'\n + (' (from cache)' if is_from_cache else ''),\n sec_disp_str='%d workers %s/ chunks of %d'\n % (num_workers, '[MP] ' if bulk_mp else '', batch_size),\n )\n else:\n gdml_predict._set_num_workers(num_workers)\n gdml_predict._set_batch_size(batch_size)\n gdml_predict._set_bulk_mp(bulk_mp)\n\n n_atoms = z.shape[0]\n\n if model['use_E']:\n e_mae_sum, e_rmse_sum = 0, 0\n f_mae_sum, f_rmse_sum = 0, 0\n cos_mae_sum, cos_rmse_sum = 0, 0\n mag_mae_sum, mag_rmse_sum = 0, 0\n\n n_done = 0\n t = time.time()\n for b_range in _batch(list(range(len(test_idxs))), b_size):\n\n n_done_step = len(b_range)\n n_done += n_done_step\n\n r = R[b_range].reshape(n_done_step, -1)\n e_pred, f_pred = gdml_predict.predict(r)\n\n # energy error\n if model['use_E']:\n e = E[b_range]\n e_mae, e_mae_sum, e_rmse, e_rmse_sum = _online_err(\n np.squeeze(e) - e_pred, 1, n_done, e_mae_sum, e_rmse_sum\n )\n\n # force component error\n f = F[b_range].reshape(n_done_step, -1)\n f_mae, f_mae_sum, f_rmse, f_rmse_sum = _online_err(\n f - f_pred, 3 * n_atoms, n_done, f_mae_sum, f_rmse_sum\n )\n\n # magnitude error\n f_pred_mags = np.linalg.norm(f_pred.reshape(-1, 3), axis=1)\n f_mags = np.linalg.norm(f.reshape(-1, 3), axis=1)\n mag_mae, mag_mae_sum, mag_rmse, mag_rmse_sum = _online_err(\n f_pred_mags - f_mags, n_atoms, n_done, mag_mae_sum, mag_rmse_sum\n )\n\n # normalized cosine error\n f_pred_norm = f_pred.reshape(-1, 3) / f_pred_mags[:, None]\n f_norm = f.reshape(-1, 3) / f_mags[:, None]\n cos_err = np.arccos(np.clip(np.einsum('ij,ij->i', f_pred_norm, f_norm), -1, 1)) / np.pi\n cos_mae, cos_mae_sum, cos_rmse, cos_rmse_sum = _online_err(\n cos_err, n_atoms, n_done, cos_mae_sum, cos_rmse_sum\n )\n\n # NEW\n\n if is_test and DEBUG_WRITE:\n\n try:\n with open('test_pred.xyz', 'a') as file:\n\n n = r.shape[0]\n for i, ri in enumerate(r):\n\n r_out = ri.reshape(-1, 3)\n e_out = e_pred[i]\n f_out = f_pred[i].reshape(-1, 3)\n\n ext_xyz_str = (\n io.generate_xyz_str(r_out, model['z'], e=e_out, f=f_out)\n + '\\n'\n )\n\n file.write(ext_xyz_str)\n\n except IOError:\n sys.exit(\"ERROR: Writing xyz file failed.\")\n\n try:\n with open('test_ref.xyz', 'a') as file:\n\n n = r.shape[0]\n for i, ri in enumerate(r):\n\n r_out = ri.reshape(-1, 3)\n e_out = (\n None\n if not model['use_E']\n else np.squeeze(E[b_range][i])\n )\n f_out = f[i].reshape(-1, 3)\n\n ext_xyz_str = (\n io.generate_xyz_str(r_out, model['z'], e=e_out, f=f_out)\n + '\\n'\n )\n file.write(ext_xyz_str)\n\n except IOError:\n sys.exit(\"ERROR: Writing xyz file failed.\")\n\n try:\n with open('test_diff.xyz', 'a') as file:\n\n n = r.shape[0]\n for i, ri in enumerate(r):\n\n r_out = ri.reshape(-1, 3)\n e_out = (\n None\n if not model['use_E']\n else (np.squeeze(E[b_range][i]) - e_pred[i])\n )\n f_out = (f[i] - f_pred[i]).reshape(-1, 3)\n\n ext_xyz_str = (\n io.generate_xyz_str(r_out, model['z'], e=e_out, f=f_out)\n + '\\n'\n )\n file.write(ext_xyz_str)\n\n except IOError:\n sys.exit(\"ERROR: Writing xyz file failed.\")\n\n # NEW\n\n sps = n_done / (time.time() - t) # examples per second\n disp_str = 'energy %.3f/%.3f, ' % (e_mae, e_rmse) if model['use_E'] else ''\n disp_str += 'forces %.3f/%.3f' % (f_mae, f_rmse)\n disp_str = (\n '{} errors (MAE/RMSE): '.format('Test' if is_test else 'Validation')\n + disp_str\n )\n sec_disp_str = '@ %.1f geo/s' % sps if b_range is not None else ''\n\n ui.callback(\n n_done,\n len(test_idxs),\n disp_str=disp_str,\n sec_disp_str=sec_disp_str,\n newline_when_done=False,\n )\n\n if is_test:\n ui.callback(\n DONE,\n disp_str='Testing on {:,} points'.format(n_test),\n sec_disp_str=sec_disp_str,\n )\n else:\n ui.callback(DONE, disp_str=disp_str, sec_disp_str=sec_disp_str)\n\n if model['use_E']:\n e_rmse_pct = (e_rmse / e_err['rmse'] - 1.0) * 100\n f_rmse_pct = (f_rmse / f_err['rmse'] - 1.0) * 100\n\n # if func_called_directly and n_models == 1:\n if is_test and n_models == 1:\n print(ui.white_bold_str('\\nTest errors (MAE/RMSE)'))\n\n r_unit = 'unknown unit'\n e_unit = 'unknown unit'\n f_unit = 'unknown unit'\n if 'r_unit' in dataset and 'e_unit' in dataset:\n r_unit = dataset['r_unit']\n e_unit = dataset['e_unit']\n f_unit = str(dataset['e_unit']) + '/' + str(dataset['r_unit'])\n\n format_str = ' {:<18} {:>.4f}/{:>.4f} [{}]'\n if model['use_E']:\n ui.print_two_column_str(\n format_str.format('Energy:', e_mae, e_rmse, e_unit),\n 'relative to expected: {:+.1f}%'.format(e_rmse_pct),\n )\n\n ui.print_two_column_str(\n format_str.format('Forces:', f_mae, f_rmse, f_unit),\n 'relative to expected: {:+.1f}%'.format(f_rmse_pct),\n )\n\n print(format_str.format(' Magnitude:', mag_mae, mag_rmse, r_unit))\n ui.print_two_column_str(\n format_str.format(' Angle:', cos_mae, cos_rmse, '0-1'),\n 'lower is better',\n )\n print()\n\n model_mutable = dict(model)\n model.close()\n model = model_mutable\n\n model_needs_update = (\n overwrite\n or (is_test and model['n_test'] < len(test_idxs))\n or (is_validation and not is_model_validated)\n )\n if model_needs_update:\n\n if is_validation and overwrite:\n model['n_test'] = 0 # flag the model as not tested\n\n if is_test:\n model['n_test'] = len(test_idxs)\n model['md5_test'] = dataset['md5']\n\n if model['use_E']:\n model['e_err'] = {\n 'mae': np.asscalar(e_mae),\n 'rmse': np.asscalar(e_rmse),\n }\n\n model['f_err'] = {'mae': np.asscalar(f_mae), 'rmse': np.asscalar(f_rmse)}\n np.savez_compressed(model_path, **model)\n\n if is_test and model['n_test'] > 0:\n log.info('Expected errors were updated in model file.')\n\n else:\n add_info_str = (\n 'the same number of'\n if model['n_test'] == len(test_idxs)\n else 'only {:,}'.format(len(test_idxs))\n )\n log.warning(\n 'This model has previously been tested on {:,} points, which is why the errors for the current test run with {} points have NOT been used to update the model file.\\n'.format(\n model['n_test'], add_info_str\n )\n + 'Run \\'{} test -o {} {} {}\\' to overwrite.'.format(\n PACKAGE_NAME, os.path.relpath(model_path), dataset_path, n_test\n )\n )\n\n F_rmse.append(f_rmse)\n\n return F_rmse\n\n\ndef select(\n model_dir, overwrite, max_processes, model_file=None, command=None, **kwargs\n): # noqa: C901\n\n func_called_directly = (\n command == 'select'\n ) # has this function been called from command line or from 'all'?\n if func_called_directly:\n ui.print_step_title('MODEL SELECTION')\n\n any_model_not_validated = False\n any_model_is_tested = False\n\n model_dir, model_file_names = model_dir\n if len(model_file_names) > 1:\n\n use_E = True\n\n rows = []\n data_names = ['sig', 'MAE', 'RMSE', 'MAE', 'RMSE']\n for i, model_file_name in enumerate(model_file_names):\n model_path = os.path.join(model_dir, model_file_name)\n _, model = io.is_file_type(model_path, 'model')\n\n use_E = model['use_E']\n\n if i == 0:\n idxs_train = set(model['idxs_train'])\n md5_train = model['md5_train']\n idxs_valid = set(model['idxs_valid'])\n md5_valid = model['md5_valid']\n else:\n if (\n md5_train != model['md5_train']\n or md5_valid != model['md5_valid']\n or idxs_train != set(model['idxs_train'])\n or idxs_valid != set(model['idxs_valid'])\n ):\n raise AssistantError(\n '{} contains models trained or validated on different datasets.'.format(\n model_dir\n )\n )\n\n e_err = {'mae': 0.0, 'rmse': 0.0}\n if model['use_E']:\n e_err = model['e_err'].item()\n f_err = model['f_err'].item()\n\n is_model_validated = not (np.isnan(f_err['mae']) or np.isnan(f_err['rmse']))\n if not is_model_validated:\n any_model_not_validated = True\n\n is_model_tested = model['n_test'] > 0\n if is_model_tested:\n any_model_is_tested = True\n\n rows.append(\n [model['sig'], e_err['mae'], e_err['rmse'], f_err['mae'], f_err['rmse']]\n )\n\n model.close()\n\n if any_model_not_validated:\n log.error(\n 'One or more models in the given directory have not been validated yet.\\n'\n + 'This is required before selecting the best performer.'\n )\n print()\n sys.exit()\n\n if any_model_is_tested:\n log.error(\n 'One or more models in the given directory have already been tested. This means that their recorded expected errors are test errors, not validation errors. However, one should never perform model selection based on the test error!\\n'\n + 'Please run the validation command (again) with the overwrite option \\'-o\\', then this selection command.'\n )\n return\n\n f_rmse_col = [row[4] for row in rows]\n best_idx = f_rmse_col.index(min(f_rmse_col)) # idx of row with lowest f_rmse\n best_sig = rows[best_idx][0]\n\n rows = sorted(rows, key=lambda col: col[0]) # sort according to sigma\n print(ui.white_bold_str('Cross-validation errors'))\n print(' ' * 7 + 'Energy' + ' ' * 6 + 'Forces')\n print((' {:>3} ' + '{:>5} ' * 4).format(*data_names))\n print(' ' + '-' * 27)\n format_str = ' {:>3} ' + '{:5.2f} ' * 4\n format_str_no_E = ' {:>3} - - ' + '{:5.2f} ' * 2\n for row in rows:\n if use_E:\n row_str = format_str.format(*row)\n else:\n row_str = format_str_no_E.format(*[row[0], row[3], row[4]])\n\n if row[0] != best_sig:\n row_str = ui.gray_str(row_str)\n print(row_str)\n print()\n\n sig_col = [row[0] for row in rows]\n if best_sig == min(sig_col) or best_sig == max(sig_col):\n log.warning(\n 'The optimal sigma lies on the boundary of the search grid.\\n'\n + 'Model performance might improve if the search grid is extended in direction sigma {} {:d}.'.format(\n '<' if best_idx == 0 else '>', best_sig\n )\n )\n\n else: # only one model available\n log.warning(\n 'Skipping model selection step as there is only one model to select.'\n )\n\n best_idx = 0\n\n best_model_path = os.path.join(model_dir, model_file_names[best_idx])\n\n if model_file is None:\n\n # generate model file name based on model properties\n best_model = np.load(best_model_path, allow_pickle=True)\n model_file = io.model_file_name(best_model, is_extended=True)\n best_model.close()\n\n model_exists = os.path.isfile(model_file)\n if model_exists and overwrite:\n log.info('Overwriting existing model file.')\n\n if not model_exists or overwrite:\n if func_called_directly:\n log.done('Writing model file \\'{}\\''.format(model_file))\n\n shutil.copy(best_model_path, model_file)\n shutil.rmtree(model_dir, ignore_errors=True)\n else:\n log.warning(\n 'Model \\'{}\\' already exists.\\n'.format(model_file)\n + 'Run \\'{} select -o {}\\' to overwrite.'.format(\n PACKAGE_NAME, os.path.relpath(model_dir)\n )\n )\n\n if func_called_directly:\n _print_next_step('select', model_files=[model_file])\n\n return model_file\n\n\ndef show(file, overwrite, max_processes, command=None, **kwargs):\n\n ui.print_step_title('SHOW DETAILS')\n file_path, file = file\n\n if file['type'].astype(str) == 'd':\n _print_dataset_properties(file)\n\n if file['type'].astype(str) == 't':\n _print_task_properties(\n use_sym=file['use_sym'],\n use_cprsn=file['use_cprsn'],\n use_E=file['use_E'],\n use_E_cstr=file['use_E_cstr'],\n )\n\n if file['type'].astype(str) == 'm':\n _print_model_properties(file)\n\n\ndef reset(command=None, **kwargs):\n\n if ui.yes_or_no('\\nDo you really want to purge all caches and temporary files?'):\n\n pkg_dir = os.path.dirname(os.path.abspath(__file__))\n bmark_file = '_bmark_cache.npz'\n bmark_path = os.path.join(pkg_dir, bmark_file)\n\n if os.path.exists(bmark_path):\n try:\n os.remove(bmark_path)\n except OSError:\n print()\n log.critical('Exception: unable to delete benchmark cache.')\n sys.exit()\n\n log.done('Benchmark cache deleted.')\n else:\n log.info('Benchmark cache was already empty.')\n else:\n print(' Cancelled.')\n print()\n\n\ndef main():\n #def _add_argument_dataset(parser, qualifier_str='', help='path to dataset file'):\n # parser.add_argument(\n # 'dataset',\n # metavar='<'\n # + qualifier_str\n # + ('_' if qualifier_str != '' else '')\n # + 'dataset_file>',\n # type=lambda x: io.is_file_type(x, 'dataset'),\n # help=help,\n # )\n\n def _add_argument_sample_size(parser, subset_str):\n subparser.add_argument(\n 'n_%s' % subset_str,\n metavar='<n_%s>' % subset_str,\n type=io.is_strict_pos_int,\n help='%s sample size' % subset_str,\n )\n\n def _add_argument_dir_with_file_type(parser, type, or_file=False):\n parser.add_argument(\n '%s_dir' % type,\n metavar='<%s_dir%s>' % (type, '_or_file' if or_file else ''),\n type=lambda x: io.is_dir_with_file_type(x, type, or_file=or_file),\n help='path to %s directory%s' % (type, ' or file' if or_file else ''),\n )\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--version',\n action='version',\n version='%(prog)s '\n + __version__\n + ' [Python {}, NumPy {}, SciPy {}'.format(\n '.'.join(map(str, sys.version_info[:3])), np.__version__, sp.__version__\n )\n + ', PyTorch {}'.format(torch.__version__ if _has_torch else 'N/A')\n + ', ASE {}'.format(ase.__version__ if _has_ase else 'N/A')\n + ']',\n )\n\n parent_parser = argparse.ArgumentParser(add_help=False)\n parent_parser.add_argument(\n '-o',\n '--overwrite',\n dest='overwrite',\n action='store_true',\n help='overwrite existing files',\n )\n parent_parser.add_argument(\n '-p',\n '--max_processes',\n metavar='<max_processes>',\n type=io.is_strict_pos_int,\n help='limit the number of processes for this application',\n )\n parent_parser.add_argument(\n '--torch',\n dest='use_torch',\n action='store_true',\n help='use PyTorch to enable GPU acceleration',\n )\n\n subparsers = parser.add_subparsers(title='commands', dest='command')\n subparsers.required = True\n parser_all = subparsers.add_parser(\n 'all', help='reconstruct force field from beginning to end', parents=[parent_parser]\n )\n parser_create = subparsers.add_parser(\n 'create', help='create training task(s)', parents=[parent_parser]\n )\n parser_train = subparsers.add_parser(\n 'train', help='train model(s) from task(s)', parents=[parent_parser]\n )\n parser_resume = subparsers.add_parser(\n 'resume', help='resume training a model', parents=[parent_parser]\n )\n parser_valid = subparsers.add_parser(\n 'validate', help='validate model(s)', parents=[parent_parser]\n )\n parser_select = subparsers.add_parser(\n 'select', help='select best performing model', parents=[parent_parser]\n )\n parser_test = subparsers.add_parser(\n 'test', help='test a model', parents=[parent_parser]\n )\n parser_show = subparsers.add_parser(\n 'show',\n help='print details about dataset, task or model file',\n parents=[parent_parser],\n )\n subparsers.add_parser(\n 'reset', help='delete all caches and temporary files', parents=[parent_parser]\n )\n\n for subparser in [parser_all, parser_create]:\n\n subparser.add_argument(\n 'dataset',\n metavar='<dataset_file>',\n type=lambda x: io.is_file_type(x, 'dataset'),\n help='path to dataset file (train/validation/test subsets are sampled from here if no seperate dataset are specified)',\n )\n\n _add_argument_sample_size(subparser, 'train')\n _add_argument_sample_size(subparser, 'valid')\n subparser.add_argument(\n '-v',\n '--validation_dataset',\n metavar='<valid_dataset_file>',\n dest='valid_dataset',\n type=lambda x: io.is_file_type(x, 'dataset'),\n help='path to validation dataset file',\n )\n subparser.add_argument(\n '-t',\n '--test_dataset',\n metavar='<test_dataset_file>',\n dest='test_dataset',\n type=lambda x: io.is_file_type(x, 'dataset'),\n help='path to test dataset file',\n )\n subparser.add_argument(\n '-s',\n '--sig',\n metavar=('<s1>', '<s2>'),\n dest='sigs',\n type=io.parse_list_or_range,\n help='integer list and/or range <start>:[<step>:]<stop> for the kernel hyper-parameter sigma',\n nargs='+',\n )\n subparser.add_argument(\n '--task_dir',\n metavar='<task_dir>',\n dest='task_dir',\n help='user-defined task output dir name',\n )\n\n group = subparser.add_mutually_exclusive_group()\n group.add_argument(\n '--gdml',\n action='store_true',\n help='don\\'t include symmetries in the model (GDML)',\n )\n group.add_argument(\n '--cprsn',\n dest='use_cprsn',\n action='store_true',\n help='compress kernel matrix along symmetric degrees of freedom',\n )\n\n group = subparser.add_mutually_exclusive_group()\n group.add_argument(\n '--no_E',\n dest='use_E',\n action='store_false',\n help='only reconstruct force field w/o potential energy surface',\n )\n group.add_argument(\n '--E_cstr',\n dest='use_E_cstr',\n action='store_true',\n help='include the energy constraints in the kernel',\n )\n\n for subparser in [parser_valid, parser_test]:\n _add_argument_dir_with_file_type(subparser, 'model', or_file=True)\n\n parser_valid.add_argument(\n 'valid_dataset',\n metavar='<valid_dataset_file>',\n type=lambda x: io.is_file_type(x, 'dataset'),\n help='path to validation dataset file',\n )\n parser_test.add_argument(\n 'test_dataset',\n metavar='<test_dataset_file>',\n type=lambda x: io.is_file_type(x, 'dataset'),\n help='path to test dataset file',\n )\n\n for subparser in [parser_all, parser_test]:\n subparser.add_argument(\n 'n_test',\n metavar='<n_test>',\n type=io.is_strict_pos_int,\n help='test sample size',\n nargs='?',\n default=None,\n )\n\n for subparser in [parser_all, parser_select]:\n subparser.add_argument(\n '--model_file',\n metavar='<model_file>',\n dest='model_file',\n help='user-defined model output file name',\n )\n\n \n # train\n _add_argument_dir_with_file_type(parser_train, 'task', or_file=True)\n\n # resume\n parser_resume.add_argument(\n 'model',\n metavar='<model_file>',\n type=lambda x: io.is_file_type(x, 'model'),\n help='path to model file to complete training for',\n )\n parser_resume.add_argument(\n 'dataset',\n metavar='<train_dataset_file>',\n type=lambda x: io.is_file_type(x, 'dataset'),\n help='path to original training dataset file',\n )\n\n for subparser in [parser_train, parser_resume]:\n subparser.add_argument(\n 'valid_dataset',\n metavar='<valid_dataset_file>',\n type=lambda x: io.is_file_type(x, 'dataset'),\n help='path to validation dataset file',\n )\n\n # select\n _add_argument_dir_with_file_type(parser_select, 'model')\n\n # show\n parser_show.add_argument(\n 'file',\n metavar='<file>',\n type=lambda x: io.is_valid_file_type(x),\n help='path to dataset, task or model file',\n )\n\n args = parser.parse_args()\n\n # post-processing for optional sig argument\n if 'sigs' in args and args.sigs is not None:\n args.sigs = np.hstack(\n args.sigs\n ).tolist() # flatten list, if (part of it) was generated using the range syntax\n args.sigs = sorted(list(set(args.sigs))) # remove potential duplicates\n\n # post-processing for optional model output file argument\n if 'model_file' in args and args.model_file is not None:\n if not args.model_file.endswith('.npz'):\n args.model_file += '.npz'\n\n _print_splash(args.max_processes, args.use_torch)\n\n # Check PyTorch GPU support.\n if 'use_torch' in args and args.use_torch:\n if _has_torch:\n if not torch.cuda.is_available():\n print() # TODO: print only if log level includes warning\n log.warning(\n 'Your PyTorch installation does not see any GPU(s) on your system and will thus run all calculations on the CPU! Unless this is what you want, we recommend running CPU calculations without \\'--torch\\' for improved performance.'\n )\n else:\n print()\n log.critical(\n 'Optional PyTorch dependency not found! Please run \\'pip install sgdml[torch]\\' to install it or disable the PyTorch option.'\n )\n sys.exit()\n\n # Replace solver flags with keyword.\n args = vars(args)\n args['solver'] = 'analytic'\n if 'use_cg' in args and args['use_cg']:\n args['solver'] = 'cg'\n args.pop('use_cg', None)\n\n\n # TODO: remove dummy variables once iterative solver ships\n missing_keys = ['n_inducing_pts_init', 'interact_cut_off', 'use_cg']\n for missing_key in missing_keys:\n if missing_key not in args: \n args[missing_key] = None\n\n try:\n getattr(sys.modules[__name__], args['command'])(**args)\n except AssistantError as err:\n log.error(str(err))\n sys.exit('')\n except:\n log.critical(traceback.format_exc())\n sys.exit()\n print()\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"numpy.sqrt",
"numpy.einsum",
"numpy.squeeze",
"numpy.concatenate",
"numpy.max",
"numpy.mean",
"torch.cuda.is_available",
"numpy.var",
"numpy.hstack",
"numpy.asscalar",
"numpy.arange",
"numpy.load",
"numpy.random.choice",
"numpy.isnan",
"numpy.min",
"torch.cuda.device_count",
"numpy.sum",
"numpy.abs",
"numpy.array_equal",
"numpy.sort",
"numpy.random.shuffle",
"numpy.savez_compressed",
"numpy.empty"
]
] |
whitemike889/glow
|
[
"1c36392512a98f2b7d28e36c9eb7d9ccdc8e489c"
] |
[
"torch_glow/tests/functionality/to_glow_selective_test.py"
] |
[
"# isort:skip_file\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport unittest\n\nimport torch_glow\nimport torch\n\n\nclass Qux(torch.nn.Module):\n def __init__(self, x):\n super(Qux, self).__init__()\n self.x = x\n\n def forward(self, a, b):\n return a - b - self.x\n\n\nclass Baz(torch.nn.Module):\n def __init__(self, x):\n super(Baz, self).__init__()\n self.x = x\n\n def forward(self, a, b):\n return a + b * self.x\n\n\nclass Bar(torch.nn.Module):\n def __init__(self, x):\n super(Bar, self).__init__()\n self.x = x\n\n def forward(self, a, b):\n return a * b + self.x\n\n\nclass Foo(torch.nn.Module):\n def __init__(self, bar, baz):\n super(Foo, self).__init__()\n self.bar = bar\n self.baz = baz\n\n def forward(self, a, b):\n return self.baz(self.bar(a, b), b)\n\n\nclass Model(torch.nn.Module):\n def __init__(self, foo, qux):\n super(Model, self).__init__()\n self.foo = foo\n self.qux = qux\n\n def forward(self, a, b):\n return self.qux(self.foo(a, b), a)\n\n\nr\"\"\"\n model\n / \\\n foo qux (Glow)\n / \\\n bar (Glow) baz\n\"\"\"\n\nbar = Bar(4.0)\nbaz = Baz(2.0)\nqux = Qux(3.0)\nfoo = Foo(bar, baz)\nmodel = Model(foo, qux)\n\n\nclass TestSelectiveToGlow(unittest.TestCase):\n def test_to_glow_selective(self):\n a = torch.zeros(4) + 8\n b = torch.zeros(4) + 7\n torch_res = model(a, b)\n\n spec = torch.classes.glow.GlowCompileSpec()\n spec.setBackend(\"Interpreter\")\n sim = torch.classes.glow.SpecInputMeta()\n sim.setSameAs(a)\n spec.addInputs([sim, sim])\n\n glow_mod = torch_glow.to_glow_selective(\n model, {\"foo.bar\": (spec, (a, b)), \"qux\": (spec, (a, b))}\n )\n\n glow_mod = torch.jit.trace(glow_mod, (a, b))\n glow_res = glow_mod(a, b)\n\n assert torch.allclose(torch_res, glow_res)\n"
] |
[
[
"torch.jit.trace",
"torch.zeros",
"torch.classes.glow.GlowCompileSpec",
"torch.allclose",
"torch.classes.glow.SpecInputMeta"
]
] |
atiselsts/tensorflow
|
[
"8d746f768196a2434d112e98fc26c99590986d73"
] |
[
"tensorflow/python/keras/distribute/dataset_creator_model_fit_test.py"
] |
[
"# Lint as: python3\n# Copyright 2021 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for `DatasetCreator` with `Model.fit` across usages and strategies.\"\"\"\n\nfrom absl import logging\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python import keras\nfrom tensorflow.python.compat import v2_compat\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.distribute import combinations as ds_combinations\nfrom tensorflow.python.distribute import multi_process_runner\nfrom tensorflow.python.distribute import parameter_server_strategy_v2\nfrom tensorflow.python.distribute import sharded_variable\nfrom tensorflow.python.distribute.coordinator import cluster_coordinator as coordinator_lib\nfrom tensorflow.python.framework import config\nfrom tensorflow.python.framework import test_combinations as combinations\nfrom tensorflow.python.keras import callbacks as callbacks_lib\nfrom tensorflow.python.keras.distribute import multi_worker_testing_utils\nfrom tensorflow.python.keras.distribute import strategy_combinations\nfrom tensorflow.python.keras.engine import sequential\nfrom tensorflow.python.keras.layers import core as core_layers\nfrom tensorflow.python.keras.optimizer_v2 import gradient_descent\nfrom tensorflow.python.keras.utils import dataset_creator\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.platform import gfile\nfrom tensorflow.python.platform import test\n\n\nclass DatasetCreatorModelFitTestBase(test.TestCase, parameterized.TestCase):\n\n def _model_compile(self,\n strategy,\n steps_per_execution=1,\n run_eagerly=False,\n with_normalization_layer=False):\n\n class ResultAssertingCallback(callbacks_lib.Callback):\n\n def __init__(self):\n self._prev_epoch = -1\n self._loss_to_compare_against = 2 # Empirical initial value\n\n def on_epoch_end(self, epoch, logs=None):\n logging.info(\"testModelFit: epoch=%r, logs=%r\", epoch, logs)\n if epoch <= self._prev_epoch:\n raise RuntimeError(\"Epoch is supposed to be larger than previous.\")\n self._prev_epoch = epoch\n is_loss_float = (\n logs.get(\"loss\", None) is not None and\n isinstance(logs[\"loss\"], (float, np.floating)))\n if not is_loss_float:\n raise RuntimeError(\"loss is supposed to be in the logs and float.\")\n if epoch == 0 or epoch == 9:\n # Making sure the loss of first epoch is below 1, and that of last\n # epoch is smaller than the first epoch.\n if logs[\"loss\"] > self._loss_to_compare_against:\n raise RuntimeError(\n \"loss at epoch {} is larger than previous.\".format(epoch))\n self._loss_to_compare_against = logs[\"loss\"]\n\n def on_train_end(self, logs=None):\n if self._prev_epoch != 9:\n raise RuntimeError(\"Unexpected last epoch: {}\".format(\n self._prev_epoch))\n\n # TODO(b/182193218): Use ParameterServerStrategy as a proper strategy\n # combination.\n if strategy == \"ParameterServerStrategy\":\n gpu_devices = config.list_physical_devices(\"GPU\")\n if len(gpu_devices) > 1:\n self.skipTest(\"b/178452835: Multi-GPUs not supported in \"\n \"ParameterServerStrategy.\")\n strategy = parameter_server_strategy_v2.ParameterServerStrategyV2(\n multi_worker_testing_utils.make_parameter_server_cluster(3, 2),\n variable_partitioner=sharded_variable.FixedShardsPartitioner(2))\n\n with strategy.scope():\n model = sequential.Sequential([core_layers.Dense(10)])\n if with_normalization_layer:\n norm = keras.layers.BatchNormalization(\n axis=-1, input_shape=(4, 4, 3), momentum=0.8)\n model.add(norm)\n model.add(core_layers.Dense(1, activation=\"sigmoid\"))\n self._metric = keras.metrics.Accuracy()\n\n model.compile(\n gradient_descent.SGD(),\n loss=\"binary_crossentropy\",\n metrics=[self._metric],\n steps_per_execution=steps_per_execution,\n run_eagerly=run_eagerly)\n return model, [ResultAssertingCallback()]\n\n def _model_fit(self,\n strategy,\n steps_per_execution=1,\n validation_data=None,\n x=None,\n steps_per_epoch=10,\n run_eagerly=False,\n with_normalization_layer=False,\n callbacks=None):\n if callbacks is None:\n callbacks = []\n\n model, default_callbacks = self._model_compile(strategy,\n steps_per_execution,\n run_eagerly,\n with_normalization_layer)\n callbacks += default_callbacks\n\n def dataset_fn(input_context):\n del input_context\n x = random_ops.random_uniform((10, 10))\n y = random_ops.random_uniform((10,))\n return dataset_ops.DatasetV2.from_tensor_slices(\n (x, y)).shuffle(10).repeat().batch(2)\n\n x = x or dataset_creator.DatasetCreator(dataset_fn)\n validation_data = (\n validation_data or dataset_creator.DatasetCreator(dataset_fn))\n\n model.fit(\n x,\n epochs=10,\n steps_per_epoch=steps_per_epoch,\n callbacks=callbacks,\n validation_data=validation_data,\n validation_steps=steps_per_epoch)\n return model\n\n def _model_evaluate(self,\n strategy,\n steps_per_execution=1,\n validation_data=None,\n steps=10,\n run_eagerly=False,\n with_normalization_layer=False,\n callbacks=None):\n if callbacks is None:\n callbacks = []\n\n model, default_callbacks = self._model_compile(strategy,\n steps_per_execution,\n run_eagerly,\n with_normalization_layer)\n callbacks += default_callbacks\n\n def dataset_fn(input_context):\n del input_context\n x = random_ops.random_uniform((10, 10))\n y = random_ops.random_uniform((10, 1))\n return dataset_ops.DatasetV2.from_tensor_slices(\n (x, y)).shuffle(10).repeat().batch(8)\n\n validation_data = (\n validation_data or dataset_creator.DatasetCreator(dataset_fn))\n model.evaluate(x=validation_data, steps=steps, callbacks=callbacks)\n return model\n\n\n@ds_combinations.generate(\n combinations.combine(\n strategy=strategy_combinations.all_strategies +\n strategy_combinations.multi_worker_mirrored_strategies +\n [\"ParameterServerStrategy\"],\n mode=\"eager\"))\nclass DatasetCreatorModelFitTest(DatasetCreatorModelFitTestBase):\n\n def testModelFit(self, strategy):\n model = self._model_fit(strategy)\n self.assertEqual(model.optimizer.iterations, 100)\n\n def testModelFitWithNormalizationLayer(self, strategy):\n model = self._model_fit(strategy, with_normalization_layer=True)\n self.assertEqual(model.optimizer.iterations, 100)\n\n def testModelFitWithStepsPerExecution(self, strategy):\n model = self._model_fit(strategy, steps_per_execution=10)\n self.assertEqual(model.optimizer.iterations, 100)\n\n def testModelFitWithNoStepsPerEpoch(self, strategy):\n with self.assertRaisesRegex(\n ValueError, \"When using a \"\n \"`tf.keras.utils.experimental.DatasetCreator`, `steps_per_epoch`, \"\n \"`validation_steps` or `steps` argument must be provided in \"\n \"`Model.fit` or `Model.evaluate`.\"):\n self._model_fit(strategy, steps_per_epoch=None)\n\n\n@ds_combinations.generate(\n combinations.combine(strategy=[\"ParameterServerStrategy\"], mode=\"eager\"))\nclass DatasetCreatorModelEvaluateParameterServerStrategyOnlyTest(\n DatasetCreatorModelFitTestBase):\n\n def testModelEvaluate(self, strategy):\n self._model_evaluate(strategy)\n self.assertGreaterEqual(self._metric.result(), 0.0)\n\n def testModelEvaluateWithNormalizationLayer(self, strategy):\n self._model_evaluate(strategy, with_normalization_layer=True)\n self.assertGreaterEqual(self._metric.result(), 0.0)\n\n def testModelEvaluateWithStepsPerExecution(self, strategy):\n self._model_evaluate(strategy, steps_per_execution=10)\n self.assertGreaterEqual(self._metric.result(), 0.0)\n\n def testModelEvaluateWithNoStepsPerEpoch(self, strategy):\n with self.assertRaisesRegex(\n ValueError, \"When using a \"\n \"`tf.keras.utils.experimental.DatasetCreator`, `steps_per_epoch`, \"\n \"`validation_steps` or `steps` argument must be provided in \"\n \"`Model.fit` or `Model.evaluate`.\"):\n self._model_evaluate(strategy, steps=None)\n\n def testModelEvaluateWithDatasetInstance(self, strategy):\n with self.assertRaisesRegex(\n NotImplementedError,\n \"Only `tf.keras.utils.experimental.DatasetCreator` input is supported \"\n \"with `ParameterServerStrategy` at this time. Please see \"\n \"`tf.keras.utils.experimental.DatasetCreator` class docstring for more \"\n \"information.\"\n ):\n self._model_evaluate(\n strategy,\n validation_data=dataset_ops.DatasetV2.from_tensor_slices([1, 1]))\n\n def testModelFitErrorOnBatchLevelCallbacks(self, strategy):\n\n class BatchLevelCallback(callbacks_lib.Callback):\n\n def on_train_batch_end(self, batch, logs=None):\n pass\n\n with self.assertRaisesRegex(ValueError,\n \"Batch-level `Callback`s are not supported\"):\n callbacks = [BatchLevelCallback()]\n self._model_evaluate(strategy, callbacks=callbacks)\n\n\n@ds_combinations.generate(\n combinations.combine(strategy=[\"ParameterServerStrategy\"], mode=\"eager\"))\nclass DatasetCreatorModelFitParameterServerStrategyOnlyTest(\n DatasetCreatorModelFitTestBase):\n\n def testModelFitWithRunEagerly(self, strategy):\n with self.assertRaisesRegex(\n ValueError, \"When using `Model` with `ParameterServerStrategy`, \"\n \"`run_eagerly` is not supported.\"):\n self._model_fit(strategy, run_eagerly=True)\n\n def testModelFitWithDatasetInstance(self, strategy):\n with self.assertRaisesRegex(\n NotImplementedError,\n \"Only `tf.keras.utils.experimental.DatasetCreator` input is supported \"\n \"with `ParameterServerStrategy` at this time. Please see \"\n \"`tf.keras.utils.experimental.DatasetCreator` class docstring for \"\n \"more information.\"):\n self._model_fit(\n strategy, x=dataset_ops.DatasetV2.from_tensor_slices([1, 1]))\n\n def testModelPredict(self, strategy):\n model, _ = self._model_compile(strategy)\n with self.assertRaisesRegex(\n NotImplementedError, \"`model.predict` is not yet supported with \"\n \"`ParameterServerStrategy`.\"):\n model.predict(x=dataset_ops.DatasetV2.from_tensor_slices([1, 1]))\n\n def testClusterCoordinatorSingleInstance(self, strategy):\n model = self._model_fit(strategy)\n strategy = model.distribute_strategy\n self.assertIs(strategy._cluster_coordinator,\n coordinator_lib.ClusterCoordinator(strategy))\n\n def testModelFitErrorOnBatchLevelCallbacks(self, strategy):\n\n class BatchLevelCallback(callbacks_lib.Callback):\n\n def on_train_batch_end(self, batch, logs=None):\n pass\n\n with self.assertRaisesRegex(ValueError,\n \"Batch-level `Callback`s are not supported\"):\n callbacks = [BatchLevelCallback()]\n self._model_fit(strategy, callbacks=callbacks)\n\n def testModelFitCallbackSupportsTFLogs(self, strategy):\n\n class MyCallback(callbacks_lib.Callback):\n\n def __init__(self):\n super(MyCallback, self).__init__()\n # Fetches the RemoteValues if necessary.\n self._supports_tf_logs = True\n\n def on_train_batch_end(self, batch, logs=None):\n assert isinstance(logs, coordinator_lib.RemoteValue)\n\n my_callback = MyCallback()\n callbacks = [my_callback]\n self._model_fit(strategy, callbacks=callbacks)\n\n def testModelFitVerbosity(self, strategy):\n\n class MyCallback(callbacks_lib.Callback):\n pass\n\n my_callback = MyCallback()\n callbacks = [my_callback]\n self._model_fit(strategy, callbacks=callbacks)\n # PSStrategy should default to epoch-level logging.\n self.assertEqual(my_callback.params[\"verbose\"], 2)\n\n def testModelFitTensorBoardEpochLevel(self, strategy):\n log_dir = self.get_temp_dir()\n callbacks = [callbacks_lib.TensorBoard(log_dir)]\n self._model_fit(strategy, callbacks=callbacks)\n self.assertTrue(gfile.Exists(log_dir))\n files = gfile.ListDirectory(log_dir)\n self.assertGreaterEqual(len(files), 1)\n\n\nif __name__ == \"__main__\":\n v2_compat.enable_v2_behavior()\n multi_process_runner.test_main()\n"
] |
[
[
"tensorflow.python.compat.v2_compat.enable_v2_behavior",
"tensorflow.python.framework.config.list_physical_devices",
"tensorflow.python.platform.gfile.ListDirectory",
"tensorflow.python.keras.metrics.Accuracy",
"tensorflow.python.keras.optimizer_v2.gradient_descent.SGD",
"tensorflow.python.keras.callbacks.TensorBoard",
"tensorflow.python.keras.distribute.multi_worker_testing_utils.make_parameter_server_cluster",
"tensorflow.python.keras.layers.BatchNormalization",
"tensorflow.python.distribute.coordinator.cluster_coordinator.ClusterCoordinator",
"tensorflow.python.distribute.sharded_variable.FixedShardsPartitioner",
"tensorflow.python.data.ops.dataset_ops.DatasetV2.from_tensor_slices",
"tensorflow.python.distribute.multi_process_runner.test_main",
"tensorflow.python.platform.gfile.Exists",
"tensorflow.python.keras.utils.dataset_creator.DatasetCreator",
"tensorflow.python.keras.layers.core.Dense",
"tensorflow.python.framework.test_combinations.combine",
"tensorflow.python.ops.random_ops.random_uniform"
]
] |
miruetoto/miruetoto.github.io
|
[
"42392e34e89c761ed2116d0aaf3e5736a6109a64"
] |
[
"source/pybase.py"
] |
[
"#1. import useful python packages \nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt \nfrom matplotlib.pyplot import plot \nfrom matplotlib.pyplot import imshow\n\n#2. python system \nimport warnings\nwarnings.filterwarnings(action='ignore')\n\n\n#3. rpy2 \nimport rpy2\nimport rpy2.robjects as ro\nro.r('library(devtools)') ## to use source_url \nro.r('library(tidyverse)')\n\n############################## rpy2 functions ##############################\ndef pull(r):\n return r2p(ro.globalenv[r])\n\ndef push(py,rname=None):\n import inspect\n def retrieve_name(var):\n for fi in reversed(inspect.stack()):\n names = [var_name for var_name, var_val in fi.frame.f_locals.items() if var_val is var]\n if len(names) > 0:\n return names[0]\n if rname==None: rname = retrieve_name(py)\n ro.globalenv[rname]=p2r(py)\n \ndef p2r(A):\n from rpy2.robjects.vectors import FloatVector \n from rpy2.robjects.vectors import StrVector as s2r_temp\n\n def a2r_temp(a):\n if type(a) in {float,int,bool}: a=[a]\n a=list(a)\n rtn=FloatVector(a)\n return rtn\n\n def m2r_temp(A):\n A=np.matrix(A)\n Acopy=A.T.copy()\n nrow=Acopy.shape[0]\n Acopy.shape=(np.prod(Acopy.shape),1)\n rtn=ro.r.matrix(a2r_temp(list(Acopy)),ncol=nrow)\n return rtn\n\n from rpy2.robjects import pandas2ri\n from rpy2.robjects.conversion import localconverter\n\n def pd2r_temp(A):\n with localconverter(ro.default_converter + pandas2ri.converter):\n rtn = ro.conversion.py2rpy(A)\n return rtn\n \n if type(A)==type(pd.DataFrame(np.zeros([2,2]))):\n rtn=pd2r_temp(A) \n elif type(A)==type(np.matrix(np.zeros([2,2]))):\n rtn=m2r_temp(A)\n elif type(A)==type(np.zeros([2,2])):\n if dim(A)==1: \n rtn=a2r_temp(A)\n else:\n rtn=m2r_temp(A)\n elif type(A)==str: # elif type(pd.DataFrame(np.matrix(A)).iloc[0,0])==str: 와 순서바꾸면 안됨\n rtn=s2r_temp(A) \n elif type(pd.DataFrame(np.matrix(A)).iloc[0,0])==str:\n rtn=s2r_temp(pd.DataFrame(np.matrix(A)).T.iloc[:,0])\n else:\n rtn=a2r_temp(A)\n return rtn\n\ndef r2p(A):\n from rpy2.robjects import pandas2ri\n from rpy2.robjects.conversion import localconverter\n\n def r2a_temp(a):\n return list(a)\n \n def r2m_temp(A):\n return np.matrix(A)\n \n def r2pd_temp(A):\n with localconverter(ro.default_converter + pandas2ri.converter):\n rtn = ro.conversion.rpy2py(A)\n return rtn \n \n ro.globalenv['temp']=A\n if ro.r('is.null(dim(temp))')[0]==False: ## in the cases of matrix or dataframe\n if ro.r('is.data.frame(temp)')[0]: \n rtn=r2pd_temp(A)\n elif ro.r('is.matrix(temp)')[0]:\n rtn=r2m_temp(A)\n else:\n print('I don\\`t know which type of this data in R.')\n else:\n rtn=r2a_temp(A)\n ro.r('rm(\"temp\")')\n return rtn\n\ndef cbind(*Mat):\n lenofMat=len(Mat)\n if lenofMat==1: \n print(\"You must enter two or more input objects.\")\n rtn=Mat[0]\n elif lenofMat==2: \n rtn=cbindtemp(Mat[0],Mat[1])\n else: \n rtn=cbindtemp(Mat[0],Mat[1])\n for i in np.arange(2,lenofMat):\n rtn=cbindtemp(rtn,Mat[i])\n return rtn\n\ndef rbind(*Mat):\n lenofMat=len(Mat)\n if lenofMat==1: \n print(\"You must enter two or more input objects.\")\n rtn=Mat[0]\n elif lenofMat==2: \n rtn=rbindtemp(Mat[0],Mat[1])\n else: \n rtn=rbindtemp(Mat[0],Mat[1])\n for i in np.arange(2,lenofMat):\n rtn=rbindtemp(rtn,Mat[i])\n return rtn\n\ndef cbindtemp(A,B):\n typ=['matrix','matrix']\n \n if isinstance(A, pd.core.series.Series): \n A=a2c(A)\n if isinstance(B, pd.core.series.Series): \n B=a2c(B)\n A=np.asmatrix(A)\n B=np.asmatrix(B)\n\n # row-vector에 대한 처리 \n if A.shape[0]==1: typ[0]='rowvec'\n if B.shape[0]==1: typ[1]='rowvec'\n\n # col-vector에 대한 처리 \n if A.shape[1]==1: typ[0]='colvec'\n if B.shape[1]==1: typ[1]='colvec' \n \n # 스칼라에 대한 처리 \n if A.shape==(1,1): typ[0]='scala'\n if B.shape==(1,1): typ[1]='scala'\n \n if typ==['scala','scala']: A=np.array(A); B=np.array(B)\n if typ==['scala','rowvec']: A=np.array(A); \n if typ==['scala','colvec']: A=np.full(B.shape,A[0,0]); \n if typ==['scala','matrix']: A=np.full((B.shape[0],1),A[0,0]); \n \t\n if typ==['rowvec','scala']: B=np.array(B)\n #if typ==['rowvec','rowvec']:\n if typ==['rowvec','colvec']: A=A.T\n if typ==['rowvec','matrix']: A=A.T\n \n if typ==['colvec','scala']: B=np.full(A.shape,B[0,0])\n if typ==['colvec','rowvec']: B=B.T\n #if typ==['colvec','colvec']: \n #if typ==['colvec','matrix']: \n \n if typ==['matrix','scala']: B=np.full((A.shape[0],1),B[0,0])\n if typ==['matrix','rowvec']: B=B.T\n #if typ==['matrix','colvec']: \n #if typ==['matrix','matrix']:\n \n return np.hstack([A,B])\n \ndef rbindtemp(A,B):\n typ=['matrix','matrix']\n \n A=np.asmatrix(A)\n B=np.asmatrix(B)\n\n # row-vector에 대한 처리 \n if A.shape[0]==1: typ[0]='rowvec'\n if B.shape[0]==1: typ[1]='rowvec'\n\n # col-vector에 대한 처리 \n if A.shape[1]==1: typ[0]='colvec'\n if B.shape[1]==1: typ[1]='colvec' \n \n # 스칼라에 대한 처리 \n if A.shape==(1,1): typ[0]='scala'\n if B.shape==(1,1): typ[1]='scala'\n \n if typ==['scala','scala']: A=np.array(A); B=np.array(B)\n if typ==['scala','rowvec']: A=np.full(B.shape,A[0,0]); \n if typ==['scala','colvec']: A=np.array(A);\n if typ==['scala','matrix']: A=np.full((1,B.shape[1]),A[0,0]); \n \t\n if typ==['rowvec','scala']: B=np.full((1,A.shape[1]),B[0,0]); \n #if typ==['rowvec','rowvec']:\n if typ==['rowvec','colvec']: B=B.T\n #if typ==['rowvec','matrix']: \n \n #if typ==['colvec','scala']: \n if typ==['colvec','rowvec']: A=A.T\n #if typ==['colvec','colvec']: \n if typ==['colvec','matrix']: A=A.T\n \n if typ==['matrix','scala']: B=np.full((1,A.shape[1]),B[0,0])\n #if typ==['matrix','rowvec']: \n if typ==['matrix','colvec']: B=B.T\n #if typ==['matrix','matrix']:\n \n return np.vstack([A,B])\n\ndef ids(pddata):\n push(pddata.columns,\"vname\")\n print(r2p(ro.r(\"str_c(str_c('(',str_c(1:length(vname)-1),') ',vname),collapse='\\n')\"))[0])\n\ndef l2distance(X): #X:=n*p matrix \n X=np.array(X)\n n=len(X)\n rtn=np.array(np.zeros([n,n]))\n try: \n rtn=np.sum((X[:,np.newaxis,:]-X[np.newaxis,:,:])**2,axis=-1)\n except MemoryError:\n for i in np.arange(0,n):\n rtn[i,:]=np.sum((X[i,:]-X[:,:])**2,axis=1)\n return np.asmatrix(rtn)\n\n\n"
] |
[
[
"numpy.matrix",
"numpy.hstack",
"numpy.arange",
"numpy.full",
"numpy.asmatrix",
"numpy.prod",
"numpy.array",
"numpy.zeros",
"numpy.sum",
"numpy.vstack"
]
] |
Naagar/BigGANs_seeds
|
[
"91e2cca7e889338aad888e16f5f7c6a62e8526ab"
] |
[
"utils.py"
] |
[
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n''' Utilities file\nThis file contains utility functions for bookkeeping, logging, and data loading.\nMethods which directly affect training should either go in layers, the model,\nor train_fns.py.\n'''\n\nfrom __future__ import print_function\nimport sys\nimport os\nimport numpy as np\nimport time\nimport datetime\nimport json\nimport pickle\nfrom argparse import ArgumentParser\nimport animal_hash\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader\n\nimport datasets as dset\n\nfrom BalancedBatchSampler import BalancedBatchSampler\n\ndef prepare_parser():\n usage = 'Parser for all scripts.'\n parser = ArgumentParser(description=usage)\n \n ### Dataset/Dataloader stuff ###\n parser.add_argument(\n '--dataset', type=str, default='TI64',\n help='Which Dataset to train on, out of I128, I256, C10, C100;'\n 'Append \"_hdf5\" to use the hdf5 version for ISLVRC '\n '(default: %(default)s)')\n parser.add_argument(\n '--augment', action='store_true', default=False,\n help='Augment with random crops and flips (default: %(default)s)')\n parser.add_argument(\n '--num_workers', type=int, default=8,\n help='Number of dataloader workers; consider using less for HDF5 '\n '(default: %(default)s)')\n parser.add_argument(\n '--no_pin_memory', action='store_false', dest='pin_memory', default=True,\n help='Pin data into memory through dataloader? (default: %(default)s)') \n parser.add_argument(\n '--shuffle', action='store_true', default=True,\n help='Shuffle the data (strongly recommended)? (default: %(default)s)')\n parser.add_argument(\n '--load_in_mem', action='store_true', default=False,\n help='Load all data into memory? (default: %(default)s)')\n parser.add_argument(\n '--use_multiepoch_sampler', action='store_true', default=False,\n help='Use the multi-epoch sampler for dataloader? (default: %(default)s)')\n \n \n ### Model stuff ###\n parser.add_argument(\n '--model', type=str, default='BigGAN',\n help='Name of the model module (default: %(default)s)')\n parser.add_argument(\n '--G_param', type=str, default='SN',\n help='Parameterization style to use for G, spectral norm (SN) or SVD (SVD)'\n ' or None (default: %(default)s)')\n parser.add_argument(\n '--D_param', type=str, default='SN',\n help='Parameterization style to use for D, spectral norm (SN) or SVD (SVD)'\n ' or None (default: %(default)s)') \n parser.add_argument(\n '--G_ch', type=int, default=64,\n help='Channel multiplier for G (default: %(default)s)')\n parser.add_argument(\n '--D_ch', type=int, default=64,\n help='Channel multiplier for D (default: %(default)s)')\n parser.add_argument(\n '--G_depth', type=int, default=1,\n help='Number of resblocks per stage in G? (default: %(default)s)')\n parser.add_argument(\n '--D_depth', type=int, default=1,\n help='Number of resblocks per stage in D? (default: %(default)s)')\n parser.add_argument(\n '--D_thin', action='store_false', dest='D_wide', default=True,\n help='Use the SN-GAN channel pattern for D? (default: %(default)s)')\n parser.add_argument(\n '--G_shared', action='store_true', default=False,\n help='Use shared embeddings in G? (default: %(default)s)')\n parser.add_argument(\n '--shared_dim', type=int, default=0,\n help='G''s shared embedding dimensionality; if 0, will be equal to dim_z. '\n '(default: %(default)s)')\n parser.add_argument(\n '--dim_z', type=int, default=128,\n help='Noise dimensionality: %(default)s)')\n parser.add_argument(\n '--z_var', type=float, default=1.0,\n help='Noise variance: %(default)s)') \n parser.add_argument(\n '--hier', action='store_true', default=False,\n help='Use hierarchical z in G? (default: %(default)s)')\n parser.add_argument(\n '--cross_replica', action='store_true', default=False,\n help='Cross_replica batchnorm in G?(default: %(default)s)')\n parser.add_argument(\n '--mybn', action='store_true', default=False,\n help='Use my batchnorm (which supports standing stats?) %(default)s)')\n parser.add_argument(\n '--G_nl', type=str, default='relu',\n help='Activation function for G (default: %(default)s)')\n parser.add_argument(\n '--D_nl', type=str, default='relu',\n help='Activation function for D (default: %(default)s)')\n parser.add_argument(\n '--G_attn', type=str, default='64',\n help='What resolutions to use attention on for G (underscore separated) '\n '(default: %(default)s)')\n parser.add_argument(\n '--D_attn', type=str, default='64',\n help='What resolutions to use attention on for D (underscore separated) '\n '(default: %(default)s)')\n parser.add_argument(\n '--norm_style', type=str, default='bn',\n help='Normalizer style for G, one of bn [batchnorm], in [instancenorm], '\n 'ln [layernorm], gn [groupnorm] (default: %(default)s)')\n parser.add_argument(\n '--mh_csc_loss', action='store_true', default=False,\n help='Multi hinge loss. (default: %(default)s)')\n parser.add_argument(\n '--resampling', action='store_true', default=False,\n help='For the generator step immediately following the discriminator step resample the noise. (default: %(default)s)')\n parser.add_argument(\n '--mh_loss', action='store_true', default=False,\n help='The multi-hinge loss with class agnostic and class specific update. (default: %(default)s)')\n parser.add_argument(\n '--use_unlabeled_data', action='store_true', default=False,\n help='For STL, use unlabeled data. (default: %(default)s)')\n parser.add_argument(\n '--bottom_width', type=int, default=4,\n help='Set this for image sizes not powers of 2. Usefule for STL at 48x48: %(default)s)')\n parser.add_argument(\n '--ignore_projection_discriminator', action='store_true', default=False,\n help='Use this for STL baseline experiments. (default: %(default)s)')\n parser.add_argument(\n '--fm_loss', action='store_true', default=False,\n help='Read as fm_loss ONLY. Feature matching loss for unlabeled portion of data on G step. (default: %(default)s)')\n parser.add_argument(\n '--mh_loss_weight', type=float, default=0.05,\n help='The weight for the class specific part of the multi hinge loss. Best weight for C100: %(default)s)') \n parser.add_argument(\n '--mh_fmloss_weight', type=float, default=1.0,\n help='The weight for the class agnostic feature matching part of the multi hinge loss. Best weight for C100: %(default)s)') \n \n \n \n ### Model init stuff ###\n parser.add_argument(\n '--seed', type=int, default=0,\n help='Random seed to use; affects both initialization and '\n ' dataloading. (default: %(default)s)')\n parser.add_argument(\n '--G_init', type=str, default='ortho',\n help='Init style to use for G (default: %(default)s)')\n parser.add_argument(\n '--D_init', type=str, default='ortho',\n help='Init style to use for D(default: %(default)s)')\n parser.add_argument(\n '--skip_init', action='store_true', default=False,\n help='Skip initialization, ideal for testing when ortho init was used '\n '(default: %(default)s)')\n \n ### Optimizer stuff ###\n parser.add_argument(\n '--G_lr', type=float, default=5e-5,\n help='Learning rate to use for Generator (default: %(default)s)')\n parser.add_argument(\n '--D_lr', type=float, default=2e-4,\n help='Learning rate to use for Discriminator (default: %(default)s)')\n parser.add_argument(\n '--G_B1', type=float, default=0.0,\n help='Beta1 to use for Generator (default: %(default)s)')\n parser.add_argument(\n '--D_B1', type=float, default=0.0,\n help='Beta1 to use for Discriminator (default: %(default)s)')\n parser.add_argument(\n '--G_B2', type=float, default=0.999,\n help='Beta2 to use for Generator (default: %(default)s)')\n parser.add_argument(\n '--D_B2', type=float, default=0.999,\n help='Beta2 to use for Discriminator (default: %(default)s)')\n \n ### Batch size, parallel, and precision stuff ###\n parser.add_argument(\n '--batch_size', type=int, default=16,\n help='Default overall batchsize (default: %(default)s)')\n parser.add_argument(\n '--G_batch_size', type=int, default=0,\n help='Batch size to use for G; if 0, same as D (default: %(default)s)')\n parser.add_argument(\n '--num_G_accumulations', type=int, default=1,\n help='Number of passes to accumulate G''s gradients over '\n '(default: %(default)s)') \n parser.add_argument(\n '--num_D_steps', type=int, default=2,\n help='Number of D steps per G step (default: %(default)s)')\n parser.add_argument(\n '--num_D_accumulations', type=int, default=1,\n help='Number of passes to accumulate D''s gradients over '\n '(default: %(default)s)')\n parser.add_argument(\n '--split_D', action='store_true', default=False,\n help='Run D twice rather than concatenating inputs? (default: %(default)s)')\n parser.add_argument(\n '--num_epochs', type=int, default=500,\n help='Number of epochs to train for (default: %(default)s). Related to memory, setting to 1e12 blows up memory...')\n parser.add_argument(\n '--parallel', action='store_true', default=True,\n help='Train with multiple GPUs (default: %(default)s)')\n parser.add_argument(\n '--G_fp16', action='store_true', default=False,\n help='Train with half-precision in G? (default: %(default)s)')\n parser.add_argument(\n '--D_fp16', action='store_true', default=False,\n help='Train with half-precision in D? (default: %(default)s)')\n parser.add_argument(\n '--D_mixed_precision', action='store_true', default=False,\n help='Train with half-precision activations but fp32 params in D? '\n '(default: %(default)s)')\n parser.add_argument(\n '--G_mixed_precision', action='store_true', default=False,\n help='Train with half-precision activations but fp32 params in G? '\n '(default: %(default)s)')\n parser.add_argument(\n '--accumulate_stats', action='store_true', default=False,\n help='Accumulate \"standing\" batchnorm stats? (default: %(default)s)')\n parser.add_argument(\n '--num_standing_accumulations', type=int, default=16,\n help='Number of forward passes to use in accumulating standing stats? '\n '(default: %(default)s)') \n \n ### Bookkeping stuff ### \n parser.add_argument(\n '--G_eval_mode', action='store_true', default=True,\n help='Run G in eval mode (running/standing stats?) at sample/test time? '\n '(default: %(default)s)')\n parser.add_argument(\n '--save_every', type=int, default=2000,\n help='Save every X iterations (default: %(default)s)')\n parser.add_argument(\n '--num_save_copies', type=int, default=2,\n help='How many copies to save (default: %(default)s)')\n parser.add_argument(\n '--num_best_copies', type=int, default=2,\n help='How many previous best checkpoints to save (default: %(default)s)')\n parser.add_argument(\n '--which_best', type=str, default='IS',\n help='Which metric to use to determine when to save new \"best\"'\n 'checkpoints, one of IS or FID (default: %(default)s)')\n parser.add_argument(\n '--no_fid', action='store_true', default=False,\n help='Calculate IS only, not FID? (default: %(default)s)')\n parser.add_argument(\n '--test_every', type=int, default=-1,\n help='Test every X iterations. Set to -1 to skip testing. (default: %(default)s)')\n parser.add_argument(\n '--num_inception_images', type=int, default=50000,\n help='Number of samples to compute inception metrics with '\n '(default: %(default)s)')\n parser.add_argument(\n '--hashname', action='store_true', default=False,\n help='Use a hash of the experiment name instead of the full config '\n '(default: %(default)s)') \n parser.add_argument(\n '--base_root', type=str, default='',\n help='Default location to store all weights, samples, data, and logs '\n ' (default: %(default)s)')\n parser.add_argument(\n '--data_root', type=str, default='data',\n help='Default location where data is stored (default: %(default)s)')\n parser.add_argument(\n '--weights_root', type=str, default='weights',\n help='Default location to store weights (default: %(default)s)')\n parser.add_argument(\n '--logs_root', type=str, default='logs',\n help='Default location to store logs (default: %(default)s)')\n parser.add_argument(\n '--samples_root', type=str, default='samples',\n help='Default location to store samples (default: %(default)s)') \n parser.add_argument(\n '--pbar', type=str, default='mine',\n help='Type of progressbar to use; one of \"mine\" or \"tqdm\" '\n '(default: %(default)s)')\n parser.add_argument(\n '--name_suffix', type=str, default='',\n help='Suffix for experiment name for loading weights for sampling '\n '(consider \"best0\") (default: %(default)s)')\n parser.add_argument(\n '--experiment_name', type=str, default='',\n help='Optionally override the automatic experiment naming with this arg. '\n '(default: %(default)s)')\n parser.add_argument(\n '--config_from_name', action='store_true', default=False,\n help='Use a hash of the experiment name instead of the full config '\n '(default: %(default)s)')\n parser.add_argument(\n '--historical_save_every', type=int, default=1e9,\n help='Save a non-overwritten version every X iterations (default: %(default)s)')\n \n \n ### EMA Stuff ###\n parser.add_argument(\n '--ema', action='store_true', default=False,\n help='Keep an ema of G''s weights? (default: %(default)s)')\n parser.add_argument(\n '--ema_decay', type=float, default=0.9999,\n help='EMA decay rate (default: %(default)s)')\n parser.add_argument(\n '--use_ema', action='store_true', default=False,\n help='Use the EMA parameters of G for evaluation? (default: %(default)s)')\n parser.add_argument(\n '--ema_start', type=int, default=0,\n help='When to start updating the EMA weights (default: %(default)s)')\n \n ### Numerical precision and SV stuff ### \n parser.add_argument(\n '--adam_eps', type=float, default=1e-8,\n help='epsilon value to use for Adam (default: %(default)s)')\n parser.add_argument(\n '--BN_eps', type=float, default=1e-5,\n help='epsilon value to use for BatchNorm (default: %(default)s)')\n parser.add_argument(\n '--SN_eps', type=float, default=1e-8,\n help='epsilon value to use for Spectral Norm(default: %(default)s)')\n parser.add_argument(\n '--num_G_SVs', type=int, default=1,\n help='Number of SVs to track in G (default: %(default)s)')\n parser.add_argument(\n '--num_D_SVs', type=int, default=1,\n help='Number of SVs to track in D (default: %(default)s)')\n parser.add_argument(\n '--num_G_SV_itrs', type=int, default=1,\n help='Number of SV itrs in G (default: %(default)s)')\n parser.add_argument(\n '--num_D_SV_itrs', type=int, default=1,\n help='Number of SV itrs in D (default: %(default)s)')\n \n ### Ortho reg stuff ### \n parser.add_argument(\n '--G_ortho', type=float, default=0.0, # 1e-4 is default for BigGAN\n help='Modified ortho reg coefficient in G(default: %(default)s)')\n parser.add_argument(\n '--D_ortho', type=float, default=0.0,\n help='Modified ortho reg coefficient in D (default: %(default)s)')\n parser.add_argument(\n '--toggle_grads', action='store_true', default=True,\n help='Toggle D and G''s \"requires_grad\" settings when not training them? '\n ' (default: %(default)s)')\n \n ### Which train function ###\n parser.add_argument(\n '--which_train_fn', type=str, default='GAN',\n help='How2trainyourbois (default: %(default)s)') \n \n ### Resume training stuff\n parser.add_argument(\n '--load_weights', type=str, default='copy0',\n help='Suffix for which weights to load (e.g. best0, copy0) '\n '(default: %(default)s)')\n parser.add_argument(\n '--resume', action='store_true', default=False,\n help='Resume training? (default: %(default)s)')\n \n ### Log stuff ###\n parser.add_argument(\n '--logstyle', type=str, default='%3.3e',\n help='What style to use when logging training metrics?'\n 'One of: %#.#f/ %#.#e (float/exp, text),'\n 'pickle (python pickle),'\n 'npz (numpy zip),'\n 'mat (MATLAB .mat file) (default: %(default)s)')\n parser.add_argument(\n '--log_G_spectra', action='store_true', default=False,\n help='Log the top 3 singular values in each SN layer in G? '\n '(default: %(default)s)')\n parser.add_argument(\n '--log_D_spectra', action='store_true', default=False,\n help='Log the top 3 singular values in each SN layer in D? '\n '(default: %(default)s)')\n parser.add_argument(\n '--sv_log_interval', type=int, default=10,\n help='Iteration interval for logging singular values '\n ' (default: %(default)s)') \n \n return parser\n\n# Arguments for sample.py; not presently used in train.py\ndef add_sample_parser(parser):\n parser.add_argument(\n '--sample_npz', action='store_true', default=False,\n help='Sample \"sample_num_npz\" images and save to npz? '\n '(default: %(default)s)')\n parser.add_argument(\n '--sample_num_npz', type=int, default=50000,\n help='Number of images to sample when sampling NPZs '\n '(default: %(default)s)')\n parser.add_argument(\n '--sample_sheets', action='store_true', default=False,\n help='Produce class-conditional sample sheets and stick them in '\n 'the samples root? (default: %(default)s)')\n parser.add_argument(\n '--sample_classwise', action='store_true', default=False,\n help='Produce class-conditional sample sheets and stick them in '\n 'the samples root? (default: %(default)s)')\n parser.add_argument(\n '--sample_interps', action='store_true', default=False,\n help='Produce interpolation sheets and stick them in '\n 'the samples root? (default: %(default)s)') \n parser.add_argument(\n '--sample_sheet_folder_num', type=int, default=-1,\n help='Number to use for the folder for these sample sheets '\n '(default: %(default)s)')\n parser.add_argument(\n '--sample_random', action='store_true', default=False,\n help='Produce a single random sheet? (default: %(default)s)')\n parser.add_argument(\n '--sample_trunc_curves', type=str, default='',\n help='Get inception metrics with a range of variances?'\n 'To use this, specify a startpoint, step, and endpoint, e.g. '\n '--sample_trunc_curves 0.2_0.1_1.0 for a startpoint of 0.2, '\n 'endpoint of 1.0, and stepsize of 1.0. Note that this is '\n 'not exactly identical to using tf.truncated_normal, but should '\n 'have approximately the same effect. (default: %(default)s)')\n parser.add_argument(\n '--sample_inception_metrics', action='store_true', default=False,\n help='Calculate Inception metrics with sample.py? (default: %(default)s)') \n parser.add_argument(\n '--sample_np_mem', action='store_true', default=False,\n help='Sample the GAN and stick it in memory. (default: %(default)s)')\n parser.add_argument(\n '--official_IS', action='store_true', default=False,\n help='Run the official inception score code. (default: %(default)s)')\n parser.add_argument(\n '--official_FID', action='store_true', default=False,\n help='Run the official frechet inception distance code. (default: %(default)s)')\n parser.add_argument(\n '--overwrite', action='store_true', default=False,\n help='Force recompute IS|FID scores (default: %(default)s)')\n parser.add_argument(\n '--dataset_is_fid', type=str, default='',\n help='Full path to the file that contains the FID moments for the dataset. (default: %(default)s)')\n parser.add_argument(\n '--sample_multiple', action='store_true', default=False,\n help='When true the load_weights argument is assumed to be a comma separated string of multiple saved model names, so sampling will be run for each entry (default: %(default)s)')\n parser.add_argument(\n '--get_test_error', action='store_true', default=False,\n help='Load the test set for the dataset and see the classifier/discriminator error. (default: %(default)s)')\n parser.add_argument(\n '--get_train_error', action='store_true', default=False,\n help='Load the train set for the dataset and see the classifier/discriminator error. (default: %(default)s)')\n parser.add_argument(\n '--get_self_error', action='store_true', default=False,\n help='See the classifier/discriminator error on generated images where the conditional y is the ground truth. (default: %(default)s)')\n parser.add_argument(\n '--get_generator_error', action='store_true', default=False,\n help='Use an auxiliary pre-trained classifier network to classify the generated images from the model and record accuracy with the conditional y as the ground truth. (default: %(default)s)')\n parser.add_argument(\n '--sample_num_error', type=int, default=10000,\n help='Number of images to sample when sampling train/test/self/generator error '\n '(default: %(default)s)')\n return parser\n\n# Convenience dicts\ndset_dict = {'I32': dset.ImageFolder, 'I64': dset.ImageFolder,\n 'TI64': dset.ImageFolder,'TI64_hdf5': dset.ILSVRC_HDF5, \n 'I128': dset.ImageFolder, 'I256': dset.ImageFolder,\n 'I32_hdf5': dset.ILSVRC_HDF5, 'I64_hdf5': dset.ILSVRC_HDF5, \n 'I128_hdf5': dset.ILSVRC_HDF5, 'I256_hdf5': dset.ILSVRC_HDF5,\n 'C10': dset.CIFAR10, 'C100': dset.CIFAR100,\n 'STL64': dset.STL10, 'STL32': dset.STL10, 'STL48': dset.STL10, 'STL96': dset.STL10,\n}\nimsize_dict = {'I32': 32, 'I32_hdf5': 32,\n 'I64': 64, 'I64_hdf5': 64,\n 'TI64': 256, 'TI64_hdf5': 64,\n 'I128': 128, 'I128_hdf5': 128,\n 'I256': 256, 'I256_hdf5': 256,\n 'C10': 32, 'C100': 32, 'STL64': 64, 'STL32': 32, 'STL48': 48, 'STL96': 96,\n}\nroot_dict = {'I32': 'ImageNet', 'I32_hdf5': 'ILSVRC32.hdf5',\n 'I64': 'train', 'I64_hdf5': 'ILSVRC64.hdf5',\n 'TI64': 'train', 'TI64_hdf5': 'TILSVRC64.hdf5',\n 'I128': 'train', 'I128_hdf5': 'ILSVRC128.hdf5',\n 'I256': 'ImageNet', 'I256_hdf5': 'ILSVRC256.hdf5',\n 'C10': 'cifar', 'C100': 'cifar', 'STL64': 'stl10', 'STL32': 'stl10', 'STL48': 'stl10', 'STL96': 'stl10',\n}\nnclass_dict = {'I32': 1000, 'I32_hdf5': 1000,\n 'I64': 1000, 'I64_hdf5': 1000,\n 'TI64': 4, 'TI64_hdf5': 200,\n 'I128': 1000, 'I128_hdf5': 1000,\n 'I256': 1000, 'I256_hdf5': 1000,\n 'C10': 10, 'C100': 100, 'STL64': 10, 'STL32': 10, 'STL48': 10, 'STL96': 10,\n}\n# Number of classes to put per sample sheet \nclasses_per_sheet_dict = {'I32': 50, 'I32_hdf5': 50,\n 'I64': 50, 'I64_hdf5': 50,\n 'TI64': 1, 'TI64_hdf5': 50,\n 'I128': 20, 'I128_hdf5': 20,\n 'I256': 20, 'I256_hdf5': 20,\n 'C10': 10, 'C100': 25, 'STL64': 10, 'STL32': 10, 'STL48': 10, 'STL96': 10,\n}\nactivation_dict = {'inplace_relu': nn.ReLU(inplace=True),\n 'relu': nn.ReLU(inplace=False),\n 'ir': nn.ReLU(inplace=True),}\n\nclass CenterCropLongEdge(object):\n \"\"\"Crops the given PIL Image on the long edge.\n Args:\n size (sequence or int): Desired output size of the crop. If size is an\n int instead of sequence like (h, w), a square crop (size, size) is\n made.\n \"\"\"\n def __call__(self, img):\n \"\"\"\n Args:\n img (PIL Image): Image to be cropped.\n Returns:\n PIL Image: Cropped image.\n \"\"\"\n return transforms.functional.center_crop(img, min(img.size))\n\n def __repr__(self):\n return self.__class__.__name__\n\nclass RandomCropLongEdge(object):\n \"\"\"Crops the given PIL Image on the long edge with a random start point.\n Args:\n size (sequence or int): Desired output size of the crop. If size is an\n int instead of sequence like (h, w), a square crop (size, size) is\n made.\n \"\"\"\n def __call__(self, img):\n \"\"\"\n Args:\n img (PIL Image): Image to be cropped.\n Returns:\n PIL Image: Cropped image.\n \"\"\"\n # height, width\n size = (min(img.size), min(img.size))\n # Only step forward along this edge if it's the long edge\n top = (0 if size[0] == img.size[0] \n else np.random.randint(low=0,high=img.size[0] - size[0]))\n left = (0 if size[1] == img.size[1]\n else np.random.randint(low=0,high=img.size[1] - size[1]))\n return transforms.functional.crop(img, top, left, size[0], size[1])\n\n def __repr__(self):\n return self.__class__.__name__\n\n \n# multi-epoch Dataset sampler to avoid memory leakage and enable resumption of\n# training from the same sample regardless of if we stop mid-epoch\nclass MultiEpochSampler(torch.utils.data.Sampler):\n r\"\"\"Samples elements randomly over multiple epochs\n\n Arguments:\n data_source (Dataset): dataset to sample from\n num_epochs (int) : Number of times to loop over the dataset\n start_itr (int) : which iteration to begin from\n \"\"\"\n\n def __init__(self, data_source, num_epochs, start_itr=0, batch_size=128):\n self.data_source = data_source\n self.num_samples = len(self.data_source)\n self.num_epochs = num_epochs\n self.start_itr = start_itr\n self.batch_size = batch_size\n\n if not isinstance(self.num_samples, int) or self.num_samples <= 0:\n raise ValueError(\"num_samples should be a positive integeral \"\n \"value, but got num_samples={}\".format(self.num_samples))\n\n def __iter__(self):\n n = len(self.data_source)\n # Determine number of epochs\n num_epochs = int(np.ceil((n * self.num_epochs \n - (self.start_itr * self.batch_size)) / float(n)))\n # Sample all the indices, and then grab the last num_epochs index sets;\n # This ensures if we're starting at epoch 4, we're still grabbing epoch 4's\n # indices\n out = [torch.randperm(n) for epoch in range(self.num_epochs)][-num_epochs:]\n # Ignore the first start_itr % n indices of the first epoch\n out[0] = out[0][(self.start_itr * self.batch_size % n):]\n # if self.replacement:\n # return iter(torch.randint(high=n, size=(self.num_samples,), dtype=torch.int64).tolist())\n # return iter(.tolist())\n output = torch.cat(out).tolist()\n print('Length dataset output is %d' % len(output))\n return iter(output)\n\n def __len__(self):\n return len(self.data_source) * self.num_epochs - self.start_itr * self.batch_size\n\n# function to balance the dataset \ndef make_weights_for_balanced_classes(images, nclasses): \n count = [0] * nclasses \n for item in images: \n count[item[1]] += 1 \n weight_per_class = [0.] * nclasses \n N = float(sum(count)) \n for i in range(nclasses): \n weight_per_class[i] = N/float(count[i]) \n weight = [0] * len(images) \n for idx, val in enumerate(images): \n weight[idx] = weight_per_class[val[1]] \n return weight\n\n# Convenience function to centralize all data loaders\ndef get_data_loaders(dataset, data_root=None, augment=False, batch_size=64, \n num_workers=8, shuffle=True, load_in_mem=False, hdf5=False,\n pin_memory=True, drop_last=True, start_itr=0,\n num_epochs=500, use_multiepoch_sampler=False, use_unlabeled_data=False,\n use_test_set=False,\n **kwargs):\n\n # Append /FILENAME.hdf5 to root if using hdf5\n data_root += '/%s' % root_dict[dataset]\n print('Using dataset root location %s' % data_root)\n\n which_dataset = dset_dict[dataset]\n norm_mean = [0.5,0.5,0.5]\n norm_std = [0.5,0.5,0.5]\n image_size = imsize_dict[dataset]\n # For image folder datasets, name of the file where we store the precomputed\n # image locations to avoid having to walk the dirs every time we load.\n dataset_kwargs = {'index_filename': '%s_imgs.npz' % dataset}\n if use_test_set:\n if dataset in ['C10', 'C100']:\n dataset_kwargs['train'] = False\n if dataset in ['STL64', 'STL32', 'STL48']:\n dataset_kwargs['train'] = False\n dataset_kwargs['unlabeled'] = False\n \n # HDF5 datasets have their own inbuilt transform, no need to train_transform \n if 'hdf5' in dataset:\n train_transform = None\n else:\n if augment:\n print('Data will be augmented...')\n if dataset in ['C10', 'C100']:\n train_transform = [transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip()]\n elif dataset in ['STL96']:\n train_transform = [transforms.RandomCrop(96, padding=4),\n transforms.RandomHorizontalFlip()]\n elif dataset in ['STL64', 'STL32', 'STL48']:\n train_transform = [transforms.RandomCrop(90),\n transforms.Resize(image_size),\n transforms.RandomHorizontalFlip()]\n else:\n train_transform = [RandomCropLongEdge(),\n transforms.Resize(image_size),\n transforms.RandomHorizontalFlip()]\n else:\n print('Data will not be augmented...')\n if dataset in ['C10', 'C100']:\n train_transform = []\n else:\n train_transform = [CenterCropLongEdge(), transforms.Resize(image_size)]\n # train_transform = [transforms.Resize(image_size), transforms.CenterCrop]\n train_transform = transforms.Compose(train_transform + [\n transforms.ToTensor(),\n transforms.Normalize(norm_mean, norm_std)])\n train_set = which_dataset(root=data_root, transform=train_transform,\n load_in_mem=load_in_mem, **dataset_kwargs)\n\n # Prepare loader; the loaders list is for forward compatibility with\n # using validation / test splits.\n loaders = [] \n if use_multiepoch_sampler:\n print('Using multiepoch sampler from start_itr %d...' % start_itr)\n loader_kwargs = {'num_workers': num_workers, 'pin_memory': pin_memory, 'drop_last': drop_last}\n sampler = MultiEpochSampler(train_set, num_epochs, start_itr, batch_size)\n train_loader = DataLoader(train_set, batch_size=batch_size,\n sampler=sampler, **loader_kwargs)\n else:\n loader_kwargs = {'num_workers': num_workers, 'pin_memory': pin_memory,\n 'drop_last': drop_last} # Default, drop last incomplete batch\n\n # Batch sampler \n balanced_batch_sampler = BalancedBatchSampler(train_set,n_classes=4, n_samples=4)\n # Sampler \n weights = make_weights_for_balanced_classes(train_set, nclasses=4) \n weights = torch.DoubleTensor(weights) \n sampler = torch.utils.data.sampler.WeightedRandomSampler(weights, len(weights)) \n\n train_loader = DataLoader(train_set, batch_sampler=balanced_batch_sampler)\n\n # seed_train = torchvision.dataset.ImageFolder(root=data_root,batch_size=batch_size,)\n # train_loader_new = \n\n loaders.append(train_loader)\n if (dataset in ['STL64', 'STL32', 'STL48', 'STL96']) and use_unlabeled_data:\n loader_kwargs = {'num_workers': num_workers, 'pin_memory': pin_memory, 'drop_last': drop_last}\n # MultiEpochSampler here will lead to memory use blowing up\n #sampler = MultiEpochSampler(train_set, num_epochs, start_itr, batch_size)\n class MyLiteDataLoader(object):\n\n def __init__(self, raw_loader, batch_size):\n self.unlimit_gen = self.generator(True)\n self.raw_loader = raw_loader\n self.bs = batch_size\n \n def generator(self, inf=False):\n while True:\n theloader = DataLoader(self.raw_loader, batch_size=self.bs, shuffle=True, **loader_kwargs)\n for xy in theloader:\n x, y = xy\n yield x, y\n if not inf: break\n \n def next(self):\n return next(self.unlimit_gen)\n \n def get_iter(self):\n return self.generator()\n \n def __len__(self):\n return len(self.raw_loader)\n \n unl_set = which_dataset(root=data_root, transform=train_transform,\n load_in_mem=load_in_mem, train=False, **dataset_kwargs)\n unl_loader = MyLiteDataLoader(unl_set, batch_size)\n loaders.append(unl_loader)\n \n return loaders\n\n\n# Utility file to seed rngs\ndef seed_rng(seed):\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n np.random.seed(seed)\n\n\n# Utility to peg all roots to a base root\n# If a base root folder is provided, peg all other root folders to it.\ndef update_config_roots(config):\n if config['base_root']:\n print('Pegging all root folders to base root %s' % config['base_root'])\n for key in ['data', 'weights', 'logs', 'samples']:\n config['%s_root' % key] = '%s/%s' % (config['base_root'], key)\n return config\n\n\n# Utility to prepare root folders if they don't exist; parent folder must exist\ndef prepare_root(config):\n for key in ['weights_root', 'logs_root', 'samples_root']:\n if not os.path.exists(config[key]):\n print('Making directory %s for %s...' % (config[key], key))\n os.mkdir(config[key])\n\n\n# Simple wrapper that applies EMA to a model. COuld be better done in 1.0 using\n# the parameters() and buffers() module functions, but for now this works\n# with state_dicts using .copy_\nclass ema(object):\n def __init__(self, source, target, decay=0.9999, start_itr=0):\n self.source = source\n self.target = target\n self.decay = decay\n # Optional parameter indicating what iteration to start the decay at\n self.start_itr = start_itr\n # Initialize target's params to be source's\n self.source_dict = self.source.state_dict()\n self.target_dict = self.target.state_dict()\n print('Initializing EMA parameters to be source parameters...')\n with torch.no_grad():\n for key in self.source_dict:\n self.target_dict[key].data.copy_(self.source_dict[key].data)\n # target_dict[key].data = source_dict[key].data # Doesn't work!\n\n def update(self, itr=None):\n # If an iteration counter is provided and itr is less than the start itr,\n # peg the ema weights to the underlying weights.\n if itr and itr < self.start_itr:\n decay = 0.0\n else:\n decay = self.decay\n with torch.no_grad():\n for key in self.source_dict:\n self.target_dict[key].data.copy_(self.target_dict[key].data * decay \n + self.source_dict[key].data * (1 - decay))\n\n\n# Apply modified ortho reg to a model\n# This function is an optimized version that directly computes the gradient,\n# instead of computing and then differentiating the loss.\ndef ortho(model, strength=1e-4, blacklist=[]):\n with torch.no_grad():\n for param in model.parameters():\n # Only apply this to parameters with at least 2 axes, and not in the blacklist\n if len(param.shape) < 2 or any([param is item for item in blacklist]):\n continue\n w = param.view(param.shape[0], -1)\n grad = (2 * torch.mm(torch.mm(w, w.t()) \n * (1. - torch.eye(w.shape[0], device=w.device)), w))\n param.grad.data += strength * grad.view(param.shape)\n\n\n# Default ortho reg\n# This function is an optimized version that directly computes the gradient,\n# instead of computing and then differentiating the loss.\ndef default_ortho(model, strength=1e-4, blacklist=[]):\n with torch.no_grad():\n for param in model.parameters():\n # Only apply this to parameters with at least 2 axes & not in blacklist\n if len(param.shape) < 2 or param in blacklist:\n continue\n w = param.view(param.shape[0], -1)\n grad = (2 * torch.mm(torch.mm(w, w.t()) \n - torch.eye(w.shape[0], device=w.device), w))\n param.grad.data += strength * grad.view(param.shape)\n\n\n# Convenience utility to switch off requires_grad\ndef toggle_grad(model, on_or_off):\n for param in model.parameters():\n param.requires_grad = on_or_off\n\n\n# Function to join strings or ignore them\n# Base string is the string to link \"strings,\" while strings\n# is a list of strings or Nones.\ndef join_strings(base_string, strings):\n return base_string.join([item for item in strings if item])\n\n\n# Save a model's weights, optimizer, and the state_dict\ndef save_weights(G, D, state_dict, weights_root, experiment_name, \n name_suffix=None, G_ema=None):\n root = '/'.join([weights_root, experiment_name])\n if not os.path.exists(root):\n os.mkdir(root)\n # print(root)\n if name_suffix:\n print('Saving weights to %s/%s...' % (root, name_suffix))\n else:\n print('Saving weights to %s...' % root)\n torch.save(G.state_dict(), \n '%s/%s.pth' % (root, join_strings('_', ['G', name_suffix])))\n torch.save(G.optim.state_dict(), \n '%s/%s.pth' % (root, join_strings('_', ['G_optim', name_suffix])))\n torch.save(D.state_dict(), \n '%s/%s.pth' % (root, join_strings('_', ['D', name_suffix])))\n torch.save(D.optim.state_dict(),\n '%s/%s.pth' % (root, join_strings('_', ['D_optim', name_suffix])))\n torch.save(state_dict,\n '%s/%s.pth' % (root, join_strings('_', ['state_dict', name_suffix])))\n if G_ema is not None:\n torch.save(G_ema.state_dict(), \n '%s/%s.pth' % (root, join_strings('_', ['G_ema', name_suffix])))\n\n\n# Load a model's weights, optimizer, and the state_dict\ndef load_weights(G, D, state_dict, weights_root, experiment_name, \n name_suffix=None, G_ema=None, strict=True, load_optim=True):\n root = '/'.join([weights_root, experiment_name])\n if name_suffix:\n print('Loading %s weights from %s...' % (name_suffix, root))\n else:\n print('Loading weights from %s...' % root)\n if G is not None:\n G.load_state_dict(\n torch.load('%s/%s.pth' % (root, join_strings('_', ['G', name_suffix]))),\n strict=strict)\n if load_optim:\n G.optim.load_state_dict(\n torch.load('%s/%s.pth' % (root, join_strings('_', ['G_optim', name_suffix]))))\n if D is not None:\n D.load_state_dict(\n torch.load('%s/%s.pth' % (root, join_strings('_', ['D', name_suffix]))),\n strict=strict)\n if load_optim:\n D.optim.load_state_dict(\n torch.load('%s/%s.pth' % (root, join_strings('_', ['D_optim', name_suffix]))))\n # Load state dict\n for item in state_dict:\n state_dict[item] = torch.load('%s/%s.pth' % (root, join_strings('_', ['state_dict', name_suffix])))[item]\n if G_ema is not None:\n G_ema.load_state_dict(\n torch.load('%s/%s.pth' % (root, join_strings('_', ['G_ema', name_suffix]))),\n strict=strict)\n\n\n''' MetricsLogger originally stolen from VoxNet source code.\n Used for logging inception metrics'''\nclass MetricsLogger(object):\n def __init__(self, fname, reinitialize=False):\n self.fname = fname\n self.reinitialize = reinitialize\n if os.path.exists(self.fname):\n if self.reinitialize:\n print('{} exists, deleting...'.format(self.fname))\n os.remove(self.fname)\n\n def log(self, record=None, **kwargs):\n \"\"\"\n Assumption: no newlines in the input.\n \"\"\"\n if record is None:\n record = {}\n record.update(kwargs)\n record['_stamp'] = time.time()\n with open(self.fname, 'a') as f:\n f.write(json.dumps(record, ensure_ascii=True) + '\\n')\n\n\n# Logstyle is either:\n# '%#.#f' for floating point representation in text\n# '%#.#e' for exponent representation in text\n# 'npz' for output to npz # NOT YET SUPPORTED\n# 'pickle' for output to a python pickle # NOT YET SUPPORTED\n# 'mat' for output to a MATLAB .mat file # NOT YET SUPPORTED\nclass MyLogger(object):\n def __init__(self, fname, reinitialize=False, logstyle='%3.3f'):\n self.root = fname\n if not os.path.exists(self.root):\n # os.mkdir(self.root)\n print(self.root)\n self.reinitialize = reinitialize\n self.metrics = []\n self.logstyle = logstyle # One of '%3.3f' or like '%3.3e'\n\n # Delete log if re-starting and log already exists\n def reinit(self, item):\n if os.path.exists('%s/%s.log' % (self.root, item)):\n if self.reinitialize:\n # Only print the removal mess\n if 'sv' in item :\n if not any('sv' in item for item in self.metrics):\n print('Deleting singular value logs...')\n else:\n print('{} exists, deleting...'.format('%s_%s.log' % (self.root, item)))\n os.remove('%s/%s.log' % (self.root, item))\n \n # Log in plaintext; this is designed for being read in MATLAB(sorry not sorry)\n def log(self, itr, **kwargs):\n for arg in kwargs:\n if arg not in self.metrics:\n if self.reinitialize:\n self.reinit(arg)\n self.metrics += [arg]\n if self.logstyle == 'pickle':\n print('Pickle not currently supported...')\n # with open('%s/%s.log' % (self.root, arg), 'a') as f:\n # pickle.dump(kwargs[arg], f)\n elif self.logstyle == 'mat':\n print('.mat logstyle not currently supported...')\n else:\n with open('%s/%s.log' % (self.root, arg), 'a') as f:\n f.write('%d: %s\\n' % (itr, self.logstyle % kwargs[arg]))\n\n\n# Write some metadata to the logs directory\ndef write_metadata(logs_root, experiment_name, config, state_dict):\n with open(('%s/%s/metalog.txt' % \n (logs_root, experiment_name)), 'w') as writefile:\n writefile.write('datetime: %s\\n' % str(datetime.datetime.now()))\n writefile.write('config: %s\\n' % str(config))\n writefile.write('state: %s\\n' %str(state_dict))\n\n\n\"\"\"\nVery basic progress indicator to wrap an iterable in.\n\nAuthor: Jan Schlüter\nAndy's adds: time elapsed in addition to ETA, makes it possible to add\nestimated time to 1k iters instead of estimated time to completion.\n\"\"\"\ndef progress(items, desc='', total=None, min_delay=0.1, displaytype='s1k'):\n \"\"\"\n Returns a generator over `items`, printing the number and percentage of\n items processed and the estimated remaining processing time before yielding\n the next item. `total` gives the total number of items (required if `items`\n has no length), and `min_delay` gives the minimum time in seconds between\n subsequent prints. `desc` gives an optional prefix text (end with a space).\n \"\"\"\n total = total or len(items)\n t_start = time.time()\n t_last = 0\n for n, item in enumerate(items):\n t_now = time.time()\n if t_now - t_last > min_delay:\n print(\"\\r%s%d/%d (%6.2f%%)\" % (\n desc, n+1, total, n / float(total) * 100), end=\" \")\n if n > 0:\n \n if displaytype == 's1k': # minutes/seconds for 1000 iters\n next_1000 = n + (1000 - n%1000)\n t_done = t_now - t_start\n t_1k = t_done / n * next_1000\n outlist = list(divmod(t_done, 60)) + list(divmod(t_1k - t_done, 60))\n print(\"(TE/ET1k: %d:%02d / %d:%02d)\" % tuple(outlist), end=\" \")\n else:# displaytype == 'eta':\n t_done = t_now - t_start\n t_total = t_done / n * total\n outlist = list(divmod(t_done, 60)) + list(divmod(t_total - t_done, 60))\n print(\"(TE/ETA: %d:%02d / %d:%02d)\" % tuple(outlist), end=\" \")\n \n sys.stdout.flush()\n t_last = t_now\n yield item\n t_total = time.time() - t_start\n print(\"\\r%s%d/%d (100.00%%) (took %d:%02d)\" % ((desc, total, total) +\n divmod(t_total, 60)))\n\n\n# Sample function for use with inception metrics\ndef sample(G, z_, y_, config):\n with torch.no_grad():\n z_.sample_()\n y_.sample_()\n if config['parallel']:\n G_z = nn.parallel.data_parallel(G, (z_, G.shared(y_)))\n else:\n G_z = G(z_, G.shared(y_))\n return G_z, y_\n\n\n# Sample function for sample sheets\ndef sample_sheet(G, classes_per_sheet, num_classes, samples_per_class, parallel,\n samples_root, experiment_name, folder_number, z_=None):\n folder_number = int(folder_number)\n # Prepare sample directory\n if not os.path.isdir('%s/%s' % (samples_root, experiment_name)):\n os.mkdir('%s/%s' % (samples_root, experiment_name))\n if not os.path.isdir('%s/%s/%d' % (samples_root, experiment_name, folder_number)):\n os.mkdir('%s/%s/%d' % (samples_root, experiment_name, folder_number))\n # loop over total number of sheets\n for i in range(num_classes // classes_per_sheet):\n ims = []\n y = torch.arange(i * classes_per_sheet, (i + 1) * classes_per_sheet, device='cuda')\n # print(y)\n for j in range(samples_per_class):\n if (z_ is not None) and hasattr(z_, 'sample_') and classes_per_sheet <= z_.size(0):\n z_.sample_()\n else:\n z_ = torch.randn(classes_per_sheet, G.dim_z, device='cuda') \n with torch.no_grad():\n if parallel:\n o = nn.parallel.data_parallel(G, (z_[:classes_per_sheet], G.shared(y)))\n else:\n o = G(z_[:classes_per_sheet], G.shared(y))\n\n ims += [o.data.cpu()]\n # This line should properly unroll the images\n out_ims = torch.stack(ims, 1).view(-1, ims[0].shape[1], ims[0].shape[2], \n ims[0].shape[3]).data.float().cpu()\n # The path for the samples\n image_filename = '%s/%s/%d/samples%d.jpg' % (samples_root, experiment_name, \n folder_number, i)\n torchvision.utils.save_image(out_ims, image_filename,\n nrow=samples_per_class, normalize=True)\n\n## Generating images classwise for each class \ndef sample_classwise(G, classes_per_sheet, num_classes, samples_per_class, parallel,\n samples_root, experiment_name, folder_number,img_class,img_no,img_class_no, z_=None):\n folder_number = int(folder_number)\n # Prepare sample directory\n # print(img_class)\n if not os.path.isdir('%s/%s' % (samples_root, experiment_name)):\n os.mkdir('%s/%s' % (samples_root, experiment_name))\n if not os.path.isdir('%s/%s/%d' % (samples_root, experiment_name, folder_number)):\n os.mkdir('%s/%s/%d' % (samples_root, experiment_name, folder_number))\n if not os.path.isdir('%s/%s/%d/%s' % (samples_root, experiment_name, folder_number,img_class)):\n os.mkdir('%s/%s/%d/%s' % (samples_root, experiment_name, folder_number, img_class))\n # loop over total number of sheets\n for i in range(num_classes // classes_per_sheet):\n ims = []\n y = torch.arange(img_class_no * classes_per_sheet, (img_class_no + 1) * classes_per_sheet, device='cuda')\n # print(y)\n for j in range(samples_per_class):\n if (z_ is not None) and hasattr(z_, 'sample_') and classes_per_sheet <= z_.size(0):\n z_.sample_()\n else:\n z_ = torch.randn(classes_per_sheet, G.dim_z, device='cuda') \n with torch.no_grad():\n if parallel:\n o = nn.parallel.data_parallel(G, (z_[:classes_per_sheet], G.shared(y)))\n else:\n o = G(z_[:classes_per_sheet], G.shared(y))\n\n ims += [o.data.cpu()]\n # This line should properly unroll the images\n out_ims = torch.stack(ims, 1).view(-1, ims[0].shape[1], ims[0].shape[2], \n ims[0].shape[3]).data.float().cpu()\n # The path for the samples\n image_filename = '%s/%s/%d/%s/samples_fake_cond_BigGAN_%s_%d_.jpg' % (samples_root, experiment_name, \n folder_number,img_class,img_class, img_no)\n torchvision.utils.save_image(out_ims, image_filename,\n nrow=samples_per_class, normalize=True)\n\n\n\n\n\n\n\n# Interp function; expects x0 and x1 to be of shape (shape0, 1, rest_of_shape..)\ndef interp(x0, x1, num_midpoints):\n lerp = torch.linspace(0, 1.0, num_midpoints + 2, device='cuda').to(x0.dtype)\n return ((x0 * (1 - lerp.view(1, -1, 1))) + (x1 * lerp.view(1, -1, 1)))\n\n# interp sheet function\n# Supports full, class-wise and intra-class interpolation\ndef interp_sheet(G, num_per_sheet, num_midpoints, num_classes, parallel,\n samples_root, experiment_name, folder_number, sheet_number=0,\n fix_z=False, fix_y=False, device='cuda'):\n # Prepare zs and ys\n if fix_z: # If fix Z, only sample 1 z per row\n zs = torch.randn(num_per_sheet, 1, G.dim_z, device=device)\n zs = zs.repeat(1, num_midpoints + 2, 1).view(-1, G.dim_z)\n else:\n zs = interp(torch.randn(num_per_sheet, 1, G.dim_z, device=device),\n torch.randn(num_per_sheet, 1, G.dim_z, device=device),\n num_midpoints).view(-1, G.dim_z)\n if fix_y: # If fix y, only sample 1 z per row\n ys = sample_1hot(num_per_sheet, num_classes)\n # print(ys)\n ys = G.shared(ys).view(num_per_sheet, 1, -1)\n # print(ys)\n ys = ys.repeat(1, num_midpoints + 2, 1).view(num_per_sheet * (num_midpoints + 2), -1)\n # print(ys)\n else:\n ys = interp(G.shared(sample_1hot(num_per_sheet, num_classes)).view(num_per_sheet, 1, -1),\n G.shared(sample_1hot(num_per_sheet, num_classes)).view(num_per_sheet, 1, -1),\n num_midpoints).view(num_per_sheet * (num_midpoints + 2), -1)\n # Run the net--note that we've already passed y through G.shared.\n if G.fp16:\n zs = zs.half()\n with torch.no_grad():\n if parallel:\n out_ims = nn.parallel.data_parallel(G, (zs, ys)).data.cpu()\n else:\n out_ims = G(zs, ys).data.cpu()\n interp_style = '' + ('Z' if not fix_z else '') + ('Y' if not fix_y else '')\n image_filename = '%s/%s/%d/interp%s%d.jpg' % (samples_root, experiment_name,\n folder_number, interp_style,\n sheet_number)\n if G.fp16:\n out_ims = out_ims.type(torch.float)\n torchvision.utils.save_image(out_ims, image_filename, nrow=num_midpoints + 2, normalize=True)\n\n\n# Convenience debugging function to print out gradnorms and shape from each layer\n# May need to rewrite this so we can actually see which parameter is which\ndef print_grad_norms(net):\n gradsums = [[float(torch.norm(param.grad).item()),\n float(torch.norm(param).item()), param.shape]\n for param in net.parameters()]\n order = np.argsort([item[0] for item in gradsums])\n print(['%3.3e,%3.3e, %s' % (gradsums[item_index][0],\n gradsums[item_index][1],\n str(gradsums[item_index][2])) \n for item_index in order])\n\n\n# Get singular values to log. This will use the state dict to find them\n# and substitute underscores for dots.\ndef get_SVs(net, prefix):\n d = net.state_dict()\n return {('%s_%s' % (prefix, key)).replace('.', '_') :\n float(d[key].item())\n for key in d if 'sv' in key}\n\n\n# Name an experiment based on its config\ndef name_from_config(config):\n name = '_'.join([\n item for item in [\n 'Big%s' % config['which_train_fn'],\n config['dataset'],\n config['model'] if config['model'] != 'BigGAN' else None,\n 'seed%d' % config['seed'],\n 'Gch%d' % config['G_ch'],\n 'Dch%d' % config['D_ch'],\n 'Gd%d' % config['G_depth'] if config['G_depth'] > 1 else None,\n 'Dd%d' % config['D_depth'] if config['D_depth'] > 1 else None,\n 'bs%d' % config['batch_size'],\n 'Gfp16' if config['G_fp16'] else None,\n 'Dfp16' if config['D_fp16'] else None,\n 'nDs%d' % config['num_D_steps'] if config['num_D_steps'] > 1 else None,\n 'nDa%d' % config['num_D_accumulations'] if config['num_D_accumulations'] > 1 else None,\n 'nGa%d' % config['num_G_accumulations'] if config['num_G_accumulations'] > 1 else None,\n 'Glr%2.1e' % config['G_lr'],\n 'Dlr%2.1e' % config['D_lr'],\n 'GB%3.3f' % config['G_B1'] if config['G_B1'] !=0.0 else None,\n 'GBB%3.3f' % config['G_B2'] if config['G_B2'] !=0.999 else None,\n 'DB%3.3f' % config['D_B1'] if config['D_B1'] !=0.0 else None,\n 'DBB%3.3f' % config['D_B2'] if config['D_B2'] !=0.999 else None,\n 'Gnl%s' % config['G_nl'],\n 'Dnl%s' % config['D_nl'],\n 'Ginit%s' % config['G_init'],\n 'Dinit%s' % config['D_init'],\n 'G%s' % config['G_param'] if config['G_param'] != 'SN' else None,\n 'D%s' % config['D_param'] if config['D_param'] != 'SN' else None,\n 'Gattn%s' % config['G_attn'] if config['G_attn'] != '0' else None,\n 'Dattn%s' % config['D_attn'] if config['D_attn'] != '0' else None,\n 'Gortho%2.1e' % config['G_ortho'] if config['G_ortho'] > 0.0 else None,\n 'Dortho%2.1e' % config['D_ortho'] if config['D_ortho'] > 0.0 else None,\n config['norm_style'] if config['norm_style'] != 'bn' else None,\n 'cr' if config['cross_replica'] else None,\n 'Gshared' if config['G_shared'] else None,\n 'hier' if config['hier'] else None,\n 'ema' if config['ema'] else None,\n config['name_suffix'] if config['name_suffix'] else None,\n ]\n if item is not None])\n # dogball\n if config['hashname']:\n return hashname(name)\n else:\n return name\n\n\n# A simple function to produce a unique experiment name from the animal hashes.\ndef hashname(name):\n h = hash(name)\n a = h % len(animal_hash.a)\n h = h // len(animal_hash.a)\n b = h % len(animal_hash.b)\n h = h // len(animal_hash.c)\n c = h % len(animal_hash.c)\n return animal_hash.a[a] + animal_hash.b[b] + animal_hash.c[c]\n\n\n# Get GPU memory, -i is the index\ndef query_gpu(indices):\n os.system('nvidia-smi -i 0 --query-gpu=memory.free --format=csv')\n\n\n# Convenience function to count the number of parameters in a module\ndef count_parameters(module):\n print('Number of parameters: {}'.format(\n sum([p.data.nelement() for p in module.parameters()])))\n\n \n# Convenience function to sample an index, not actually a 1-hot\ndef sample_1hot(batch_size, num_classes, device='cuda'):\n return torch.randint(low=0, high=num_classes, size=(batch_size,),\n device=device, dtype=torch.int64, requires_grad=False)\n\n\n# A highly simplified convenience class for sampling from distributions\n# One could also use PyTorch's inbuilt distributions package.\n# Note that this class requires initialization to proceed as\n# x = Distribution(torch.randn(size))\n# x.init_distribution(dist_type, **dist_kwargs)\n# x = x.to(device,dtype)\n# This is partially based on https://discuss.pytorch.org/t/subclassing-torch-tensor/23754/2\nclass Distribution(torch.Tensor):\n # Init the params of the distribution\n def init_distribution(self, dist_type, **kwargs): \n self.dist_type = dist_type\n self.dist_kwargs = kwargs\n if self.dist_type == 'normal':\n self.mean, self.var = kwargs['mean'], kwargs['var']\n elif self.dist_type == 'categorical':\n self.num_categories = kwargs['num_categories']\n\n def sample_(self):\n if self.dist_type == 'normal':\n self.normal_(self.mean, self.var)\n elif self.dist_type == 'categorical':\n self.random_(0, self.num_categories) \n # return self.variable\n \n # Silly hack: overwrite the to() method to wrap the new object\n # in a distribution as well\n def to(self, *args, **kwargs):\n new_obj = Distribution(self)\n new_obj.init_distribution(self.dist_type, **self.dist_kwargs)\n new_obj.data = super().to(*args, **kwargs) \n return new_obj\n\n\n# Convenience function to prepare a z and y vector\ndef prepare_z_y(G_batch_size, dim_z, nclasses, device='cuda', \n fp16=False,z_var=1.0):\n z_ = Distribution(torch.randn(G_batch_size, dim_z, requires_grad=False))\n z_.init_distribution('normal', mean=0, var=z_var)\n z_ = z_.to(device,torch.float16 if fp16 else torch.float32) \n \n if fp16:\n z_ = z_.half()\n\n y_ = Distribution(torch.zeros(G_batch_size, requires_grad=False))\n y_.init_distribution('categorical',num_categories=nclasses)\n y_ = y_.to(device, torch.int64)\n return z_, y_\n\n\ndef initiate_standing_stats(net):\n for module in net.modules():\n if hasattr(module, 'accumulate_standing'):\n module.reset_stats()\n module.accumulate_standing = True\n\n\ndef accumulate_standing_stats(net, z, y, nclasses, num_accumulations=16):\n initiate_standing_stats(net)\n net.train()\n for i in range(num_accumulations):\n with torch.no_grad():\n z.normal_()\n y.random_(0, nclasses)\n x = net(z, net.shared(y)) # No need to parallelize here unless using syncbn\n # Set to eval mode\n net.eval() \n\n\n# This version of Adam keeps an fp32 copy of the parameters and\n# does all of the parameter updates in fp32, while still doing the\n# forwards and backwards passes using fp16 (i.e. fp16 copies of the\n# parameters and fp16 activations).\n#\n# Note that this calls .float().cuda() on the params.\nimport math\nfrom torch.optim.optimizer import Optimizer\nclass Adam16(Optimizer):\n def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8,weight_decay=0):\n defaults = dict(lr=lr, betas=betas, eps=eps,\n weight_decay=weight_decay)\n params = list(params)\n super(Adam16, self).__init__(params, defaults)\n \n # Safety modification to make sure we floatify our state\n def load_state_dict(self, state_dict):\n super(Adam16, self).load_state_dict(state_dict)\n for group in self.param_groups:\n for p in group['params']:\n self.state[p]['exp_avg'] = self.state[p]['exp_avg'].float()\n self.state[p]['exp_avg_sq'] = self.state[p]['exp_avg_sq'].float()\n self.state[p]['fp32_p'] = self.state[p]['fp32_p'].float()\n\n def step(self, closure=None):\n \"\"\"Performs a single optimization step.\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n loss = closure()\n\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n \n grad = p.grad.data.float()\n state = self.state[p]\n\n # State initialization\n if len(state) == 0:\n state['step'] = 0\n # Exponential moving average of gradient values\n state['exp_avg'] = grad.new().resize_as_(grad).zero_()\n # Exponential moving average of squared gradient values\n state['exp_avg_sq'] = grad.new().resize_as_(grad).zero_()\n # Fp32 copy of the weights\n state['fp32_p'] = p.data.float()\n\n exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n beta1, beta2 = group['betas']\n\n state['step'] += 1\n\n if group['weight_decay'] != 0:\n grad = grad.add(group['weight_decay'], state['fp32_p'])\n\n # Decay the first and second moment running average coefficient\n exp_avg.mul_(beta1).add_(1 - beta1, grad)\n exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n\n denom = exp_avg_sq.sqrt().add_(group['eps'])\n\n bias_correction1 = 1 - beta1 ** state['step']\n bias_correction2 = 1 - beta2 ** state['step']\n step_size = group['lr'] * math.sqrt(bias_correction2) / bias_correction1\n \n state['fp32_p'].addcdiv_(-step_size, exp_avg, denom)\n p.data = state['fp32_p'].half()\n\n return loss\n"
] |
[
[
"torch.randint",
"torch.zeros",
"torch.randperm",
"torch.cat",
"torch.utils.data.DataLoader",
"torch.no_grad",
"numpy.random.randint",
"torch.norm",
"torch.randn",
"torch.eye",
"torch.arange",
"torch.DoubleTensor",
"torch.linspace",
"torch.stack",
"numpy.argsort",
"numpy.random.seed",
"torch.cuda.manual_seed",
"torch.nn.parallel.data_parallel",
"torch.manual_seed",
"torch.nn.ReLU"
]
] |
gabriel-vanzandycke/experimentator
|
[
"e733e03930fc45ad62dfbf3f85cb9babfd078585"
] |
[
"experimentator/tf1_chunk_processors.py"
] |
[
"import tensorflow as tf\n\nclass ChunkProcessor():\n # graph property should be set in the framework specific experiment\n graph = None\n\nclass DoNothing(ChunkProcessor):\n def __call__(self, chunk):\n pass\n\nclass UnSparsify(ChunkProcessor):\n def __call__(self, chunk):\n for name in chunk:\n if isinstance(chunk[name], tf.SparseTensor):\n chunk[name] = tf.sparse.to_dense(chunk[name])\n\nclass CastFloat(ChunkProcessor):\n def __init__(self, tensor_name):\n self.tensor_name = [tensor_name] if isinstance(tensor_name, str) else tensor_name\n def __call__(self, chunk):\n for tensor_name in self.tensor_name:\n if tensor_name in chunk:\n chunk[tensor_name] = tf.cast(chunk[tensor_name], tf.float32)\n\nclass Normalize(ChunkProcessor):\n def __init__(self, tensor_name):\n self.tensor_name = tensor_name\n def __call__(self, chunk):\n assert chunk[self.tensor_name].dtype == tf.float32\n chunk[self.tensor_name] = chunk[self.tensor_name]/255\n\nclass DeNormalize(ChunkProcessor):\n def __init__(self, tensor_name):\n self.tensor_name = tensor_name\n def __call__(self, chunk):\n chunk[self.tensor_name] = tf.saturate_cast(chunk[self.tensor_name]*255, tf.uint8, name=self.tensor_name)\n\nclass Classify(ChunkProcessor):\n def __init__(self, tensor_name=\"batch_softmax\"):\n self.tensor_name = tensor_name\n def __call__(self, chunk):\n chunk[\"batch_output\"] = tf.cast(tf.argmax(chunk[self.tensor_name], axis=-1, output_type=tf.int32), tf.uint8)\n\nclass Output(ChunkProcessor):\n def __init__(self, tensor_name):\n self.tensor_name = tensor_name\n def __call__(self, chunk):\n chunk[\"batch_output\"] = tf.identity(chunk[self.tensor_name], name=\"batch_output\")\n\nclass Heatmap(ChunkProcessor):\n def __init__(self, tensor_name, class_index):\n self.class_index = class_index\n self.tensor_name = tensor_name\n def __call__(self, chunk):\n chunk[\"batch_heatmap\"] = chunk[self.tensor_name][:,:,:,self.class_index]\n\nclass Sigmoid(ChunkProcessor):\n def __call__(self, chunk):\n chunk[\"batch_sigmoid\"] = tf.nn.sigmoid(chunk[\"batch_logits\"])\n\nclass SigmoidCrossEntropyLoss(ChunkProcessor):\n def __call__(self, chunk):\n chunk[\"loss\"] = tf.losses.sigmoid_cross_entropy(chunk[\"batch_target\"][...,tf.newaxis], chunk[\"batch_logits\"], reduction=tf.losses.Reduction.SUM)\n\nclass SoftmaxCrossEntropyLoss(ChunkProcessor):\n def __call__(self, chunk):\n chunk[\"loss\"] = tf.losses.softmax_cross_entropy(chunk[\"batch_target\"], chunk[\"batch_logits\"], reduction=tf.losses.Reduction.SUM)\n\nclass Softmax(ChunkProcessor):\n def __call__(self, chunk):\n assert chunk[\"batch_logits\"].shape[-1] > 1, \"It doesn't mean anything to take the softmax of a signle output feature map\"\n chunk[\"batch_softmax\"] = tf.nn.softmax(chunk[\"batch_logits\"])\n\nclass OneHot(ChunkProcessor):\n def __init__(self, tensor_name, num_classes):\n self.num_classes = num_classes\n self.tensor_name = tensor_name\n self.on_value = 1.0\n self.off_value = 0.0\n def __call__(self, chunk):\n assert len(chunk[self.tensor_name].shape) == 3, \"Wrong shape for 'batch_target'. Expected (B,H,W). Received {}\".format(chunk[self.tensor_name].shape)\n chunk[self.tensor_name] = tf.one_hot(chunk[self.tensor_name], self.num_classes, on_value=self.on_value, off_value=self.off_value)\n\nclass OneHotTarget(OneHot):\n def __init__(self, *args, **kwargs):\n super().__init__(tensor_name=\"batch_target\", *args, **kwargs)\n\n\nclass SoftmaxCrossEntropyLossMap(ChunkProcessor):\n def __init__(self, label_smoothing=0):\n self.label_smoothing = label_smoothing\n def __call__(self, chunk):\n if \"batch_softmax\" in chunk:\n chunk[\"loss_map\"] = tf.losses.log_loss(labels=chunk[\"batch_target\"], predictions=chunk[\"batch_softmax\"], reduction=tf.losses.Reduction.NONE)\n else:\n chunk[\"loss_map\"] = tf.losses.softmax_cross_entropy(onehot_labels=chunk[\"one_hot\"], logits=chunk[\"batch_logits\"], reduction=tf.losses.Reduction.NONE, label_smoothing=self.label_smoothing)\n\nclass SigmoidCrossEntropyLossMap(ChunkProcessor):\n def __init__(self):\n pass\n #raise Exception(\"should probably not be used. use soft labels softmax-cross-entropy loss instead\")\n def __call__(self, chunk):\n batch_target = chunk[\"batch_target\"] if len(chunk[\"batch_target\"].shape) == 4 else tf.expand_dims(chunk[\"batch_target\"], -1)\n if \"batch_sigmoid\" in chunk:\n chunk[\"loss_map\"] = tf.losses.log_loss(labels=batch_target, predictions=chunk[\"batch_sigmoid\"], reduction=tf.losses.Reduction.NONE)\n else:\n chunk[\"loss_map\"] = tf.losses.sigmoid_cross_entropy(multi_class_labels=batch_target, logits=chunk[\"batch_logits\"], reduction=tf.losses.Reduction.NONE)\n\nclass MeanSquaredErrorLossMap(ChunkProcessor):\n def __call__(self, chunk):\n chunk[\"loss_map\"] = tf.losses.mean_squared_error(chunk[\"batch_target\"], chunk[\"batch_logits\"], reduction=tf.losses.Reduction.NONE)\n\nclass ReduceLossMap(ChunkProcessor):\n def __call__(self, chunk):\n chunk[\"loss\"] = tf.reduce_mean(chunk[\"loss_map\"])\n\nclass KerasHack(ChunkProcessor):\n def __call__(self, chunk):\n chunk[\"batch_logits\"] = tf.subtract(chunk[\"batch_logits\"], tf.expand_dims(tf.reduce_max(chunk[\"batch_logits\"], axis=-1), -1))\n\nclass GlobalMaxPoolingLogits(ChunkProcessor):\n def __call__(self, chunk):\n chunk[\"batch_logits\"] = tf.reduce_max(chunk[\"batch_logits\"], axis=[1,2])\n\nclass GlobalAvgPoolingLogits(ChunkProcessor):\n def __call__(self, chunk):\n chunk[\"batch_logits\"] = tf.reduce_mean(chunk[\"batch_logits\"], axis=[1,2])\n\nclass MeanSquareErrorLoss(ChunkProcessor):\n def __call__(self, chunk):\n chunk[\"loss\"] = tf.losses.mean_squared_error(chunk[\"batch_target\"], chunk[\"batch_logits\"])"
] |
[
[
"tensorflow.losses.mean_squared_error",
"tensorflow.nn.softmax",
"tensorflow.nn.sigmoid",
"tensorflow.reduce_max",
"tensorflow.sparse.to_dense",
"tensorflow.reduce_mean",
"tensorflow.losses.sigmoid_cross_entropy",
"tensorflow.identity",
"tensorflow.expand_dims",
"tensorflow.cast",
"tensorflow.losses.softmax_cross_entropy",
"tensorflow.one_hot",
"tensorflow.saturate_cast",
"tensorflow.argmax",
"tensorflow.losses.log_loss"
]
] |
stevenwchien/csml-iw-rrp
|
[
"ad95afd614997bb39a1b8822dbe997886f18407b"
] |
[
"test_model.py"
] |
[
"from transformers import BertForSequenceClassification, BertTokenizer\nfrom transformers import DistilBertTokenizer, DistilBertForSequenceClassification\nimport torch\nimport numpy as np\nimport pandas as pd\nfrom sklearn import metrics\nfrom torch.utils.data import SequentialSampler, DataLoader\nfrom logger import Logger\n\nfrom train_model import evaluate\nfrom data_util import extract_features\n\nimport argparse\nimport time\nimport sys\nimport json\n\n# helper method to create a confusion matrix using pandas crosstab method\ndef confusion_matrix(preds, labels):\n pred_labels = preds.astype(int) + 1\n actual_labels = labels.astype(int) + 1\n both = np.stack((pred_labels, actual_labels), axis=-1)\n labels_df = pd.DataFrame(data=both, columns=['predicted', 'actual'])\n\n return pd.crosstab(labels_df['predicted'], labels_df['actual'], rownames=['Predicted'], colnames=['Actual'])\n\n# helper method to return the mean average distance\ndef mean_abs_error(preds, labels):\n return np.sum(np.abs(preds-labels)) / len(labels)\n\n# helper method to return the mean square error\ndef mean_square_error(preds, labels):\n return np.sum(np.abs(preds-labels)**2) / len(labels)\n\ndef main():\n parser = argparse.ArgumentParser(description='argument parsing for testing')\n\n parser.add_argument('--data_dir',\n default='data',\n type=str,\n help='path to data directory - default: \\'data\\'')\n\n parser.add_argument('--review_file',\n default='yelp_reviews_test1000.csv',\n type=str,\n help='file name containig reviews')\n\n parser.add_argument('--batch_size',\n default=32,\n type=int,\n help='batch size - default: 32')\n\n parser.add_argument('--model_save',\n default='./model_save',\n type=str,\n help='directory to pull model')\n\n parser.add_argument('--nolog',\n action='store_true',\n help='disable logging')\n\n # parse input arguments\n clargs = parser.parse_args()\n\n # log to file and stdout\n if clargs.nolog:\n print(\"Not logging\")\n else:\n sys.stdout = Logger('test')\n\n print(\"\")\n print(\"==========================================\")\n print(\"-------------Confirm Arguments------------\")\n print(\"==========================================\")\n\n print(\"Data directory for test data: {0:s}\".format(clargs.data_dir))\n print(\"Test reviews file: {0:s}\".format(clargs.review_file))\n print(\"Batch size of {0:d}\".format(clargs.batch_size))\n print(\"Loading model from: {0:s}\".format(clargs.model_save))\n\n print(\"\")\n print(\"==========================================\")\n print(\"---------------Generate Data--------------\")\n print(\"==========================================\")\n\n path = clargs.data_dir\n fn = clargs.review_file\n filename = path + \"/\" + fn\n\n t0 = time.perf_counter()\n print(\"Reading in training data from {0:s}\".format(clargs.review_file))\n reviews_df = pd.read_csv(filename)\n reviews_df = reviews_df[['text', 'stars']]\n TEST_SIZE = len(reviews_df.index)\n elapsed = time.perf_counter() - t0\n print(\"Finished reading {0:d} entries | Took {1:0.2f} seconds\".format(TEST_SIZE, elapsed))\n\n # load the model from save\n print(\"\")\n print(\"==========================================\")\n print(\"----------------Load Model----------------\")\n print(\"==========================================\")\n\n print(\"Loading model and tokenizer from directory\")\n model_path = clargs.model_save\n json_infile = model_path + '/' + 'hyperparams.json'\n with open(json_infile, 'r') as infile:\n hyper_json = json.load(infile)\n\n if 'model' not in hyper_json or hyper_json['model'] == 'bert':\n print(\"Loading normal bert model\")\n tokenizer = BertTokenizer.from_pretrained(model_path)\n model = BertForSequenceClassification.from_pretrained(model_path)\n else:\n print(\"Loading distilbert Model\")\n tokenizer = DistilBertTokenizer.from_pretrained(model_path)\n model = DistilBertForSequenceClassification.from_pretrained(model_path)\n\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n model.to(device)\n model.eval()\n\n print(\"Tokenizing the data to be tested\")\n dataset = extract_features(reviews_df, tokenizer)\n test_dataloader = DataLoader(\n dataset,\n sampler = SequentialSampler(dataset),\n batch_size = clargs.batch_size,\n drop_last = False)\n\n\n\n # test the model against some test data\n print(\"\")\n print(\"==========================================\")\n print(\"----------------Test Model----------------\")\n print(\"==========================================\")\n print(\"Testing - Split {0:d} examples into {1:d} batches\".format(TEST_SIZE, len(test_dataloader)))\n test_loss, test_acc, pred_labels, actual_labels = evaluate(model, device, test_dataloader, TEST_SIZE)\n mae = mean_abs_error(pred_labels, actual_labels)\n mse = mean_square_error(pred_labels, actual_labels)\n conf_matrix = confusion_matrix(pred_labels, actual_labels)\n print(\"\")\n print(\"==========================================\")\n print(\"---------------TEST RESULTS---------------\")\n print(\"==========================================\")\n print(\"\")\n print(\"-----------TRAINING HYPERPARAMS-----------\")\n print(\"Data directory: {0:s}\".format(hyper_json['dataDirectory']))\n print(\"Reviews file: {0:s}\".format(hyper_json['dataFile']))\n print(\"Batch size of {0:s}\".format(hyper_json['batchSize']))\n print(\"Train ratio of {0:s}\".format(hyper_json['trainRatio']))\n print(\"Train for {0:s} epochs\".format(hyper_json['numEpochs']))\n print(\"\")\n print(\"Testing accuracy: \", test_acc)\n print(\"Mean absolute error: \", mae)\n print(\"Mean square error: \", mse)\n print(\"\")\n print(\"-------------CONFUSION MATRIX-------------\")\n print(\"\")\n print(conf_matrix)\n print(\"\")\n target_names = ['1 star', '2 star', '3 star', '4 star', '5 star']\n print(metrics.classification_report(actual_labels, pred_labels, digits=3, target_names=target_names))\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"pandas.crosstab",
"pandas.read_csv",
"numpy.abs",
"torch.utils.data.SequentialSampler",
"numpy.stack",
"pandas.DataFrame",
"torch.cuda.is_available",
"sklearn.metrics.classification_report"
]
] |
EIDOSlab/SeReNe
|
[
"d553078de6d2ae000cabd4f288ce65ea42a8224c"
] |
[
"src/utilities/pruning/thresholding/plateau_scheduler.py"
] |
[
"from copy import deepcopy\nfrom math import inf, isnan\n\nimport torch\n\n\nclass Scheduler(object):\n \"\"\"\n Identifies a plateau in the classificaiton loss, based on `torch.optim.lr_scheduler.ReduceLROnPlateau`.\n \"\"\"\n\n def __init__(self, model, pwe):\n \"\"\"\n :param model: PyTorch model to evaluate, the state_dict of model corresponding to the best loss metric is\n memorized and restored when a plateau is found.\n :param pwe: Plateau Wating Epochs, the scheduler patience, i.e. how many adjacent bad epoch should pass before\n a plateau is identified.\n \"\"\"\n self.model = model\n self.patience = pwe\n self.tolerance = 0.01\n\n self.best = inf\n self.best_dict = None\n self.save_epoch = 0\n\n self.num_bad_epochs = 0\n\n self.tag = \"-- Plateau Scheduler --\"\n\n @torch.no_grad()\n def step(self, metrics, epoch):\n \"\"\"\n Performs a scheduling step:\n - Evaluate if the current metric is better than the best found previously\n - If the current set it as the new best and reset the number of bad epochs\n - Else increase the number of bad epochs by one.\n if the number of bad epochs exceeds the scheduler patients it identities a perfomance plateau.\n :param metrics: Metric value, i.e. the classification loss.\n :param epoch: Iteration in which the metric values is computed.\n :return: True if a performance plateau is found, False otherwise.\n \"\"\"\n current = float(metrics)\n\n if self.best_dict is None:\n self.best_dict = deepcopy(self.model.state_dict())\n\n if isnan(current):\n self.model.load_state_dict(self.best_dict)\n self._reset()\n\n return True\n\n if self._is_better(current):\n self.num_bad_epochs = 0\n if current < self.best:\n self.best = current\n self.best_dict = deepcopy(self.model.state_dict())\n self.save_epoch = epoch\n else:\n self.num_bad_epochs += 1\n print(\"{} plateau length: {}/{}\".format(self.tag, self.num_bad_epochs, self.patience))\n\n if self.num_bad_epochs >= self.patience:\n self.model.load_state_dict(self.best_dict)\n print(\"{} loaded model of epoch {}\".format(self.tag, self.save_epoch))\n self._reset()\n\n return True\n\n return False\n\n def _is_better(self, current):\n \"\"\"\n Check if the give value is less than the current lowest, given a relative tolerance\n :param current: Value compared to the current lowest\n :return: True if current is less then best given the tolerance, False otherwise\n \"\"\"\n return current < (self.best + (self.best * self.tolerance))\n\n def _reset(self):\n \"\"\"\n Reset the state of the scheduler to the initialization.\n \"\"\"\n self.best = inf\n self.num_bad_epochs = 0\n self.best_dict = None\n self.save_epoch = 0\n"
] |
[
[
"torch.no_grad"
]
] |
emay2022/fraplib
|
[
"9c580ea6c9405bcf2dbf50cdbf66e39bfbad0b06"
] |
[
"fraplib/_falsecolor.py"
] |
[
"import numpy as np\nfrom matplotlib import cm\nfrom matplotlib import pyplot as plt\nfrom matplotlib.colors import LinearSegmentedColormap, ListedColormap\n\n\ndef make_colormap(rgb):\n \"\"\"\n creates a new color map from black to white through the specified RGB color\n\n Parameters\n ----------\n rgb : list\n [r = #, g = #, b = #] where # is between 0 and 256\n\n Returns\n -------\n new_cm : mpl.colors.ListedColormap\n \"\"\"\n\n r = rgb[0]\n g = rgb[1]\n b = rgb[2]\n\n N = 256\n vals = np.ones((N, 4))\n vals[:, 0] = np.linspace(0, r / 256, N)\n vals[:, 1] = np.linspace(0, g / 256, N)\n vals[:, 2] = np.linspace(0, b / 256, N)\n ko = ListedColormap(vals)\n\n N = 256\n vals = np.ones((N, 4))\n vals[:, 0] = np.linspace(r / 256, 1, N)\n vals[:, 1] = np.linspace(g / 256, 1, N)\n vals[:, 2] = np.linspace(b / 256, 1, N)\n ow = ListedColormap(vals)\n\n top = cm.get_cmap(ko, 128)\n bottom = cm.get_cmap(ow, 128)\n\n newcolors = np.vstack((top(np.linspace(0, 1, 128)), bottom(np.linspace(0, 1, 128))))\n\n new_cm = ListedColormap(newcolors)\n\n return new_cm\n\n\ndef falsecolor(im, cmap=None, *args, **kwargs):\n \"\"\"\n creates figure and axes objects displaying im with an optionally specified false coloring by cmap\n\n Parameters\n ----------\n im : np.ndarray\n image to be displayed\n cmap : list or matplotlib.colors.ListedColormap or matplotlib.colors. LinearSegmentedColormap\n [r = #, g = #, b = #] where # is between 0 and 256\n *args : list\n passes arguments to plt.imshow()\n **kwargs : dict\n passes keyword arguments to plt.imshow()\n\n Returns\n -------\n fig : matplotlib.figure.Figure\n ax : matplotlib.axes._subplots.AxesSubplot\n \"\"\"\n\n fig, ax = plt.subplots()\n\n if cmap is not None:\n if isinstance(cmap, ListedColormap) or isinstance(\n cmap, LinearSegmentedColormap\n ):\n plt.imshow(im, cmap=cmap, *args, **kwargs)\n else:\n cmap = make_colormap(cmap)\n plt.imshow(im, cmap=cmap, *args, **kwargs)\n else:\n plt.imshow(im, *args, **kwargs)\n\n plt.axis(\"off\")\n\n return fig, ax\n"
] |
[
[
"matplotlib.pyplot.imshow",
"numpy.linspace",
"matplotlib.pyplot.subplots",
"numpy.ones",
"matplotlib.colors.ListedColormap",
"matplotlib.pyplot.axis",
"matplotlib.cm.get_cmap"
]
] |
jvahala/ping-pong-ranker
|
[
"eda814e9dc1fd1798ff45645a9a2387d1c145ba1"
] |
[
"py-modules/utils.py"
] |
[
"import numpy as np \n\ndef softmax(x,rescale_=False): \n\tif rescale_: \n\t\tx_ = rescale(x)\n\telse: \n\t\tx_ = x\n\texpx = np.exp(-1.0*np.array(x_))\t\t#take exponential of the -x(i) values in x \n\ttotal = np.sum(expx)\t#for use in the denominator\n\treturn expx/float(total)\n\ndef rescale(x,max_=10):\n\tx_scaled = [k/400*float(max_) for k in x]\n\treturn x_scaled"
] |
[
[
"numpy.array",
"numpy.sum"
]
] |
zbchern/Neural-Relational-Topic-Models
|
[
"49e57a56039e1c5af10d5774cc220f87bb46269a"
] |
[
"main_cora.py"
] |
[
"import tensorflow as tf\nimport utils\nimport os\nimport logging\nimport models\nimport vae\n\nutils.set_best_gpu()\n\nflags = tf.app.flags\n\n# model training settings\nflags.DEFINE_integer('batch_size', 128, 'training batch size')\nflags.DEFINE_float('init_lr_pretrain', 0.01, 'initial learning rate for pre-train')\nflags.DEFINE_float('init_lr_train', 0.001, 'initial learning rate for training')\nflags.DEFINE_float('lr_decay', 0.1, 'learning rate decay rate')\nflags.DEFINE_float('lambda_w', 1e-4, 'lambda for the regularizer of W')\nflags.DEFINE_string('noise', 'None', \"[None, 'gaussian', 'mask']\")\nflags.DEFINE_integer('hidden_dim', 50, 'dimension of embedding layer')\nflags.DEFINE_integer('top_k', 10, 'top k words')\nflags.DEFINE_string('pretrain_layers_list', '[200, 100]', 'pretrain layers of model') # will also be used in training\nflags.DEFINE_string('cf_layers_list', '[50, 25, 8, 1]', 'layers of model')\nflags.DEFINE_string('activations', \"['sigmoid', 'sigmoid']\", 'activations for different layers')\nflags.DEFINE_string('loss', 'cross-entropy', \"cross-entropy, rmse\")\n\nflags.DEFINE_integer('train_max_epoch', 50, 'max epoch for training')\nflags.DEFINE_integer('pretrain_max_epoch', 50, 'max epoch for pretrain')\nflags.DEFINE_integer('pretrain_print_step', 1, 'print step for pretrain')\nflags.DEFINE_integer('trained_print_step', 1, 'print step for training')\nflags.DEFINE_integer('test_step', 2, 'step for testing')\nflags.DEFINE_integer('print_words_step', 2, 'step for printing words')\n\nflags.DEFINE_integer('negative_num', 5, 'negative samples for each positive citation')\n\n# system settings\nflags.DEFINE_string('data_dir', 'data/cora/', 'directory of data')\nflags.DEFINE_string('dataset', 'cora', 'dataset')\nflags.DEFINE_string('pretrain_dir', 'saver/pretrain_cora/', 'directory for storing pre-training files')\nflags.DEFINE_string('trained_dir', 'saver/trained_cora/', 'directory for storing training files')\nflags.DEFINE_integer('mode', 2, '1 for pretrain, 2 for training')\n\nFLAGS = flags.FLAGS\n\nif not os.path.exists(FLAGS.pretrain_dir):\n os.makedirs(FLAGS.pretrain_dir)\nif not os.path.exists(FLAGS.trained_dir):\n os.makedirs(FLAGS.trained_dir)\n\nif FLAGS.mode == 1:\n utils.init_logging(FLAGS.pretrain_dir + 'pretrain.log')\nelse:\n utils.init_logging(FLAGS.trained_dir + 'trained.log')\n\nlogging.info('Loading data...')\ndata = utils.load_data(FLAGS.data_dir, FLAGS.negative_num)\nlogging.info('Finish loading data')\n\n\ndef main(_):\n\n utils.print_settings(FLAGS)\n\n logging.info('#' * 60)\n logging.info('Current mode is {0}'.format(FLAGS.mode))\n logging.info('#' * 60 + '\\n')\n\n if FLAGS.mode == 1:\n vae_net = vae.VariationalAutoEncoder(FLAGS, data['doc_contents'], data['vocab'])\n vae_net.pretrain()\n elif FLAGS.mode == 2:\n nrtm = models.NRTM(FLAGS, data['doc_contents'], data['train_links_neg'], data['train_labels_neg'],\n data['test_links'], data['test_links_hit'], data['vocab'], data['links'])\n nrtm.load_model(FLAGS.pretrain_dir)\n nrtm.train()\n\n\nif __name__ == '__main__':\n tf.app.run()\n"
] |
[
[
"tensorflow.app.run"
]
] |
Prausome/nmf_python-
|
[
"a931b664a6b076941cdf1de31965f1eaf7e1e632"
] |
[
"nonnegfac/nmf.py"
] |
[
"import numpy as np\nimport scipy.sparse as sps\nimport scipy.optimize as opt\nimport numpy.linalg as nla\nimport nonnegfac.matrix_utils as mu\nimport time\nimport json\nfrom numpy import random\nfrom nonnegfac.nnls import nnlsm_activeset\nfrom nonnegfac.nnls import nnlsm_blockpivot\n\n\nclass NMF_Base(object):\n\n \"\"\" Base class for NMF algorithms\n\n Specific algorithms need to be implemented by deriving from this class.\n \"\"\"\n default_max_iter = 100\n default_max_time = np.inf\n\n def __init__(self):\n raise NotImplementedError(\n 'NMF_Base is a base class that cannot be instantiated')\n\n def set_default(self, default_max_iter, default_max_time):\n self.default_max_iter = default_max_iter\n self.default_max_time = default_max_time\n\n def run(self, A, k, init=None, max_iter=None, max_time=None, verbose=0):\n \"\"\" Run a NMF algorithm\n\n Parameters\n ----------\n A : numpy.array or scipy.sparse matrix, shape (m,n)\n k : int - target lower rank\n\n Optional Parameters\n -------------------\n init : (W_init, H_init) where\n W_init is numpy.array of shape (m,k) and\n H_init is numpy.array of shape (n,k).\n If provided, these values are used as initial values for NMF iterations.\n max_iter : int - maximum number of iterations.\n If not provided, default maximum for each algorithm is used.\n max_time : int - maximum amount of time in seconds.\n If not provided, default maximum for each algorithm is used.\n verbose : int - 0 (default) - No debugging information is collected, but\n input and output information is printed on screen.\n -1 - No debugging information is collected, and\n nothing is printed on screen.\n 1 (debugging/experimental purpose) - History of computation is\n returned. See 'rec' variable.\n 2 (debugging/experimental purpose) - History of computation is\n additionally printed on screen.\n Returns\n -------\n (W, H, rec)\n W : Obtained factor matrix, shape (m,k)\n H : Obtained coefficient matrix, shape (n,k)\n rec : dict - (debugging/experimental purpose) Auxiliary information about the execution\n \"\"\"\n info = {'k': k,\n\n 'alg': str(self.__class__),\n 'A_dim_1': A.shape[0],\n 'A_dim_2': A.shape[1],\n 'A_type': str(A.__class__),\n 'max_iter': max_iter if max_iter is not None else self.default_max_iter,\n 'verbose': verbose,\n 'max_time': max_time if max_time is not None else self.default_max_time}\n if init != None:\n W = init[0].copy()\n H = init[1].copy()\n info['init'] = 'user_provided'\n else:\n W = random.rand(A.shape[0], k)\n H = random.rand(A.shape[1], k)\n info['init'] = 'uniform_random'\n\n if verbose >= 0:\n print ('[NMF] Running: ')\n print (json.dumps(info, indent=4, sort_keys=True))\n\n norm_A = mu.norm_fro(A)\n total_time = 0\n\n if verbose >= 1:\n his = {'iter': [], 'elapsed': [], 'rel_error': []}\n\n start = time.time()\n # algorithm-specific initilization\n (W, H) = self.initializer(W, H)\n\n for i in range(1, info['max_iter'] + 1):\n start_iter = time.time()\n # algorithm-specific iteration solver\n (W, H) = self.iter_solver(A, W, H, k, i)\n elapsed = time.time() - start_iter\n\n if verbose >= 1:\n rel_error = mu.norm_fro_err(A, W, H, norm_A) / norm_A\n his['iter'].append(i)\n his['elapsed'].append(elapsed)\n his['rel_error'].append(rel_error)\n if verbose >= 2:\n print ('iter:' + str(i) + ', elapsed:' + str(elapsed) + ', rel_error:' + str(rel_error))\n\n total_time += elapsed\n if total_time > info['max_time']:\n break\n\n W, H, weights = mu.normalize_column_pair(W, H)\n\n final = {}\n final['norm_A'] = norm_A\n final['rel_error'] = mu.norm_fro_err(A, W, H, norm_A) / norm_A\n final['iterations'] = i\n final['elapsed'] = time.time() - start\n\n rec = {'info': info, 'final': final}\n if verbose >= 1:\n rec['his'] = his\n\n if verbose >= 0:\n print ('[NMF] Completed: ')\n print (json.dumps(final, indent=4, sort_keys=True))\n return (W, H, rec)\n\n def run_repeat(self, A, k, num_trial, max_iter=None, max_time=None, verbose=0):\n \"\"\" Run an NMF algorithm several times with random initial values \n and return the best result in terms of the Frobenius norm of\n the approximation error matrix\n\n Parameters\n ----------\n A : numpy.array or scipy.sparse matrix, shape (m,n)\n k : int - target lower rank\n num_trial : int number of trials\n\n Optional Parameters\n -------------------\n max_iter : int - maximum number of iterations for each trial.\n If not provided, default maximum for each algorithm is used.\n max_time : int - maximum amount of time in seconds for each trial.\n If not provided, default maximum for each algorithm is used.\n verbose : int - 0 (default) - No debugging information is collected, but\n input and output information is printed on screen.\n -1 - No debugging information is collected, and\n nothing is printed on screen.\n 1 (debugging/experimental purpose) - History of computation is\n returned. See 'rec' variable.\n 2 (debugging/experimental purpose) - History of computation is\n additionally printed on screen.\n Returns\n -------\n (W, H, rec)\n W : Obtained factor matrix, shape (m,k)\n H : Obtained coefficient matrix, shape (n,k)\n rec : dict - (debugging/experimental purpose) Auxiliary information about the execution\n \"\"\"\n for t in range(num_trial):\n if verbose >= 0:\n print ('[NMF] Running the {0}/{1}-th trial ...'.format(t + 1, num_trial))\n this = self.run(A, k, verbose=(-1 if verbose is 0 else verbose))\n if t == 0:\n best = this\n else:\n if this[2]['final']['rel_error'] < best[2]['final']['rel_error']:\n best = this\n if verbose >= 0:\n print ('[NMF] Best result is as follows.')\n print (json.dumps(best[2]['final'], indent=4, sort_keys=True))\n return best\n\n def iter_solver(self, A, W, H, k, it):\n raise NotImplementedError\n\n def initializer(self, W, H):\n return (W, H)\n\n\nclass NMF_ANLS_BLOCKPIVOT(NMF_Base):\n\n \"\"\" NMF algorithm: ANLS with block principal pivoting\n\n J. Kim and H. Park, Fast nonnegative matrix factorization: An active-set-like method and comparisons,\n SIAM Journal on Scientific Computing, \n vol. 33, no. 6, pp. 3261-3281, 2011.\n \"\"\"\n\n def __init__(self, default_max_iter=50, default_max_time=np.inf):\n self.set_default(default_max_iter, default_max_time)\n\n def iter_solver(self, A, W, H, k, it):\n Sol, info = nnlsm_blockpivot(W, A, init=H.T)\n H = Sol.T\n Sol, info = nnlsm_blockpivot(H, A.T, init=W.T)\n W = Sol.T\n return (W, H)\n\n\nclass NMF_ANLS_AS_NUMPY(NMF_Base):\n\n \"\"\" NMF algorithm: ANLS with scipy.optimize.nnls solver\n \"\"\"\n\n def __init__(self, default_max_iter=50, default_max_time=np.inf):\n self.set_default(default_max_iter, default_max_time)\n\n def iter_solver(self, A, W, H, k, it):\n if not sps.issparse(A):\n for j in range(0, H.shape[0]):\n res = opt.nnls(W, A[:, j])\n H[j, :] = res[0]\n else:\n for j in range(0, H.shape[0]):\n res = opt.nnls(W, A[:, j].toarray()[:, 0])\n H[j, :] = res[0]\n\n if not sps.issparse(A):\n for j in range(0, W.shape[0]):\n res = opt.nnls(H, A[j, :])\n W[j, :] = res[0]\n else:\n for j in range(0, W.shape[0]):\n res = opt.nnls(H, A[j, :].toarray()[0,:])\n W[j, :] = res[0]\n return (W, H)\n\n\nclass NMF_ANLS_AS_GROUP(NMF_Base):\n\n \"\"\" NMF algorithm: ANLS with active-set method and column grouping\n\n H. Kim and H. Park, Nonnegative matrix factorization based on alternating nonnegativity \n constrained least squares and active set method, SIAM Journal on Matrix Analysis and Applications, \n vol. 30, no. 2, pp. 713-730, 2008.\n \"\"\"\n\n def __init__(self, default_max_iter=50, default_max_time=np.inf):\n self.set_default(default_max_iter, default_max_time)\n\n def iter_solver(self, A, W, H, k, it):\n if it == 1:\n Sol, info = nnlsm_activeset(W, A)\n H = Sol.T\n Sol, info = nnlsm_activeset(H, A.T)\n W = Sol.T\n else:\n Sol, info = nnlsm_activeset(W, A, init=H.T)\n H = Sol.T\n Sol, info = nnlsm_activeset(H, A.T, init=W.T)\n W = Sol.T\n return (W, H)\n\n\nclass NMF_HALS(NMF_Base):\n\n \"\"\" NMF algorithm: Hierarchical alternating least squares\n\n A. Cichocki and A.-H. Phan, Fast local algorithms for large scale nonnegative matrix and tensor factorizations,\n IEICE Transactions on Fundamentals of Electronics, Communications and Computer Sciences,\n vol. E92-A, no. 3, pp. 708-721, 2009.\n \"\"\"\n\n def __init__(self, default_max_iter=100, default_max_time=np.inf):\n self.eps = 1e-16\n self.set_default(default_max_iter, default_max_time)\n\n def initializer(self, W, H):\n W, H, weights = mu.normalize_column_pair(W, H)\n return W, H\n\n def iter_solver(self, A, W, H, k, it):\n AtW = A.T.dot(W)\n WtW = W.T.dot(W)\n for kk in range(0, k):\n temp_vec = H[:, kk] + AtW[:, kk] - H.dot(WtW[:, kk])\n H[:, kk] = np.maximum(temp_vec, self.eps)\n\n AH = A.dot(H)\n HtH = H.T.dot(H)\n for kk in range(0, k):\n temp_vec = W[:, kk] * HtH[kk, kk] + AH[:, kk] - W.dot(HtH[:, kk])\n W[:, kk] = np.maximum(temp_vec, self.eps)\n ss = nla.norm(W[:, kk])\n if ss > 0:\n W[:, kk] = W[:, kk] / ss\n\n return (W, H)\n\n\nclass NMF_MU(NMF_Base):\n\n \"\"\" NMF algorithm: Multiplicative updating \n\n Lee and Seung, Algorithms for non-negative matrix factorization, \n Advances in Neural Information Processing Systems, 2001, pp. 556-562.\n \"\"\"\n\n def __init__(self, default_max_iter=500, default_max_time=np.inf):\n self.eps = 1e-16\n self.set_default(default_max_iter, default_max_time)\n\n def iter_solver(self, A, W, H, k, it):\n AtW = A.T.dot(W)\n HWtW = H.dot(W.T.dot(W)) + self.eps\n H = H * AtW\n H = H / HWtW\n\n AH = A.dot(H)\n WHtH = W.dot(H.T.dot(H)) + self.eps\n W = W * AH\n W = W / WHtH\n\n return (W, H)\n\n###\nclass NMF_RANK2(NMF_Base):\n\n def __init__(self, default_max_iter=500, default_max_time=np.inf):\n self.eps = 1e-16\n self.set_default(default_max_iter, default_max_time)\n\n def iter_solver(self, A, W ,H ,k ,it):\n\n # H: n * k\n\n m = np.shape(A)[0]\n n = np.shape(A)[1]\n tol = 1e-4\n vec_norm = 2.0\n normW = True\n\n left = H.T.dot(H)\n right = A.dot(H)\n\n #for i in range(1,10):\n \n W = self.anls_entry_rank2_precompute(left,right,W);\n\n\n norms_W = np.sqrt(np.sum(np.square(W)))\n W = W/norms_W\n left = W.T.dot(W)\n right = A.T.dot(W)\n\n H = self.anls_entry_rank2_precompute(left, right, H)\n gradH = left.dot(H.T).T - right \n left = H.T.dot(H)\n right = A.dot(H)\n\n gradW = W.dot(left) - right\n\n # if(i == 1):\n # initgrad = np.sqrt(np.square(nla.norm(gradW[gradW<=0|W>0])) + np.square(nla.norm(gradH<=0|H>0)))\n # continue;\n # else :\n # projnorm = np.sqrt(np.square(nla.norm(gradW[gradW<=0|W>0])) + np.square(nla.norm(gradH<=0|H>0)))\n\n # if(projnorm < tol *initgrad):\n # break;\n\n # grad = projnorm / initgrad \n\n # print(grad)\n\n\n # for i in range(1,10):\n # if(nla.matrix_rank(left)<2):\n # # singular\n # W = np.zeros(m,2)\n # H = np.zeros(n,2);\n # U, S, Vh = nla.svd(A);\n # print('singular')\n\n # W = self.anls_entry_rank2_precompute(left,right,W).;\n\n\n if vec_norm !=0:\n if normW :\n norms = np.sum(np.power(W,vec_norm), axis=0)*(1/vec_norm)\n H = H * norms \n W = W / norms \n else :\n norms = np.sum(np.power(H,vec_norm),axis = 0)*(1/vec_norm)\n W = W.dot(norms)\n \n # print(np.shape(A))\n\n # if np.shape(A) !=2:\n # print ('error');\n\n\n return (W,H)\n\n\n def anls_entry_rank2_precompute(self, left, right, H):\n\n #if abs(left(1,1)) < eps & abs(left(1,2)) < eps\n\n #print (np.shape(left))\n #print (left)\n\n n = np.shape(right)[0]\n\n solve_either = np.zeros((n,2)) \n solve_either[:,0] = right[:,0] * (1./left[0,0])\n solve_either[:,1] = right[:,1] * (1./left[1,1])\n cosine_either = np.zeros((n,2))\n cosine_either[:,0] = np.multiply(solve_either[:,0] , np.sqrt(left[0,0]))\n cosine_either[:,1] = np.multiply(solve_either[:,1] , np.sqrt(left[1,1]))\n\n choose_first = (cosine_either[:,0] >= cosine_either[:,1])\n\n\n solve_either[choose_first,1] = 0\n solve_either[~choose_first,0] = 0\n\n if ( abs(left[0,0]) <= abs(left[0,1])):\n\n t = left[1,0]/left[0,0];\n a2 = left[0,0] + t*left[1,0];\n b2 = left[0,1] + t*left[1,1];\n d2 = left[1,1] - t*left[0,1];\n\n e2 = right[:,0] + t * right[:,1]\n f2 = right[:,1] - t * right[:,0]\n\n else:\n\n ct = left[0,0] / left[1,0]\n a2 = left[1,0] + ct * left[0,0]\n b2 = left[1,1] + ct * left[0,1]\n d2 = -left[0,1] + ct * left[1,1]\n\n e2 = right[:,1] + ct * right[:,0]\n f2 = -right[:,0] + ct * right[:,1]\n\n\n H[:,1] = f2 * (1/d2)\n H[:,0] = (e2-b2*H[:,1])*(1/a2) \n\n\n use_either = ~np.all(H>0,1)\n H[use_either,:] = solve_either[use_either,:]\n\n\n return H\n\n\n\n###\nclass Hier8_net():\n\n def __init__(self):\n print('start hier8')\n\n def hier8_net(self,A,k): \n\n # print(np.where(np.sum(A[:,0]))\n\n\n trial_allowance = 3 \n unbalance = 0.1 \n vec_norm = 2.0 \n normW = True \n tol = 1e-4 \n maxiter= 10000 \n\n m = np.shape(A)[0]\n n = np.shape(A)[1]\n\n timings = np.zeros((1,k-1))\n #clusters = np.zeros((1,2*(k-1)))\n clusters = []\n #Ws = np.zeros((1,2*(k-1)))\n Ws = []\n W_buffer = [] \n H_buffer = [] \n priorities = np.zeros((2*(k-1)))\n is_leaf = -1 * np.ones(2*(k-1))\n tree = np.zeros((2,2*(k-1)))\n splits = -1 * np.ones(k-1)\n\n term_subset =np.where(np.sum(A, axis=1)!=0) \n # print(m,n)\n # print(np.shape(term_subset))\n term_subset = np.array(term_subset[0])\n term_subset = term_subset.flatten()\n W = np.random.rand(np.size(term_subset),2)\n H = np.random.rand(n,2)\n\n print('hier8')\n\n if(np.size(term_subset) == m):\n W, H = self.nmfsh_comb_rank2(A, W ,H )\n print('done')\n else : \n W_tmp, H = self.nmfsh_comb_rank2(A[term_subset,:], W, H)\n print('done rank2')\n W = np.zeros((m,2))\n W[term_subset,:] = W_tmp\n\n result_used = 0\n\n\n for i in range(0,k):\n if(i == 0):\n split_node = 0; \n new_nodes = np.array([0,1])\n min_priority = 1e308\n split_subset = []\n else: \n leaves = np.where(is_leaf==1)[0]\n #leaves = np.array(leaves)\n print('leaves')\n print(leaves)\n temp_priority = priorities[leaves]\n print('temp_priority', temp_priority)\n print('priorities', priorities)\n #min_priority = np.minimum(temp_priority[temp_priority>0])\n #print('min_priority' + min_priority)\n split_node = leaves[split_node]\n is_leaf[split_node] = 0 \n print('split_node')\n print(split_node)\n W = W_buffer[split_node]\n H = H_buffer[split_node]\n split_subset = clusters[split_node]\n new_nodes = np.array([result_used, result_used+1])\n tree[0,split_node] = new_nodes[0]\n tree[1,split_node] = new_nodes[1]\n print('new nodes', new_nodes)\n\n result_used = result_used + 2\n max_val, cluster_subset = H.T.max(0), H.T.argmax(0) \n #clusters[new_nodes[0]] = np.where(cluster_subset==0) \n # temp = np.where(cluster_subset == 0 )\n # temp = np.array(temp)\n # temp2 = np.where(cluster_subset == 1)\n # temp2 =np.array(temp2)\n # clusters[new_nodes[0]] = temp\n # clusters.append(temp2)\n clusters.append(np.array(np.where(cluster_subset == 0)))\n clusters.append(np.array(np.where(cluster_subset == 1)))\n #clusters = np.array(clusters)\n Ws.append(W[:,0])\n Ws.append(W[:,1])\n splits[i] = split_node\n is_leaf[new_nodes] = 1 \n\n #print('length of each clusters', np.shape(clusters[new_nodes[0]]), np.shape(clusters[new_nodes[1]]))\n\n subset = clusters[new_nodes[0]]\n subset, W_buffer_one, H_buffer_one, priority_one = self.trial_split(trial_allowance, unbalance, min_priority, A, subset, W[:,0])\n print('done trial_split')\n clusters[new_nodes[0]] = subset\n W_buffer.append(W_buffer_one)\n H_buffer.append(H_buffer_one)\n priorities[new_nodes[0]] = priority_one\n print('priority_one', priority_one)\n\n subset = clusters[new_nodes[1]]\n subset, W_buffer_one, H_buffer_one, priority_one = self.trial_split(trial_allowance, unbalance, min_priority, A, subset, W[:,1])\n clusters[new_nodes[1]] = subset\n W_buffer.append(W_buffer_one)\n H_buffer.append(H_buffer_one)\n priorities[new_nodes[1]] = priority_one\n\n print('qwe')\n # else: \n # min_priority = min(temp_priority[temp_priority>0])\n\n\n def trial_split(self, trial_allowance, unbalance, min_priority, A, subset, W_parent):\n\n trial = 0\n subset = np.array(subset)[0]\n subset_backup = subset \n while(trial < trial_allowance):\n cluster_subset, W_buffer_one, H_buffer_one, priority_one = self.actual_split(A, subset, W_parent)\n if(priority_one < 0 ):\n break;\n unique_cluster_subset = np.unique(cluster_subset)\n temp = np.where(cluster_subset == unique_cluster_subset[0])\n temp = np.array(temp)\n temp = temp.flatten()\n length_cluster1 = len(temp)\n\n temp2 = np.where(cluster_subset == unique_cluster_subset[1])\n temp2 = np.array(temp2)\n temp2 = temp2.flatten()\n length_cluster2 = len(temp2)\n\n if(np.minimum(length_cluster1, length_cluster2) < unbalance * len(cluster_subset)):\n print('dasda')\n min_val = np.minimum(length_cluster1,length_cluster2)\n if (length_cluster1 - length_cluster2 >=0):\n idx_small = 0\n else:\n idx_small = 1\n subset_small = np.where(cluster_subset == unique_cluster_subset[idx_small])[0]\n #print(np.shape(subset))\n #print(subset_small)\n subset_small = subset[subset_small]\n cluster_subset_small, W_buffer_one_small, H_buffer_one_small, priority_one_small = self.actual_split(A, subset_small, W_buffer_one[:,idx_small])\n if (priority_one_small < min_priority):\n trial = trial + 1 \n if(trial < trial_allowance):\n subset = np.setdiff1d(subset, subset_small)\n else: \n break;\n else:\n break; \n\n #subset_small = np.array(subset_small)\n #subset_small = subset_small.faltten()\n #print(subset_small)\n\n if( trial == trial_allowance):\n\n subset = subset_backup\n W_buffer_one = np.zeros((m,2))\n H_buffer_one = np.zeros(len(subset,2))\n priority_one = -2\n\n return subset, W_buffer_one, H_buffer_one, priority_one\n\n def actual_split(self, A, subset, W_parent):\n\n m = np.shape(A)[0]\n n = np.shape(A)[1]\n #print(np.size(subset))\n\n if( np.size(subset) <= 3):\n cluster_subset = np.ones((1,len(subset)))\n W_buffer_one = np.zeros((m,2))\n H_buffer_one = np.zeros((len(subset),2))\n priority_one = -1 \n else:\n subset = subset.flatten()\n #print(np.sum(A[:,subset], axis=1))\n #print(np.shape(np.sum(A[:,subset], axis=1)))\n term_subset = np.where(np.sum(A[:,subset], axis=1) !=0)\n term_subset = np.array(term_subset)[0]\n term_subset = term_subset.flatten()\n print('actual_split')\n #print(np.shape(term_subset))\n # print(A[term_subset][:,subset])\n #print(np.shape(A[term_subset][:,subset]))\n A_subset = A[term_subset][:,subset]; \n W = random.rand(len(term_subset),2)\n H = random.rand(len(subset),2)\n W, H = self.nmfsh_comb_rank2(A_subset, W, H)\n print(np.shape(H))\n max_val, cluster_subset = H.T.max(0), H.T.argmax(0) \n W_buffer_one = np.zeros((m,2))\n W_buffer_one[term_subset,:] = W \n H_buffer_one = H \n if(len(np.unique(cluster_subset))>1):\n priority_one = self.compute_priority(W_parent, W_buffer_one)\n print('priority_one',priority_one)\n else:\n priority_one = -1 \n\n return cluster_subset, W_buffer_one, H_buffer_one, priority_one\n\n def compute_priority(self, W_parent, W_child):\n\n\n print('compute_priority')\n n = len(W_parent)\n print(n)\n sorted_parent, idx_parent = np.sort(W_parent)[::-1], np.argsort(W_parent[::-1]) #descending order\n sorted_child1, idx_child1 = -np.sort(-W_child[:,0]), np.argsort(-W_child[:,0])\n sorted_child2, idx_child2 = -np.sort(-W_child[:,1]), np.argsort(-W_child[:,1])\n\n temp = np.array(np.where(W_parent !=0))\n temp = temp.flatten()\n n_part = len(temp)\n \n if(n_part <= 1):\n priority = -3\n else:\n weight = np.log(np.arange(n,0,-1))\n first_zero = np.where(sorted_parent==0 & 1)[0]\n if(len(first_zero)>0):\n weight[first_zero] = 1 \n weight_part = np.zeros((n,1)).flatten()\n weight_part[0:n_part] = np.log(np.arange(n_part,0,-1))\n sorted1, idx1 = np.sort(idx_child1), np.argsort(idx_child1)\n sorted2, idx2 = np.sort(idx_child2), np.argsort(idx_child2)\n \n max_pos = np.maximum(idx1, idx2) \n discount = np.log(n - max_pos[idx_parent]+1)\n discount[discount ==0] = np.log(2)\n weight = weight / discount\n weight_part = weight_part / discount\n print(weight, weight_part)\n priority = self.NDCG_part(idx_parent, idx_child1, weight, weight_part) * self.NDCG_part(idx_parent, idx_child2, weight, weight_part)\n \n\n\n return priority \n\n\n def NDCG_part(self, ground, test, weight, weight_part):\n\n sorted1, seq_idx = np.sort(ground), np.argsort(ground)\n weight_part = weight_part[seq_idx]\n \n n = len(test)\n uncum_score = weight_part[test]\n uncum_score[1:n-1:1] = np.log2(uncum_score[1:n-1:1])\n cum_score = np.cumsum(uncum_score)\n\n ideal_score = np.sort(weight)[::-1]\n ideal_score[1:n-1:1] = np.log2(ideal_score[1:n-1:1])\n cum_ideal_score = np.cumsum(ideal_score)\n\n score = cum_score / cum_ideal_score \n score = score[-1]\n\n #print(score)\n\n return score\n \n\n\n def nmfsh_comb_rank2(self,A, Winit, Hinit):\n \n m = np.shape(A)[0]\n n = np.shape(A)[1]\n tol = 1e-4\n vec_norm = 2.0\n normW = True\n\n W = Winit \n H = Hinit.T\n\n print('nmfsh_comb_rank2')\n\n\n left = H.dot(H.T)\n right = A.dot(H.T)\n\n #print(np.shape(left), np.shape(right))\n\n for i in range(0,1000):\n if(nla.matrix_rank(left)<2):\n print('The matrix H is singular')\n W = np.zeors((m,2))\n H = np.zeros((2,n))\n U, S, V = nla.svd(A,1)\n if(np.sum(U)<0):\n U = - U \n V = - V \n W[:,0] = U \n H[0,:] = V.T \n\n \n W = self.anls_entry_rank2_precompute(left,right,W);\n\n #print('W shape', np.shape(W))\n norms_W = np.sqrt(np.sum(np.square(W)))\n W = W/norms_W\n left = W.T.dot(W)\n right = A.T.dot(W)\n #print(np.shape(A), np.shape(right))\n\n H = self.anls_entry_rank2_precompute(left, right, H.T).T\n gradH = left.dot(H) - right.T \n left = H.dot(H.T)\n right = A.dot(H.T)\n\n gradW = W.dot(left) - right\n\n\n if vec_norm !=0:\n if normW :\n norms = np.sum(np.power(W,vec_norm), axis=0)*(1/vec_norm)\n #norms = np.matrix(norms)\n H[:,0] = H[:,0] * norms[0]\n H[:,1] = H[:,1] * norms[1]\n W[:,0] = W[:,0] / norms[0]\n W[:,1] = W[:,1] / norms[1]\n else :\n norms = np.sum(np.power(H,vec_norm),axis = 0)*(1/vec_norm)\n #norms = np.matrix(norms)\n H[:,0] = H[:,0] * norms[0]\n H[:,1] = H[:,1] * norms[1]\n W[:,0] = W[:,0] / norms[0]\n W[:,1] = W[:,1] / norms[1]\n\n H = H.T\n \n\n\n return (W,H)\n\n\n\n def anls_entry_rank2_precompute(self, left, right, H):\n\n\n n = np.shape(right)[0]\n\n solve_either = np.zeros((n,2)) \n solve_either[:,0] = right[:,0] * (1./left[0,0])\n solve_either[:,1] = right[:,1] * (1./left[1,1])\n cosine_either = np.zeros((n,2))\n cosine_either[:,0] = np.multiply(solve_either[:,0] , np.sqrt(left[0,0]))\n cosine_either[:,1] = np.multiply(solve_either[:,1] , np.sqrt(left[1,1]))\n\n choose_first = (cosine_either[:,0] >= cosine_either[:,1])\n\n\n solve_either[choose_first,1] = 0\n solve_either[~choose_first,0] = 0\n\n if ( abs(left[0,0]) <= abs(left[0,1])):\n\n t = left[1,0]/left[0,0];\n a2 = left[0,0] + t*left[1,0];\n b2 = left[0,1] + t*left[1,1];\n d2 = left[1,1] - t*left[0,1];\n\n e2 = right[:,0] + t * right[:,1]\n f2 = right[:,1] - t * right[:,0]\n\n else:\n\n ct = left[0,0] / left[1,0]\n a2 = left[1,0] + ct * left[0,0]\n b2 = left[1,1] + ct * left[0,1]\n d2 = -left[0,1] + ct * left[1,1]\n\n e2 = right[:,1] + ct * right[:,0]\n f2 = -right[:,0] + ct * right[:,1]\n\n\n H[:,1] = f2 * (1/d2)\n H[:,0] = (e2-b2*H[:,1])*(1/a2) \n\n\n use_either = ~np.all(H>0,1)\n H[use_either,:] = solve_either[use_either,:]\n\n\n return H\n\n\n\n\n\n\n\nclass NMF(NMF_ANLS_BLOCKPIVOT):\n\n \"\"\" Default NMF algorithm: NMF_ANLS_BLOCKPIVOT\n \"\"\"\n\n def __init__(self, default_max_iter=50, default_max_time=np.inf):\n self.set_default(default_max_iter, default_max_time)\n\n\ndef _mmio_example(m=100, n=100, k=10):\n print ('\\nTesting mmio read and write ...\\n')\n import scipy.io.mmio as mmio\n\n W_org = random.rand(m, k)\n H_org = random.rand(n, k)\n X = W_org.dot(H_org.T)\n X[random.rand(n, k) < 0.5] = 0\n X_sparse = sps.csr_matrix(X)\n\n filename = '_temp_mmio.mtx'\n mmio.mmwrite(filename, X_sparse)\n A = mmio.mmread(filename)\n\n alg = NMF_ANLS_BLOCKPIVOT()\n rslt = alg.run(X_sparse, k, max_iter=50)\n\n\ndef _compare_nmf(m=300, n=300, k=10):\n from pylab import plot, show, legend, xlabel, ylabel\n\n W_org = random.rand(m, k)\n H_org = random.rand(n, k)\n A = W_org.dot(H_org.T)\n\n print ('\\nComparing NMF algorithms ...\\n')\n\n names = [NMF_MU, NMF_HALS, NMF_ANLS_BLOCKPIVOT,\n NMF_ANLS_AS_NUMPY, NMF_ANLS_AS_GROUP]\n iters = [2000, 1000, 100, 100, 100]\n labels = ['mu', 'hals', 'anls_bp', 'anls_as_numpy', 'anls_as_group']\n styles = ['-x', '-o', '-+', '-s', '-D']\n\n results = []\n init_val = (random.rand(m, k), random.rand(n, k))\n\n for i in range(len(names)):\n alg = names[i]()\n results.append(\n alg.run(A, k, init=init_val, max_iter=iters[i], verbose=1))\n\n for i in range(len(names)):\n his = results[i][2]['his']\n plot(np.cumsum(his['elapsed']), his['rel_error'],\n styles[i], label=labels[i])\n\n xlabel('time (sec)')\n ylabel('relative error')\n legend()\n show()\n\n\ndef _test_nmf(m=300, n=300, k=10):\n W_org = random.rand(m, k)\n H_org = random.rand(n, k)\n A = W_org.dot(H_org.T)\n\n alg_names = [NMF_ANLS_BLOCKPIVOT, NMF_ANLS_AS_GROUP,\n NMF_ANLS_AS_NUMPY, NMF_HALS, NMF_MU]\n iters = [50, 50, 50, 500, 1000]\n\n print ('\\nTesting with a dense matrix...\\n')\n for alg_name, i in zip(alg_names, iters):\n alg = alg_name()\n rslt = alg.run(A, k, max_iter=i)\n\n print ('\\nTesting with a sparse matrix...\\n')\n A_sparse = sps.csr_matrix(A)\n for alg_name, i in zip(alg_names, iters):\n alg = alg_name()\n rslt = alg.run(A_sparse, k, max_iter=i)\n\n\nif __name__ == '__main__':\n _test_nmf()\n _mmio_example()\n\n # To see an example of comparisons of NMF algorithms, execute\n # _compare_nmf() with X-window enabled.\n # _compare_nmf()\n"
] |
[
[
"scipy.io.mmio.mmwrite",
"numpy.minimum",
"numpy.sqrt",
"numpy.linalg.matrix_rank",
"numpy.cumsum",
"numpy.all",
"numpy.where",
"numpy.square",
"numpy.linalg.svd",
"scipy.sparse.issparse",
"numpy.unique",
"numpy.arange",
"numpy.size",
"numpy.zeros",
"scipy.io.mmio.mmread",
"numpy.log",
"numpy.power",
"scipy.sparse.csr_matrix",
"numpy.random.rand",
"numpy.argsort",
"numpy.array",
"numpy.sum",
"numpy.log2",
"numpy.maximum",
"scipy.optimize.nnls",
"numpy.zeors",
"numpy.linalg.norm",
"numpy.sort",
"numpy.ones",
"numpy.setdiff1d",
"numpy.shape"
]
] |
jeyong/AirSim
|
[
"1fd6a3fc311c704bbbb0b2b6b245e8fa0ba26c8b"
] |
[
"PythonClient/computer_vision/create_ir_segmentation_map.py"
] |
[
"import numpy\nimport cv2\nimport time\nimport sys\nimport os\nimport random\nfrom airsim import *\n\ndef radiance(absoluteTemperature, emissivity, dx=0.01, response=None):\n \"\"\"\n title::\n radiance\n\n description::\n Calculates radiance and integrated radiance over a bandpass of 8 to 14\n microns, given temperature and emissivity, using Planck's Law.\n\n inputs::\n absoluteTemperature\n temperture of object in [K]\n\n either a single temperature or a numpy\n array of temperatures, of shape (temperatures.shape[0], 1)\n emissivity\n average emissivity (number between 0 and 1 representing the\n efficiency with which it emits radiation; if 1, it is an ideal \n blackbody) of object over the bandpass\n\n either a single emissivity or a numpy array of emissivities, of \n shape (emissivities.shape[0], 1)\n dx\n discrete spacing between the wavelengths for evaluation of\n radiance and integration [default is 0.1]\n response\n optional response of the camera over the bandpass of 8 to 14 \n microns [default is None, for no response provided]\n \n returns::\n radiance\n discrete spectrum of radiance over bandpass\n integratedRadiance\n integration of radiance spectrum over bandpass (to simulate\n the readout from a sensor)\n\n author::\n Elizabeth Bondi\n \"\"\"\n wavelength = numpy.arange(8,14,dx)\n c1 = 1.19104e8 # (2 * 6.62607*10^-34 [Js] * \n # (2.99792458 * 10^14 [micron/s])^2 * 10^12 to convert \n # denominator from microns^3 to microns * m^2)\n c2 = 1.43879e4 # (hc/k) [micron * K]\n if response is not None:\n radiance = response * emissivity * (c1 / ((wavelength**5) * \\\n (numpy.exp(c2 / (wavelength * absoluteTemperature )) - 1)))\n else:\n radiance = emissivity * (c1 / ((wavelength**5) * (numpy.exp(c2 / \\\n (wavelength * absoluteTemperature )) - 1)))\n if absoluteTemperature.ndim > 1:\n return radiance, numpy.trapz(radiance, dx=dx, axis=1)\n else:\n return radiance, numpy.trapz(radiance, dx=dx)\n\n\ndef get_new_temp_emiss_from_radiance(tempEmissivity, response):\n \"\"\"\n title::\n get_new_temp_emiss_from_radiance\n\n description::\n Transform tempEmissivity from [objectName, temperature, emissivity]\n to [objectName, \"radiance\"] using radiance calculation above.\n\n input::\n tempEmissivity\n numpy array containing the temperature and emissivity of each\n object (e.g., each row has: [objectName, temperature, emissivity])\n response\n camera response (same input as radiance, set to None if lacking\n this information)\n\n returns::\n tempEmissivityNew\n tempEmissivity, now with [objectName, \"radiance\"]; note that \n integrated radiance (L) is divided by the maximum and multiplied \n by 255 in order to simulate an 8 bit digital count observed by the \n thermal sensor, since radiance and digital count are linearly \n related, so it's [objectName, simulated thermal digital count]\n\n author::\n Elizabeth Bondi\n \"\"\"\n numObjects = tempEmissivity.shape[0]\n\n L = radiance(tempEmissivity[:,1].reshape((-1,1)).astype(numpy.float64), \n tempEmissivity[:,2].reshape((-1,1)).astype(numpy.float64), \n response=response)[1].flatten() \n L = ((L / L.max()) * 255).astype(numpy.uint8)\n\n tempEmissivityNew = numpy.hstack((\n tempEmissivity[:,0].reshape((numObjects,1)), \n L.reshape((numObjects,1))))\n\n return tempEmissivityNew\n\ndef set_segmentation_ids(segIdDict, tempEmissivityNew, client):\n \"\"\"\n title::\n set_segmentation_ids\n\n description::\n Set stencil IDs in environment so that stencil IDs correspond to\n simulated thermal digital counts (e.g., if elephant has a simulated\n digital count of 219, set stencil ID to 219).\n\n input::\n segIdDict\n dictionary mapping environment object names to the object names in\n the first column of tempEmissivityNew \n tempEmissivityNew\n numpy array containing object names and corresponding simulated\n thermal digital count\n client\n connection to AirSim (e.g., client = MultirotorClient() for UAV)\n\n author::\n Elizabeth Bondi\n \"\"\"\n\n #First set everything to 0.\n success = client.simSetSegmentationObjectID(\"[\\w]*\", 0, True);\n if success != True:\n msg = 'There was a problem setting all segmentation object IDs to 0. '\n msg += 'Please try again.'\n print(msg)\n sys.exit(1)\n\n #Next set all objects of interest provided to corresponding object IDs\n #segIdDict values MUST match tempEmissivityNew labels.\n for key in segIdDict:\n objectID = int(tempEmissivityNew[numpy.where(tempEmissivityNew == \\\n segIdDict[key])[0],1][0])\n\n success = client.simSetSegmentationObjectID(\"[\\w]*\"+key+\"[\\w]*\", \n objectID, True);\n if success != True:\n msg = 'There was a problem setting \"' + key\n msg += '\" segmentation object ID to ' + str(objectID) + '. '\n msg += 'Please try again.'\n print(msg)\n sys.exit(1)\n\n time.sleep(0.1)\n\n\nif __name__ == '__main__':\n\n #Connect to AirSim, UAV mode.\n client = MultirotorClient()\n client.confirmConnection()\n\n segIdDict = {'Base_Terrain':'soil',\n 'elephant':'elephant',\n 'zebra':'zebra',\n 'Crocodile':'crocodile',\n 'Rhinoceros':'rhinoceros',\n 'Hippo':'hippopotamus',\n 'Poacher':'human',\n 'InstancedFoliageActor':'tree',\n 'Water_Plane':'water',\n 'truck':'truck'}\n \n #Choose temperature values for winter or summer.\n #\"\"\"\n #winter\n tempEmissivity = numpy.array([['nothing',0,0],\n ['elephant',290,0.96], \n ['zebra',298,0.98],\n ['rhinoceros',291,0.96],\n ['hippopotamus',290,0.96],\n ['crocodile',295,0.96],\n ['human',292,0.985], \n ['tree',273,0.952], \n ['grass',273,0.958], \n ['soil',278,0.914], \n ['shrub',273,0.986],\n ['truck',273,0.8],\n ['water',273,0.96]])\n #\"\"\"\n \"\"\"\n #summer\n tempEmissivity = numpy.array([['nothing',0,0],\n ['elephant',298,0.96], \n ['zebra',307,0.98],\n ['rhinoceros',299,0.96],\n ['hippopotamus',298,0.96],\n ['crocodile',303,0.96],\n ['human',301,0.985], \n ['tree',293,0.952], \n ['grass',293,0.958], \n ['soil',288,0.914], \n ['shrub',293,0.986],\n ['truck',293,0.8],\n ['water',293,0.96]])\n \"\"\"\n\n #Read camera response.\n response = numpy.load('camera_response.npy')\n\n #Calculate radiance.\n tempEmissivityNew = get_new_temp_emiss_from_radiance(tempEmissivity, \n response)\n\n #Set IDs in AirSim environment.\n set_segmentation_ids(segIdDict, tempEmissivityNew, client)"
] |
[
[
"numpy.arange",
"numpy.load",
"numpy.array",
"numpy.exp",
"numpy.where",
"numpy.trapz"
]
] |
jmenges/yolov1_maxim
|
[
"299d0d52edf3aec961b3b9c72cdd590352d26beb"
] |
[
"loss_plot.py"
] |
[
"import re\n\ndef extract_value(fname, regex_str, strloc, endloc):\n f = open(fname, 'r')\n str_buf = f.read()\n\n regex = re.compile(regex_str)\n\n str_list = regex.findall(str_buf)\n print(str_list)\n data_list = []\n for item in str_list:\n # data_list.append(float(item[7:]))\n x = item[strloc:endloc]\n # print(x)\n data_list.append(float(x))\n\n print(data_list)\n # print(len(data_list))\n return data_list\n\n# extract_value('log.txt')\n\n\nimport matplotlib.pyplot as plt\nimport torch\nimport seaborn as sns\nimport numpy as np\n\nepoch = extract_value('log/QAT-20210715-030212/log.txt', 'epoch : .+; l', 8, -3)\nloss_value = extract_value('log/QAT-20210715-030212/log.txt', 'loss : {.+} ; a', 8, -5)\n\nplt.plot(epoch, loss_value)\nplt.show()\n\n\n"
] |
[
[
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show"
]
] |
AlexMGitHub/TheWholeEnchilada
|
[
"9b488777ab2e82d616b952457b45acf6b7eb7c69",
"9b488777ab2e82d616b952457b45acf6b7eb7c69"
] |
[
"src/bokeh_server/results/plots/regression_results.py",
"src/bokeh_server/train/twe_learn/train_model.py"
] |
[
"\"\"\"Display classification results of trained model.\n\nResults:\n - actual_vs_pred: Scatter plot of predicted values vs. actual values\n\n - resid_hist: Histogram of regression residuals\n\n - resid_vs_pred_plot: Return plot containing residuals versus predictions\n\"\"\"\n\n# %% Imports\n# Standard system imports\nfrom pathlib import Path\nimport pickle\n\n# Related third party imports\nfrom bokeh.io import show\nfrom bokeh.layouts import column, row\nfrom bokeh.models.sources import ColumnDataSource\nfrom bokeh.palettes import Category10\nfrom bokeh.plotting import figure\nfrom bokeh.models import DataTable, Div, Select, TableColumn\nimport joblib\nimport numpy as np\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n\n\n# Local application/library specific imports\n\n\n# %% Define globals\nMAX_PLOT_SIZE = 400\nCOLOR = Category10[3][0]\n\n\n# %% Define plots\ndef actual_vs_pred(y_true, y_pred, target):\n \"\"\"Return scatterplot of actual vs. predicted values.\"\"\"\n # -------------------------------------------------------------------------\n # Setup\n # -------------------------------------------------------------------------\n # Define constants\n MARKER = 'circle'\n DEFAULT_MARKER_SIZE = 9\n # Define source\n source = ColumnDataSource({'y_pred': y_pred, 'y_true': y_true})\n\n # -------------------------------------------------------------------------\n # Plots\n # -------------------------------------------------------------------------\n scatter_plot = figure(max_width=MAX_PLOT_SIZE, output_backend=\"webgl\",\n background_fill_color=\"#DDDDDD\",\n outline_line_color=\"white\", toolbar_location='right',\n width=MAX_PLOT_SIZE, sizing_mode=\"scale_width\",\n height=MAX_PLOT_SIZE)\n scatter_plot.scatter(x='y_pred', y='y_true', color=COLOR, source=source,\n fill_alpha=0.4, marker=MARKER,\n size=DEFAULT_MARKER_SIZE, legend_label=target)\n # Style scatter plot\n scatter_plot.grid.grid_line_dash = [6, 4]\n scatter_plot.grid.grid_line_color = \"white\"\n scatter_plot.axis.major_label_text_font_size = \"1em\"\n scatter_plot.axis.major_label_text_font_style = \"bold\"\n scatter_plot.axis.axis_label_text_font_size = \"1em\"\n scatter_plot.axis.axis_label_text_font_style = \"bold\"\n # Add title and axis labels\n scatter_plot.title = f'{target}: True vs. Predicted Values'\n scatter_plot.xaxis.axis_label = 'Predicted'\n scatter_plot.yaxis.axis_label = 'True'\n # Style legend\n scatter_plot.legend.background_fill_color = \"#DDDDDD\"\n scatter_plot.legend.border_line_color = \"white\"\n scatter_plot.legend.label_text_font_style = \"bold\"\n scatter_plot.legend.label_text_font_size = \"1em\"\n scatter_plot.legend.glyph_width = 30\n scatter_plot.legend.glyph_height = 30\n scatter_plot.legend.spacing = 0\n scatter_plot.legend.border_line_width = 2\n scatter_plot.legend.border_line_color = \"black\"\n scatter_plot.legend.padding = 5\n scatter_plot.legend.margin = 30\n scatter_plot.legend.label_standoff = 0\n scatter_plot.legend.location = \"top_left\"\n return scatter_plot\n\n\ndef resid_hist(y_true, y_pred, target):\n \"\"\"Create a histogram plot of error residuals.\"\"\"\n # -------------------------------------------------------------------------\n # Setup\n # -------------------------------------------------------------------------\n residuals = y_true - y_pred\n\n hist_plot = figure(max_width=MAX_PLOT_SIZE, output_backend=\"webgl\",\n toolbar_location=None,\n background_fill_color=\"#DDDDDD\",\n outline_line_color=\"white\",\n width=MAX_PLOT_SIZE, sizing_mode=\"scale_width\",\n height=MAX_PLOT_SIZE)\n hist, edges = np.histogram(residuals, density=True, bins='auto')\n hist_plot.quad(top=hist, bottom=0, left=edges[:-1],\n right=edges[1:], fill_color=COLOR,\n line_color=\"white\", alpha=0.5, legend_label=target)\n hist_plot.y_range.start = 0\n # Style histogram\n hist_plot.grid.grid_line_dash = [6, 4]\n hist_plot.grid.grid_line_color = \"white\"\n hist_plot.axis.major_label_text_font_size = \"1em\"\n hist_plot.axis.major_label_text_font_style = \"bold\"\n hist_plot.axis.axis_label_text_font_size = \"1em\"\n hist_plot.axis.axis_label_text_font_style = \"bold\"\n # Add title and axis labels\n hist_plot.title = f\"{target}: Residuals Histogram\"\n hist_plot.xaxis.axis_label = 'Residuals'\n hist_plot.yaxis.axis_label = 'Density'\n # Disable and hide toolbar\n hist_plot.toolbar.active_drag = None\n hist_plot.toolbar.active_scroll = None\n hist_plot.toolbar.active_tap = None\n # Style legend\n hist_plot.legend.background_fill_color = \"#DDDDDD\"\n hist_plot.legend.border_line_color = \"white\"\n hist_plot.legend.label_text_font_style = \"bold\"\n hist_plot.legend.label_text_font_size = \"1em\"\n hist_plot.legend.glyph_width = 30\n hist_plot.legend.glyph_height = 30\n hist_plot.legend.spacing = 0\n hist_plot.legend.border_line_width = 2\n hist_plot.legend.border_line_color = \"black\"\n hist_plot.legend.padding = 5\n hist_plot.legend.margin = 30\n hist_plot.legend.label_standoff = 0\n hist_plot.legend.location = \"top_left\"\n return hist_plot\n\n\ndef resid_vs_pred_plot(y_true, y_pred, target):\n \"\"\"Return plot containing residuals versus predictions.\"\"\"\n # -------------------------------------------------------------------------\n # Setup\n # -------------------------------------------------------------------------\n # Define constants\n MARKER = 'circle'\n DEFAULT_MARKER_SIZE = 9\n # Define source\n residuals = y_true - y_pred\n source = ColumnDataSource({'y_pred': y_pred, 'residuals': residuals})\n\n # -------------------------------------------------------------------------\n # Plots\n # -------------------------------------------------------------------------\n scatter_plot = figure(max_width=MAX_PLOT_SIZE, output_backend=\"webgl\",\n background_fill_color=\"#DDDDDD\",\n outline_line_color=\"white\",\n toolbar_location='right',\n width=MAX_PLOT_SIZE, sizing_mode=\"scale_width\",\n height=MAX_PLOT_SIZE)\n scatter_plot.scatter(x='y_pred', y='residuals', color=COLOR, source=source,\n fill_alpha=0.4, marker=MARKER,\n size=DEFAULT_MARKER_SIZE, legend_label=target)\n # Style scatter plot\n scatter_plot.grid.grid_line_dash = [6, 4]\n scatter_plot.grid.grid_line_color = \"white\"\n scatter_plot.axis.major_label_text_font_size = \"1em\"\n scatter_plot.axis.major_label_text_font_style = \"bold\"\n scatter_plot.axis.axis_label_text_font_size = \"1em\"\n scatter_plot.axis.axis_label_text_font_style = \"bold\"\n # Add title and axis labels\n scatter_plot.title = f\"{target}: Residuals vs. Predictions\"\n scatter_plot.xaxis.axis_label = 'Predicted'\n scatter_plot.yaxis.axis_label = 'Residuals'\n # Style legend\n scatter_plot.legend.background_fill_color = \"#DDDDDD\"\n scatter_plot.legend.border_line_color = \"white\"\n scatter_plot.legend.label_text_font_style = \"bold\"\n scatter_plot.legend.label_text_font_size = \"1em\"\n scatter_plot.legend.glyph_width = 30\n scatter_plot.legend.glyph_height = 30\n scatter_plot.legend.spacing = 0\n scatter_plot.legend.border_line_width = 2\n scatter_plot.legend.border_line_color = \"black\"\n scatter_plot.legend.padding = 5\n scatter_plot.legend.margin = 30\n scatter_plot.legend.label_standoff = 0\n scatter_plot.legend.location = \"top_left\"\n return scatter_plot\n\n\ndef regression_results():\n \"\"\"Return table and plots of regression results using different metrics.\"\"\"\n # -------------------------------------------------------------------------\n # Setup\n # -------------------------------------------------------------------------\n # Load EDA data and metadata\n data_path = Path('src/bokeh_server/data/eda_data')\n with open(data_path, 'rb') as data_file:\n pickled_data = pickle.load(data_file)\n metadata = pickled_data['metadata']\n dataset = metadata['dataset']\n target = metadata['target']\n # Load model and training data\n model_filename = Path('src/bokeh_server/data/model')\n data_filename = Path('src/bokeh_server/data/train_data')\n model = joblib.load(model_filename)\n data = joblib.load(data_filename)\n training_settings = data['training_settings']\n X_train = data['X_train']\n X_test = data['X_test']\n y_train = data['y_train']\n y_test = data['y_test']\n y_pred_train = model.predict(X_train)\n y_pred_test = model.predict(X_test)\n # Calculate error\n mse_train = mean_squared_error(y_train, y_pred_train)\n mse_test = mean_squared_error(y_test, y_pred_test)\n rmse_train = mean_squared_error(y_train, y_pred_train, squared=False)\n rmse_test = mean_squared_error(y_test, y_pred_test, squared=False)\n mae_train = mean_absolute_error(y_train, y_pred_train)\n mae_test = mean_absolute_error(y_test, y_pred_test)\n r2_train = r2_score(y_train, y_pred_train)\n r2_test = r2_score(y_test, y_pred_test)\n # Create source\n results_dict = {\n 'Metrics': ['MSE', 'RMSE', 'MAE', 'R\\u00b2'],\n 'Training Data': [round(mse_train, 2), round(rmse_train, 2),\n round(mae_train, 2), round(r2_train, 2)],\n 'Test Data': [round(mse_test, 2), round(rmse_test, 2),\n round(mae_test, 2), round(r2_test, 2)]\n }\n source = ColumnDataSource(results_dict)\n # Layout parameters\n col_width = 300 # Results table width\n settings_width = 500 # Training settings div width\n\n # -------------------------------------------------------------------------\n # Data Table\n # -------------------------------------------------------------------------\n # Title for results table\n results_div = Div(\n text=\"\"\"\n <style>\n .bokeh_header {font-size: 20px; margin: auto;}\n .bokeh_title {border-bottom: 3px solid black;}\n </style>\n \"\"\"\n f\"\"\"\n <div style=\"display: table; height: 50px; overflow: hidden;\">\n <div style=\"display: table-cell; vertical-align: middle;\n width: {col_width}px; text-align: center;\" class=\"bokeh_title\">\n <h1 class=\"bokeh_header\">{dataset} Results</h1>\n </div>\n </div>\"\"\",\n height=50, width=225)\n # Data table containing results\n columns = [TableColumn(field=col, title=col) for col in results_dict]\n results_table = DataTable(\n source=source, columns=columns, sortable=False,\n sizing_mode=\"stretch_width\", autosize_mode=\"fit_viewport\",\n width=col_width, index_position=None, height=150)\n\n # -------------------------------------------------------------------------\n # Plots\n # -------------------------------------------------------------------------\n avp = actual_vs_pred(y_test, y_pred_test, target)\n hist_plot = resid_hist(y_test, y_pred_test, target)\n rvp = resid_vs_pred_plot(y_test, y_pred_test, target)\n\n # -------------------------------------------------------------------------\n # Widgets\n # -------------------------------------------------------------------------\n select_data = Select(title=\"Train/Test Data:\", value='Test',\n options=['Test', 'Training'], width=100)\n\n # -------------------------------------------------------------------------\n # Callbacks\n # -------------------------------------------------------------------------\n def select_data_change(attrname, old, new):\n \"\"\"Toggle test/train data for select_data dropdown menu.\"\"\"\n if new == 'Training':\n avp = actual_vs_pred(y_train, y_pred_train, target)\n hist_plot = resid_hist(y_train, y_pred_train, target)\n rvp = resid_vs_pred_plot(y_train, y_pred_train, target)\n elif new == 'Test':\n avp = actual_vs_pred(y_test, y_pred_test, target)\n hist_plot = resid_hist(y_test, y_pred_test, target)\n rvp = resid_vs_pred_plot(y_test, y_pred_test, target)\n update(avp, hist_plot, rvp)\n\n def update(avp, hist_plot, rvp):\n \"\"\"Update layout with new plots.\"\"\"\n results_layout.children[0].children[1] = avp\n results_layout.children[1].children[0] = hist_plot\n results_layout.children[1].children[1] = rvp\n\n select_data.on_change('value', select_data_change)\n\n # -------------------------------------------------------------------------\n # Div Containing Settings\n # -------------------------------------------------------------------------\n # Create settings div title\n settings_div = Div(text=\"\"\"\n <style>\n .bokeh_header2 {font-size: 30px; margin: auto;}\n .bokeh_title2 {border-bottom: 3px solid black;}\n </style>\n \"\"\"f\"\"\"\n <div style=\"display: table; height: 50px; overflow: hidden;\">\n <div style=\"display: table-cell; vertical-align: middle;\n width: {settings_width}px; text-align: center;\" class=\"bokeh_title2\">\n <h1 class=\"bokeh_header2\">{dataset} Training Settings</h1>\n </div>\n </div>\n <div>\n \"\"\", height=50)\n # Add model params to div\n for key, value in training_settings.items():\n settings_div.text += f\"<b>{key}:</b> {value}<br>\"\n settings_div.text += f\"\"\"\n <br><b>Chosen Params:</b> {model.best_estimator_}</div>\"\"\"\n\n # -------------------------------------------------------------------------\n # Layout\n # -------------------------------------------------------------------------\n results_layout = row(\n column(column(\n column(results_div, results_table),\n row(select_data, margin=(50, 0, 0, 300)), height=MAX_PLOT_SIZE),\n avp, margin=(0, 30, 0, 0)),\n column(hist_plot, rvp),\n column(settings_div, width=settings_width, margin=(0, 0, 0, 30))\n )\n\n return results_layout\n\n\nif __name__ == '__main__':\n plot = regression_results()\n show(plot)\n",
"\"\"\"Train model on data according to provided hyperparameters.\n\nPerforms grid search and saves grid search estimator and settings to volume.\n\"\"\"\n\n# %% Imports\n# Standard system imports\nfrom pathlib import Path\n\n# Related third party imports\nimport joblib\nimport numpy as np\n# Import models\nfrom sklearn.ensemble import GradientBoostingClassifier, \\\n GradientBoostingRegressor, RandomForestClassifier, RandomForestRegressor\nfrom sklearn.linear_model import LogisticRegression, LinearRegression, Lasso, \\\n Ridge\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor\nfrom sklearn.svm import LinearSVC, SVC, SVR, LinearSVR\n# Preprocessing, model selection, pipeline, metrics\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.metrics import accuracy_score\n\n# Local application/library specific imports\n\n\n# %% Train model\ndef train_model(X, y, training_settings):\n \"\"\"Train model and save estimator to volume.\"\"\"\n # Model selection\n if training_settings['model'] == 'Gradient Boosting CLF':\n model = GradientBoostingClassifier\n elif training_settings['model'] == 'Gradient Boosting REG':\n model = GradientBoostingRegressor\n elif training_settings['model'] == 'K-Nearest Neighbors CLF':\n model = KNeighborsClassifier\n elif training_settings['model'] == 'K-Nearest Neighbors REG':\n model = KNeighborsRegressor\n elif training_settings['model'] == 'Logistic Regression':\n model = LogisticRegression\n elif training_settings['model'] == 'Linear Regression':\n model = LinearRegression\n elif training_settings['model'] == 'Lasso Regression':\n model = Lasso\n elif training_settings['model'] == 'Ridge Regression':\n model = Ridge\n elif training_settings['model'] == 'Naive Bayes':\n model = GaussianNB\n elif training_settings['model'] == 'Random Forest CLF':\n model = RandomForestClassifier\n elif training_settings['model'] == 'Random Forest REG':\n model = RandomForestRegressor\n elif training_settings['model'] == 'SVC (linear kernel)':\n model = LinearSVC\n elif training_settings['model'] == 'SVC (rbf kernel)':\n model = SVC\n elif training_settings['model'] == 'SVR (linear kernel)':\n model = LinearSVR\n elif training_settings['model'] == 'SVR (rbf kernel)':\n model = SVR\n # Define hyperparameters used for GridSearch\n param_grid = {f'model__{x[0]}': x[1] for x in training_settings['params']}\n # Define pipeline\n estimators = [('scale', StandardScaler()),\n ('model', model())\n ]\n pipe = Pipeline(estimators)\n # Split data into train and test sets\n train_size = training_settings['train_split']\n X_train, X_test, y_train, y_test = train_test_split(X, y,\n train_size=train_size,\n random_state=214)\n # Perform grid search\n grid_search = GridSearchCV(pipe, param_grid=param_grid, n_jobs=-1)\n grid_search.fit(X_train, y_train)\n # Save model and data to volume using joblib\n model_filename = Path('src/bokeh_server/data/model')\n data_filename = Path('src/bokeh_server/data/train_data')\n with open(model_filename, 'wb') as model_file:\n joblib.dump(grid_search, model_file)\n with open(data_filename, 'wb') as data_file:\n joblib.dump({'X_train': X_train,\n 'X_test': X_test,\n 'y_train': y_train,\n 'y_test': y_test,\n 'training_settings': training_settings\n }, data_file)\n\n return grid_search.best_params_, grid_search.score(X_train, y_train), \\\n grid_search.score(X_test, y_test)\n"
] |
[
[
"sklearn.metrics.mean_absolute_error",
"numpy.histogram",
"sklearn.metrics.r2_score",
"sklearn.metrics.mean_squared_error"
],
[
"sklearn.preprocessing.StandardScaler",
"sklearn.model_selection.GridSearchCV",
"sklearn.model_selection.train_test_split",
"sklearn.pipeline.Pipeline"
]
] |
trajkova-elena/scikit-multiflow
|
[
"dd372c677a97346a9c60cd25b45b350e0fd83d3c"
] |
[
"tests/meta/test_multi_output_learner.py"
] |
[
"from skmultiflow.data.generator.multilabel_generator import MultilabelGenerator\nfrom skmultiflow.data.generator.regression_generator import RegressionGenerator\nfrom skmultiflow.meta.multi_output_learner import MultiOutputLearner\nfrom skmultiflow.metrics.measure_collection import hamming_score\nfrom sklearn.linear_model import SGDClassifier, SGDRegressor\nfrom skmultiflow.utils.utils import get_next_n_samples\nfrom sklearn import __version__ as sklearn_version\nfrom sklearn.metrics import mean_absolute_error\nfrom distutils.version import LooseVersion\nfrom sklearn import set_config\nimport numpy as np\nimport pytest\n\n\n# Force sklearn to show only the parameters whose default value have been changed when\n# printing an estimator (backwards compatibility with versions prior to sklearn==0.23)\nset_config(print_changed_only=True)\n\n\[email protected]('ignore::UserWarning')\ndef test_multi_output_learner_classifier():\n\n stream = MultilabelGenerator(n_samples=5150,\n n_features=15,\n n_targets=3,\n n_labels=4,\n random_state=112)\n\n estimator = SGDClassifier(random_state=112, max_iter=10, loss='log')\n classifier = MultiOutputLearner(base_estimator=estimator)\n\n X, y = get_next_n_samples(stream, 150)\n classifier.partial_fit(X, y)\n\n cnt = 0\n max_samples = 5000\n predictions = []\n true_labels = []\n wait_samples = 100\n correct_predictions = 0\n\n while cnt < max_samples:\n X, y = stream.next_sample()\n # Test every n samples\n if (cnt % wait_samples == 0) and (cnt != 0):\n predictions.append(classifier.predict(X)[0])\n true_labels.append(y[0])\n if np.array_equal(y[0], predictions[-1]):\n correct_predictions += 1\n\n classifier.partial_fit(X, y)\n cnt += 1\n\n if LooseVersion(sklearn_version) < LooseVersion(\"0.21\"):\n expected_predictions = [[1.0, 1.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0],\n [1.0, 1.0, 1.0], [0.0, 1.0, 1.0], [1.0, 1.0, 1.0], [0.0, 0.0, 1.0],\n [1.0, 1.0, 1.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 1.0, 1.0],\n [0.0, 1.0, 1.0], [0.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 0.0, 0.0],\n [0.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 1.0], [0.0, 1.0, 0.0],\n [0.0, 0.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0],\n [0.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0],\n [0.0, 1.0, 1.0], [1.0, 1.0, 1.0], [0.0, 1.0, 0.0], [0.0, 1.0, 1.0],\n [1.0, 1.0, 1.0], [0.0, 1.0, 1.0], [1.0, 0.0, 1.0], [0.0, 0.0, 1.0],\n [0.0, 1.0, 1.0], [0.0, 1.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0], [1.0, 1.0, 0.0], [1.0, 0.0, 1.0], [1.0, 0.0, 1.0],\n [0.0, 0.0, 1.0], [1.0, 1.0, 1.0], [0.0, 1.0, 0.0], [1.0, 1.0, 1.0],\n [0.0, 1.0, 1.0]]\n assert np.alltrue(np.array_equal(predictions, expected_predictions))\n\n expected_correct_predictions = 26\n assert correct_predictions == expected_correct_predictions\n\n expected_performance = 0.7755102040816326\n performance = hamming_score(true_labels, predictions)\n assert np.isclose(performance, expected_performance)\n\n expected_info = \"MultiOutputLearner(base_estimator=SGDClassifier(loss='log', \" \\\n \"random_state=112))\"\n info = \" \".join([line.strip() for line in classifier.get_info().split()])\n assert info == expected_info\n\n else:\n expected_predictions = [[1.0, 1.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0],\n [1.0, 1.0, 1.0], [0.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 0.0, 1.0],\n [1.0, 0.0, 1.0], [1.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 1.0, 1.0],\n [0.0, 1.0, 1.0], [0.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 0.0],\n [1.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 1.0], [1.0, 1.0, 1.0],\n [1.0, 0.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0],\n [0.0, 1.0, 1.0], [1.0, 1.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 1.0],\n [0.0, 1.0, 1.0], [1.0, 1.0, 0.0], [1.0, 1.0, 1.0], [0.0, 1.0, 1.0],\n [1.0, 1.0, 1.0], [0.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 0.0, 1.0],\n [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 1.0],\n [0.0, 0.0, 1.0], [1.0, 1.0, 0.0], [1.0, 0.0, 1.0], [0.0, 0.0, 1.0],\n [0.0, 0.0, 1.0], [1.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 1.0, 1.0],\n [0.0, 1.0, 1.0]]\n np.alltrue(np.array_equal(predictions, expected_predictions))\n\n expected_correct_predictions = 23\n assert correct_predictions == expected_correct_predictions\n\n expected_performance = 0.7482993197278911\n performance = hamming_score(true_labels, predictions)\n assert np.isclose(performance, expected_performance)\n\n expected_info = \"MultiOutputLearner(base_estimator=SGDClassifier(loss='log', \" \\\n \"max_iter=10, random_state=112))\"\n\n info = \" \".join([line.strip() for line in classifier.get_info().split()])\n assert info == expected_info\n\n assert type(classifier.predict(X)) == np.ndarray\n assert type(classifier.predict_proba(X)) == np.ndarray\n\n\[email protected]('ignore::UserWarning')\ndef test_multi_output_learner_regressor():\n\n stream = RegressionGenerator(n_samples=5500,\n n_features=10,\n n_informative=20,\n n_targets=2,\n random_state=1)\n\n estimator = SGDRegressor(random_state=112, tol=1e-3, max_iter=10, loss='squared_loss')\n learner = MultiOutputLearner(base_estimator=estimator)\n\n X, y = get_next_n_samples(stream, 150)\n learner.partial_fit(X, y)\n\n cnt = 0\n max_samples = 5000\n predictions = []\n true_targets = []\n wait_samples = 100\n correct_predictions = 0\n\n while cnt < max_samples:\n X, y = stream.next_sample()\n # Test every n samples\n if (cnt % wait_samples == 0) and (cnt != 0):\n predictions.append(learner.predict(X)[0])\n true_targets.append(y[0])\n if np.array_equal(y[0], predictions[-1]):\n correct_predictions += 1\n\n learner.partial_fit(X, y)\n cnt += 1\n\n expected_performance = 2.444365309339395\n performance = mean_absolute_error(true_targets, predictions)\n assert np.isclose(performance, expected_performance)\n\n assert learner._estimator_type == \"regressor\"\n assert type(learner.predict(X)) == np.ndarray\n\n with pytest.raises(AttributeError):\n learner.predict_proba(X)\n"
] |
[
[
"numpy.array_equal",
"sklearn.linear_model.SGDRegressor",
"sklearn.metrics.mean_absolute_error",
"sklearn.set_config",
"sklearn.linear_model.SGDClassifier",
"numpy.isclose"
]
] |
ccen-stripe/tflite-support
|
[
"a92abc7eb8bd08c1fb8b26fecf394e0f8fcf3654"
] |
[
"tensorflow_lite_support/custom_ops/kernel/ngrams_test.py"
] |
[
"# Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for tensorflow_lite_support.custom_ops.ngrams.\"\"\"\n\nimport os\nimport sys\nimport timeit\n\nfrom absl import logging\nfrom absl.testing import parameterized\nimport tensorflow as tf\nimport tensorflow_text as tf_text\nfrom tensorflow.lite.python import interpreter as interpreter_wrapper # pylint: disable=g-direct-tensorflow-import\nfrom tensorflow_lite_support.custom_ops.python import tflite_text_api\n\n# Force loaded shared object symbols to be globally visible. This is needed so\n# that the interpreter_wrapper, in one .so file, can see the op resolver\n# in a different .so file. Note that this may already be set by default.\n# pylint: disable=g-import-not-at-top,g-bad-import-order,unused-import\nif hasattr(sys, 'setdlopenflags') and hasattr(sys, 'getdlopenflags'):\n sys.setdlopenflags(sys.getdlopenflags() | os.RTLD_GLOBAL)\nfrom tensorflow_lite_support.custom_ops.kernel import _pywrap_ngrams_op_resolver\n\nTEST_CASES = [\n [['this', 'is', 'a', 'test']],\n [['one']],\n [['two', 'tokens'], ['a', 'b']],\n [['has', 'three', 'tokens'], ['a', 'b', 'c'], ['0', '1', '2']],\n [['a', 'ragged', 'tensor'], ['a'], ['0', '1']],\n [[['a', 'multidimensional', 'test', 'case'], ['a', 'b', 'c', 'd', 'e']],\n [['0', '1', '2', '3', '4', '5']]],\n]\n\nINVOKES_FOR_SINGLE_OP_BENCHMARK = 1000\nINVOKES_FOR_FLEX_DELEGATE_BENCHMARK = 100\n\n\nclass NgramsTest(parameterized.TestCase):\n\n _models = {}\n\n def _make_model(self, rank, width, ragged_tensor=False, flex=False):\n temp_dir = self.create_tempdir().full_path\n\n key = (rank, width, ragged_tensor, flex)\n if key in self._models:\n return self._models[key]\n\n ngrams = tf_text.ngrams if flex else tflite_text_api.ngrams\n\n if ragged_tensor:\n input_signature = [tf.TensorSpec(shape=[None], dtype=tf.string)]\n rs = rank - 1\n input_signature += [tf.TensorSpec(shape=[None], dtype=tf.int64)] * rs\n\n class Model(tf.Module):\n\n @tf.function(input_signature=input_signature)\n def __call__(self, values, *args):\n row_splits = list(args)\n input_tensor = tf.RaggedTensor.from_nested_row_splits(\n flat_values=values, nested_row_splits=tuple(row_splits))\n output_tensor = ngrams(\n input_tensor, width, reduction_type=tf_text.Reduction.STRING_JOIN)\n output = [output_tensor.flat_values]\n output.extend(list(output_tensor.nested_row_splits))\n return tuple(output)\n\n tf.saved_model.save(Model(), temp_dir)\n else:\n shape = [None] * rank\n\n class Model(tf.Module):\n\n @tf.function(\n input_signature=[tf.TensorSpec(shape=shape, dtype=tf.string)])\n def __call__(self, input_tensor):\n return ngrams(\n input_tensor, width, reduction_type=tf_text.Reduction.STRING_JOIN)\n\n tf.saved_model.save(Model(), temp_dir)\n\n converter = tf.lite.TFLiteConverter.from_saved_model(temp_dir)\n converter.inference_type = tf.float32\n converter.inference_input_type = tf.float32\n converter.allow_custom_ops = not flex\n if flex:\n converter.target_spec.supported_ops = [\n tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS\n ]\n model = converter.convert()\n self._models[key] = model\n return model\n\n @parameterized.parameters([t] for t in TEST_CASES)\n def test_width_2_tensor_equivalence(self, test_case):\n input_tensor = tf.ragged.constant(test_case).to_tensor()\n tf_output = tf_text.ngrams(\n input_tensor, 2, reduction_type=tf_text.Reduction.STRING_JOIN)\n\n rank = input_tensor.shape.rank\n model = self._make_model(rank, 2, ragged_tensor=False, flex=False)\n interpreter = interpreter_wrapper.InterpreterWithCustomOps(\n model_content=model, custom_op_registerers=['AddNgramsCustomOp'])\n interpreter.resize_tensor_input(0, input_tensor.shape)\n interpreter.allocate_tensors()\n interpreter.set_tensor(interpreter.get_input_details()[0]['index'],\n input_tensor.numpy())\n interpreter.invoke()\n tflite_output = interpreter.get_tensor(\n interpreter.get_output_details()[0]['index'])\n\n self.assertEqual(tf_output.numpy().tolist(), tflite_output.tolist())\n\n @parameterized.parameters([t] for t in TEST_CASES)\n def test_width_3_tensor_equivalence(self, test_case):\n input_tensor = tf.ragged.constant(test_case).to_tensor()\n tf_output = tf_text.ngrams(\n input_tensor, 3, reduction_type=tf_text.Reduction.STRING_JOIN)\n\n rank = input_tensor.shape.rank\n model = self._make_model(rank, 3, ragged_tensor=False, flex=False)\n interpreter = interpreter_wrapper.InterpreterWithCustomOps(\n model_content=model, custom_op_registerers=['AddNgramsCustomOp'])\n interpreter.resize_tensor_input(0, input_tensor.shape)\n interpreter.allocate_tensors()\n interpreter.set_tensor(interpreter.get_input_details()[0]['index'],\n input_tensor.numpy())\n interpreter.invoke()\n tflite_output = interpreter.get_tensor(\n interpreter.get_output_details()[0]['index'])\n self.assertEqual(tf_output.numpy().tolist(), tflite_output.tolist())\n\n @parameterized.parameters([t] for t in TEST_CASES)\n def test_width_2_ragged_tensor_equivalence(self, test_case):\n input_tensor = tf.ragged.constant(test_case)\n tf_output = tf_text.ngrams(\n input_tensor, 2, reduction_type=tf_text.Reduction.STRING_JOIN)\n rank = input_tensor.shape.rank\n model = self._make_model(rank, 2, ragged_tensor=True, flex=False)\n interpreter = interpreter_wrapper.InterpreterWithCustomOps(\n model_content=model, custom_op_registerers=['AddNgramsCustomOp'])\n signature_fn = interpreter.get_signature_runner()\n signature_kwargs = {}\n signature_kwargs['values'] = input_tensor.flat_values.numpy()\n for r in range(rank - 1):\n signature_kwargs[f'args_{r}'] = input_tensor.nested_row_splits[r].numpy()\n output = signature_fn(**signature_kwargs)\n tflite_output_values = output['output_0']\n self.assertEqual(tf_output.flat_values.numpy().tolist(),\n tflite_output_values.tolist())\n for i in range(rank - 1):\n tflite_output_cur_row_splits = output[f'output_{i + 1}']\n self.assertEqual(tf_output.nested_row_splits[i].numpy().tolist(),\n tflite_output_cur_row_splits.tolist())\n\n @parameterized.parameters([t] for t in TEST_CASES)\n def test_width_3_ragged_tensor_equivalence(self, test_case):\n input_tensor = tf.ragged.constant(test_case)\n tf_output = tf_text.ngrams(\n input_tensor, 3, reduction_type=tf_text.Reduction.STRING_JOIN)\n\n rank = input_tensor.shape.rank\n model = self._make_model(rank, 3, ragged_tensor=True, flex=False)\n interpreter = interpreter_wrapper.InterpreterWithCustomOps(\n model_content=model, custom_op_registerers=['AddNgramsCustomOp'])\n signature_fn = interpreter.get_signature_runner()\n signature_kwargs = {}\n signature_kwargs['values'] = (\n input_tensor.flat_values.numpy().astype('bytes'))\n for r in range(rank - 1):\n signature_kwargs[f'args_{r}'] = input_tensor.nested_row_splits[r].numpy()\n output = signature_fn(**signature_kwargs)\n tflite_output_values = output['output_0']\n self.assertEqual(tf_output.flat_values.numpy().tolist(),\n tflite_output_values.tolist())\n for i in range(rank - 1):\n tflite_output_cur_row_splits = output[f'output_{i+1}']\n self.assertEqual(tf_output.nested_row_splits[i].numpy().tolist(),\n tflite_output_cur_row_splits.tolist())\n\n def test_latency(self):\n latency_op = 0.0\n for test_case in TEST_CASES:\n input_tensor = tf.ragged.constant(test_case)\n\n rank = input_tensor.shape.rank\n model = self._make_model(rank, 3, ragged_tensor=True, flex=False)\n interpreter = interpreter_wrapper.InterpreterWithCustomOps(\n model_content=model, custom_op_registerers=['AddNgramsCustomOp'])\n signature_fn = interpreter.get_signature_runner()\n signature_kwargs = {}\n signature_kwargs['values'] = input_tensor.flat_values.numpy()\n for r in range(rank - 1):\n signature_kwargs[f'args_{r}'] = input_tensor.nested_row_splits[r].numpy()\n start_time = timeit.default_timer()\n for _ in range(INVOKES_FOR_SINGLE_OP_BENCHMARK):\n _ = signature_fn(**signature_kwargs)\n latency_op = latency_op + timeit.default_timer() - start_time\n latency_op = latency_op / (\n INVOKES_FOR_SINGLE_OP_BENCHMARK * len(TEST_CASES))\n\n latency_flex = 0.0\n for test_case in TEST_CASES:\n input_tensor = tf.ragged.constant(test_case)\n\n rank = input_tensor.shape.rank\n model = self._make_model(rank, 3, ragged_tensor=True, flex=True)\n interpreter = interpreter_wrapper.Interpreter(model_content=model)\n signature_fn = interpreter.get_signature_runner()\n signature_kwargs = {}\n signature_kwargs['values'] = input_tensor.flat_values.numpy()\n\n for r in range(rank - 1):\n signature_kwargs[f'args_{r}'] = input_tensor.nested_row_splits[r].numpy(\n )\n start_time = timeit.default_timer()\n for _ in range(INVOKES_FOR_FLEX_DELEGATE_BENCHMARK):\n _ = signature_fn(**signature_kwargs)\n latency_flex = latency_flex + timeit.default_timer() - start_time\n latency_flex = latency_flex / (\n INVOKES_FOR_FLEX_DELEGATE_BENCHMARK * len(TEST_CASES))\n\n logging.info('Latency (single op): %fms', latency_op * 1000.0)\n logging.info('Latency (flex delegate): %fms', latency_flex * 1000.0)\n\n\nif __name__ == '__main__':\n tf.test.main()\n"
] |
[
[
"tensorflow.lite.python.interpreter.InterpreterWithCustomOps",
"tensorflow.ragged.constant",
"tensorflow.test.main",
"tensorflow.lite.python.interpreter.Interpreter",
"tensorflow.function",
"tensorflow.lite.TFLiteConverter.from_saved_model",
"tensorflow.TensorSpec"
]
] |
KGJsGit/my_Optimization-studio
|
[
"1f3f78c22c58017f439c7be8b716a233be872ccc",
"1f3f78c22c58017f439c7be8b716a233be872ccc"
] |
[
"code/CS/cps2.py",
"code/GA/GA_TSP.py"
] |
[
"import numpy as np\r\nimport pandas as pd\r\nimport random as rd\r\n\r\npd.set_option('display.expand_frame_repr', False) # DataFrame 출력시 짤림 해결\r\npd.set_option('display.max_rows', 400)\r\npd.set_option('display.max_columns', 200)\r\npd.set_option('display.width', 1000)\r\n\r\nclass Machine :\r\n # ['Set', job, operation, machine, processingTime, start]\r\n def __init__(self, setup, number):\r\n print('...'+str(number)+'번 Machine를 초기화중입니다...')\r\n self.isIdle = True\r\n self.setup = setup\r\n self.number = number\r\n self.machine_time = 0\r\n self.recentSetup = 0\r\n self.queue = [] # 아직 못들어간 대기 엔티티들\r\n self.system = [] # 기계 안에서 직접 할당중인 엔티티\r\n\r\n def allocation(self, info):\r\n self.system.append(info)\r\n self.isIdle = False\r\n self.recentSetup = int(info[0])\r\n return info\r\n\r\n def deallocation(self):\r\n self.system.pop()\r\n self.isIdle = True\r\n\r\nclass Simulator :\r\n def __init__(self, environment, setup, number_of_jobs, operations_per_jobs, number_of_machines):\r\n print('...Simulator를 초기화중입니다...')\r\n self.environment = environment\r\n self.number_of_jobs = number_of_jobs\r\n self.operations_per_jobs = operations_per_jobs\r\n self.number_of_machines = number_of_machines\r\n self.setup = setup\r\n\r\n self.machineInit()\r\n\r\n self.eventlist = []\r\n self.TNOW = 0\r\n self.index = 0\r\n self.completer = []\r\n print('Simulating 준비가 모두 끝났습니다.')\r\n\r\n def initialize(self):\r\n self.eventlist = []\r\n self.TNOW = 0\r\n self.index = 0\r\n self.completer = []\r\n self.machineInit()\r\n\r\n def machineInit(self):\r\n self.machineList = []\r\n self.machine_assign = []\r\n self.machine_per_index = []\r\n for i in range(1, self. number_of_machines+1) :\r\n self.machineList.append(Machine(self.setup[i-1], i))\r\n self.machine_assign.append([])\r\n self.machine_per_index.append(0)\r\n\r\n def sortEventlist(self):\r\n self.eventlist = sorted(self.eventlist, key=lambda x : x[-1])\r\n\r\n def feasibleChecker(self):\r\n # TODO Fully Feasible 체커는 좀 나중에 구현하는 걸로... 방법은 J,O 떼와서 정렬인지 확인 + M할당 적합성 확인?\r\n return True\r\n\r\n def getDepartureInfo(self, JOM):\r\n alloc_machine = self.machineList[int(JOM[2]) - 1]\r\n job = int(JOM[0])\r\n operation = int(JOM[1])\r\n machine = int(JOM[2])\r\n processingTime = self.environment[job-1][operation-1][machine-1]\r\n\r\n if alloc_machine.recentSetup == 0 :\r\n processingTime += self.setup[int(job)-1][int(job)-1] # 디폴트 셋업\r\n elif alloc_machine.recentSetup != job or alloc_machine.recentSetup != int(job) :\r\n processingTime += self.setup[int(job)-1][alloc_machine.recentSetup - 1]\r\n\r\n finishTime = self.TNOW + processingTime\r\n\r\n alloc_machine.allocation([job, operation, machine, processingTime, finishTime])\r\n\r\n return ['Dep', job, operation, machine, processingTime, finishTime]\r\n\r\n def output_per_index(self):\r\n print(self.index, \"번 째 Event list :\", self.eventlist, 'TNOW : ', self.TNOW)\r\n\r\n def machine_assigner(self):\r\n for i in self.solution :\r\n self.machine_assign[int(i[2])-1].append(i)\r\n\r\n def finder(self, JO):\r\n finder = None\r\n for i in range(self.number_of_machines) :\r\n try :\r\n if JO == str(int(self.machine_assign[i][self.machine_per_index[i]][0:2])-1) and self.machineList[i].isIdle == True :\r\n finder = self.machine_assign[i][self.machine_per_index[i]]\r\n except :\r\n pass\r\n\r\n return finder\r\n\r\n def simulate(self, solution):\r\n self.initialize()\r\n self.solution = solution\r\n if self.feasibleChecker() == False : # 모든 해가 유효하게 가정 및 유도\r\n print(\"해가 유효하지 않습니다.\")\r\n return\r\n\r\n print(solution)\r\n self.machine_assigner() # Machine assign 산출\r\n print(self.machine_assign)\r\n # initialer = 0\r\n for i in range(self.number_of_machines) :\r\n if self.machine_assign[i][0][1] == '1' :\r\n todo = self.machine_assign[i][0]\r\n self.eventlist.append(self.getDepartureInfo(todo))\r\n\r\n # for i in range(initialer) :\r\n # todo = self.machine_assign[i][0]\r\n # self.eventlist.append(self.getDepartureInfo(todo))\r\n # # self.machine_per_index[i] += 1\r\n\r\n self.eventlist.append(['End', 9999, 9999, 9999, 9999, 9999])\r\n self.sortEventlist()\r\n self.output_per_index()\r\n\r\n while self.eventlist[0][0] != 'End' :\r\n self.index += 1 # 인덱스 +1\r\n self.output_per_index()\r\n\r\n self.TNOW = self.eventlist[0][-1]\r\n currenter = self.machine_assign[int(self.eventlist[0][3]) - 1][self.machine_per_index[int(self.eventlist[0][3]) - 1]] # JOM\r\n try :\r\n nexter = self.machine_assign[int(self.eventlist[0][3])-1][self.machine_per_index[int(self.eventlist[0][3])-1]+1] # J'O'M'\r\n except :\r\n pass\r\n self.machineList[int(self.eventlist[0][3])-1].deallocation()\r\n self.completer.append(currenter[0:2]) # JO\r\n self.eventlist.pop(0)\r\n print(currenter, '를 해치웠다!', self.TNOW)\r\n if self.machine_per_index[int(currenter[2])-1] < len(self.machine_assign[int(currenter[2])-1]) :\r\n self.machine_per_index[int(currenter[2])-1] +=1\r\n print(\"case0\")\r\n\r\n # JOM 다음이 JO+1M일경우 바로 할당\r\n if currenter == str(int(nexter)-10) :\r\n todo = nexter\r\n self.eventlist.append(self.getDepartureInfo(todo))\r\n # self.machine_per_index[int(currenter[2])-1] += 1\r\n self.sortEventlist()\r\n print(\"case1-1\")\r\n\r\n # JOM 다음이 J'O'M인데, J', O'-1이 끝난 상황이면 바로 할당\r\n elif (str(int(nexter[0:2])-1) in self.completer or nexter[1] == '1') and currenter[-1] == nexter[-1] and currenter != nexter :\r\n todo = nexter\r\n self.eventlist.append(self.getDepartureInfo(todo))\r\n # self.machine_per_index[int(currenter[-1])-1] += 1\r\n self.sortEventlist()\r\n print(\"case2-1\")\r\n\r\n finder = self.finder(currenter[0:2])\r\n if finder != None :\r\n todo = finder\r\n self.eventlist.append(self.getDepartureInfo(todo))\r\n # self.machine_per_index[int(todo[-1])-1] += 1\r\n self.sortEventlist()\r\n print(\"case3-1\")\r\n\r\n return self.TNOW\r\n\r\nclass CuckooSearch :\r\n def __init__(self, popSize, maxIter, number_of_jobs, operations_per_jobs, number_of_machines, target_env, method):\r\n self.number_of_jobs = number_of_jobs\r\n self.operation_per_jobs = operations_per_jobs\r\n self.number_of_machines = number_of_machines\r\n self.target_env = target_env\r\n self.popSize = popSize\r\n self.maxIter = maxIter\r\n self.pa = 0.25\r\n self.selPres = 0.5\r\n self.iteration = 0\r\n self.population = []\r\n self.method = method\r\n\r\n def initialize(self):\r\n solution = []\r\n env = []\r\n for i in range(1, self.number_of_jobs+1) :\r\n jobNum = i\r\n temp = []\r\n for j in range(1, self.operation_per_jobs+1) :\r\n temp.append(str(jobNum)+str(j))\r\n env.append(temp)\r\n\r\n while 1 :\r\n if env == [[], [], [], []] :\r\n break\r\n rand1 = rd.randint(0, self.number_of_jobs-1)\r\n try :\r\n solution.append(env[rand1].pop(0))\r\n except :\r\n pass\r\n\r\n solution_result = []\r\n for i in solution :\r\n machine = 0\r\n job = i[0]\r\n operation = i[1]\r\n machine_pool = self.target_env[int(job)-1][int(operation)-1]\r\n while 1:\r\n rand2 = rd.randint(1, len(machine_pool))\r\n if np.isnan(self.target_env[int(job)-1][int(operation)-1][rand2-1]) :\r\n pass\r\n else :\r\n machine = rand2\r\n break\r\n solution_result.append(i+str(machine))\r\n\r\n return solution_result\r\n\r\n def get_fitness(self, solution):\r\n return self.method.simulate(solution)\r\n\r\n def sorting(self):\r\n self.population = sorted(self.population, key=lambda x : x[-1])\r\n\r\n def search(self):\r\n # initialize\r\n for i in range(self.popSize) :\r\n temp = []\r\n temp.append(self.initialize())\r\n temp.append(self.get_fitness(temp[0]))\r\n self.population.append(temp)\r\n self.sorting()\r\n\r\n print(self.population)\r\n\r\n # todo levystep, smallstep, largestep\r\n\r\nif __name__ == \"__main__\" :\r\n target_env = [\r\n [[20, 15, 18, 17], [7, np.nan, 8, np.nan], [12, 10, np.nan, 15], [14, np.nan, 12, 12], [11, np.nan, 12, 12]],\r\n [[np.nan, 23, np.nan, 32], [22, np.nan, 12, np.nan], [23, 19, np.nan, np.nan], [27, np.nan, np.nan, 25], [np.nan, 13, 16, np.nan]],\r\n [[16, 5, 5, 4], [np.nan, 5, np.nan, 5], [12, 5, 5, 7], [np.nan, 5, np.nan, 5], [14, 5, 6, 7]],\r\n [[12, np.nan, 14 ,np.nan], [17, np.nan, 18, np.nan], [np.nan, 20, np.nan, 21], [22, np.nan ,np.nan, 23], [np.nan, 12, 26, np.nan]],\r\n ]\r\n\r\n setup_time = [[5, 4, 2, 4],\r\n [2, 5, 2, 3],\r\n [1, 5, 5, 1],\r\n [4, 4, 4, 5]]\r\n\r\n number_of_jobs = 4\r\n operations_per_jobs = 5\r\n number_of_machines = 4\r\n\r\n solution = ['111', '212', '314', '413', '121',\r\n '223', '322', '423', '131', '232',\r\n '333', '434', '143', '241', '342',\r\n '444', '154', '253', '352', '452']\r\n\r\n minju_solution = ['314', '212', '411', '113', '324',\r\n '223', '121', '423', '333', '232',\r\n '131', '434', '143', '244', '441',\r\n '342', '352', '452', '253', '151']\r\n\r\n minju_solution2 = ['212', '114', '313', '411', '223',\r\n '421', '121', '322', '132', '232',\r\n '434', '333', '444', '342', '241',\r\n '143', '153', '252', '353', '453']\r\n\r\n hard = ['411', '313', '113', '423', '121', '212', '221', '232', '324', '333', '241', '342', '351', '432', '131', '141', '441', '452', '253', '151']\r\n\r\n simul = Simulator(environment=target_env,\r\n setup=setup_time,\r\n number_of_jobs=number_of_jobs,\r\n operations_per_jobs=operations_per_jobs,\r\n number_of_machines=number_of_machines)\r\n\r\n result = simul.simulate(solution=minju_solution2)\r\n print(result)\r\n\r\n cs = CuckooSearch(popSize=20,\r\n maxIter=100,\r\n number_of_jobs=number_of_jobs,\r\n operations_per_jobs = operations_per_jobs,\r\n number_of_machines = number_of_machines,\r\n target_env=target_env,\r\n method=simul)\r\n\r\n # cs.search()",
"import math\nimport timeit\nimport numpy as np\nimport random\nfrom threading import Thread\nimport functools\n\n# 시간제한 데코레이터\ndef timeout(seconds_before_timeout):\n def deco(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n res = [Exception('function [%s] timeout [%s seconds] exceeded!' %(func.__name__, seconds_before_timeout))]\n def newFunc():\n try:\n res[0] = func(*args, **kwargs)\n except Exception as e:\n res[0] = e\n t = Thread(target=newFunc)\n t.daemon = True\n try:\n t.start()\n t.join(seconds_before_timeout)\n except Exception as e:\n print('error starting thread')\n raise e\n ret = res[0]\n if isinstance(ret, BaseException):\n raise ret\n return ret\n return wrapper\n return deco\n\n\ndist_ar = [] # 거리표(global)\nlimit_time = 36 # 제한시간(global)\ncities_count = 0 # 도시 수(global)\ndots_list = [] # 도시 리스트(global)\n\n# Hyper Parameter\nMUT = 0.2 # 변이확률\nSEL = 0.85 # 선택압\nEND = 1000 # 최종세대 설정\nchrCOUNT = 50 # 해집단 내 염색체 개수\nselCOUNT = 25 # selection시 선택되는 상위 염색체의 개수\n\n# 거리표 제작(param : 문제 경로) : dist_df\ndef make_distDataframe(str):\n global dist_ar\n global limit_time\n global cities_count\n global dots_list\n\n reader = open(str, mode='rt', encoding='utf-8')\n dots_list = reader.read().split(\"\\n\") # ['x1 y1', 'x2 y2', 'x3 y3' ... 'xn yn']\n cities_count = int(dots_list.pop(0))\n limit_time = float(dots_list.pop())\n\n x_list = [] # ['x1', 'x2', 'x3' ... 'xn']\n y_list = [] # ['y1', 'y2', 'y3' ... 'yn']\n for i in range(cities_count):\n temp = dots_list[i].split(\" \")\n x_list.append(float(temp[0]))\n y_list.append(float(temp[1]))\n\n dist_ar = []\n for n in range(cities_count):\n temp = []\n for m in range(cities_count):\n temp.append(round((math.sqrt(((x_list[m] - x_list[n]) ** 2) + ((y_list[m] - y_list[n]) ** 2))), 2))\n dist_ar.append(temp)\n\n dist_ar = np.array(dist_ar)\n print(dist_ar)\n\n# 거리표를 이용한 적합도 매칭 함수\ndef cal_fit(stri) :\n fit = 0\n for i in range(len(stri)-1) :\n if i == len(stri)-1 :\n fit += dist_ar[stri[i], stri[0]]\n else :\n fit += dist_ar[stri[i], stri[i+1]]\n return fit\n\n# 0 ~ ranges-1의 범위 중 두 개를 랜덤으로 샘플링해서 list 리턴\ndef randomTwo(ranges) :\n randomList = []\n randomList += random.sample(range(0,ranges), 2)\n randomList.sort()\n return randomList\n\ndef TSP_GA() :\n # 환경 설정 및 초기화\n generation = 1 # 현재 세대\n population = [] # 현재 세대 or initializing시 최종 population\n population_fit = [] # population의 적합도\n populations = [] #population과 적합도로 이루어진 이차원 배열\n step_result = [] # step을 거칠 때 변화된 population\n\n # initialize\n for i in range(chrCOUNT) :\n population.append(random.sample(range(0, cities_count), cities_count))\n\n for i in range(chrCOUNT) :\n population_fit.append(round(cal_fit(population[i]), 5))\n\n populations = np.array([population, population_fit])\n populations = populations.T\n # print('초기 염색체 : \\n', population, '\\n염색체 별 적합도 :\\n', population_fit)\n # print(populations)\n\n while 1:\n generation += 1\n populations = populations[np.argsort(populations[:, 1])]\n\n # selection : 토너먼트선택,\n populations = populations[np.argsort(populations[:, 1])]\n for endSel in range(selCOUNT):\n # 난수룰 발생시켜 해집단 내 두 유전자 선택, 선택난수 발생\n # 선택난수가 선택압보다 작으면 두 유전자 중 좋은 유전자가 선택. 아니면 반대로\n parents_index = [0] * 2\n for i in range(len(parents_index)):\n selGeneNum = randomTwo((chrCOUNT - endSel))\n match = random.random()\n if match < SEL:\n if populations[selGeneNum[0], 1] < populations[selGeneNum[1], 1]:\n parents_index[i] = selGeneNum[0]\n else:\n parents_index[i] = selGeneNum[1]\n else:\n if populations[selGeneNum[0], 1] < populations[selGeneNum[1], 1]:\n parents_index[i] = selGeneNum[1]\n else:\n parents_index[i] = selGeneNum[0]\n # crossover : order-based crossover\n daddy_value = populations[parents_index[0], 0].copy()\n mommy_value = populations[parents_index[1], 0].copy()\n CsGeneNum = randomTwo(cities_count)\n offspring = daddy_value[CsGeneNum[0]: CsGeneNum[1]]\n for i in daddy_value[CsGeneNum[0]: CsGeneNum[1]]:\n mommy_value.remove(i)\n for i in range(len(offspring)):\n mommy_value.insert(CsGeneNum[0] + i, offspring[i])\n offspring = mommy_value\n offspring_fit = cal_fit(offspring)\n\n # mutation : exchange mutation\n mut_p = random.random()\n if mut_p < MUT:\n MtGeneNum = randomTwo(cities_count)\n mut_Temp = offspring[MtGeneNum[0]]\n offspring[MtGeneNum[0]] = offspring[MtGeneNum[1]]\n offspring[MtGeneNum[1]] = mut_Temp\n offspring_fit = cal_fit(offspring)\n populations = np.vstack((populations, [offspring, offspring_fit]))\n # Replacement\n populations = populations[np.argsort(populations[:, 1])]\n for i in range(chrCOUNT - selCOUNT):\n np.delete(populations, (chrCOUNT + i), axis=0)\n print(generation, '세대 최적 해 : \\n', populations[0, 0], \"\\n\", populations[0, 1])\n\n@timeout(limit_time)\ndef start_GA(stri) :\n make_distDataframe(stri)\n TSP_GA()\n\ntry :\n start = timeit.default_timer()\n start_GA(\"2opt_dots/2opt_cycle100.in\")\n stop = timeit.default_timer()\n print(stop - start)\nexcept :\n stop = timeit.default_timer()\n print(stop - start)\n"
] |
[
[
"pandas.set_option"
],
[
"numpy.argsort",
"numpy.delete",
"numpy.array",
"numpy.vstack"
]
] |
mmaher22/Instance-based-smoothing
|
[
"a6aaed2d26d828f59bbc2ae10a9bd6ad83528ecc"
] |
[
"Instance-based Smoothing in Neural Networks/Instance-based-smoothing.py"
] |
[
"# -*- coding: utf-8 -*-\nimport os\nimport gc\nimport copy\nimport torch\nimport pickle\nimport random\nimport argparse\nimport torchvision\nimport numpy as np\nimport pandas as pd\nimport torch.nn as nn\nfrom PIL import Image\nimport torch.optim as optim\nfrom netcal.metrics import ECE\nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt\nfrom sklearn.manifold import TSNE\nfrom torchvision import transforms\nfrom torch.utils.data import Dataset\nfrom models.densenet import DenseNet\nfrom models.inception import inceptionv4\nfrom models.resnet import ResNet18, ResNet50\nfrom utils.utils import progress_bar, save_model\nfrom torch.utils.data.sampler import SubsetRandomSampler\n########################################################################################\n#################################### Loss Functions ####################################\n########################################################################################\nclass KDELabelSmoothingCrossEntropy(nn.Module):\n def __init__(self, orig_net, mul_factor = 1, smoothing = 0.1):\n super(KDELabelSmoothingCrossEntropy, self).__init__()\n self.orig_net = orig_net\n self.mul_factor = mul_factor\n self.smoothing = smoothing\n def forward(self, x, target, inputs):\n with torch.no_grad():\n sm = self.orig_net(inputs)\n sm = (sm.cpu().detach().numpy()) * self.mul_factor\n for i in range(len(sm)):\n mini = np.amin(sm[i, :])\n if mini < 0:\n sm[i, :] -= mini\n sums = np.sum(sm, axis = -1)\n for i in range(len(sm)):\n t = target[i].item()\n smoothing_factor = self.smoothing * sm[i, t] / sums[i]\n sums[i] -= sm[i, t]\n sm[i, t] = 1 - smoothing_factor\n for j in range(args.num_classes):\n if j == t:\n continue\n else:\n if sums[i] == 0:\n sm[i, j] = smoothing_factor / (self.mul_factor - 1)\n else: \n sm[i, j] = smoothing_factor * (sm[i, j]) / sums[i]\n sm = torch.autograd.Variable(torch.from_numpy(sm).float().to(device), requires_grad=False)\n logprobs = F.log_softmax(x, dim=-1)\n smooth_loss = -(logprobs * sm).sum(dim=-1)\n loss = smooth_loss\n return loss.mean()\n\n###################################################################################\n#################################### Arguments ####################################\n###################################################################################\nnp.random.seed(42)\nparser = argparse.ArgumentParser()\nparser.add_argument('--lr', default=0.1, type=float, help='learning rate')\nparser.add_argument('--resume', '-r', action='store_true', help='resume from checkpoint')\nparser.add_argument('--ce', default = True, help='Cross entropy use')\nparser.add_argument('--dataset', default = 'fashionmnist', help='Dataset')\nparser.add_argument('--num_classes', default = 10, help='Dataset')\nparser.add_argument('--batch_size', default = 512, help='Batch size')\nparser.add_argument('--epochs', default = 100, help='Number of epochs')\nparser.add_argument('--estop', default = 10, help='Early stopping')\nparser.add_argument('--ece_bins', default = 10, help='ECE bins')\nparser.add_argument('--tr_size', default = 0.8, help='Training/Validation sets split ratio')\nparser.add_argument('--model', default = 'densenet', help='Model to be used')\nargs = parser.parse_args([])\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\n######################################################################################\n#################################### Data_Loaders ####################################\n######################################################################################\ndef get_transforms(dataset):\n if dataset[:5] == 'cifar':\n transform_train = transforms.Compose([transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), \n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),])\n transform_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),])\n transform_mi = transforms.Compose([transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), \n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),])\n else:\n transform_train = transforms.Compose([transforms.Resize(96), transforms.RandomHorizontalFlip(),transforms.ToTensor(),transforms.Normalize((0.5,), (0.5,)),])\n transform_test = transforms.Compose([transforms.Resize(96),transforms.ToTensor(),transforms.Normalize((0.5,), (0.5,)),]) \n transform_mi = transforms.Compose([transforms.Resize(128), transforms.RandomCrop(88, padding=4), transforms.RandomHorizontalFlip(),\n transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,)),])\n return transform_train, transform_test, transform_mi\n\ntransform_train, transform_test, transform_mi = get_transforms(args.dataset)\nif args.dataset == 'fashionmnist':\n trainset = torchvision.datasets.FashionMNIST(root='data', train=True, download=True, transform=transform_train,)\n validset = torchvision.datasets.FashionMNIST(root='data', train=True, download=True, transform=transform_test,)\n testset = torchvision.datasets.FashionMNIST(root='data', train=False, download=True, transform=transform_test,)\n trainset2 = torchvision.datasets.FashionMNIST(root='data', train=True , download=True)\n testset2 = torchvision.datasets.FashionMNIST(root='data', train=False, download=True)\nelif args.dataset == 'cifar10':\n trainset = torchvision.datasets.CIFAR10(root='data', train=True, download=True, transform=transform_train,)\n validset = torchvision.datasets.CIFAR10(root='data', train=True, download=True, transform=transform_test,)\n testset = torchvision.datasets.CIFAR10(root='data', train=False, download=True, transform=transform_test,)\n trainset2 = torchvision.datasets.CIFAR10(root='data', train=True , download=True)\n testset2 = torchvision.datasets.CIFAR10(root='data', train=False, download=True)\nelif args.dataset == 'cifar100':\n trainset = torchvision.datasets.CIFAR100(root='data', train=True, download=True, transform=transform_train,)\n validset = torchvision.datasets.CIFAR100(root='data', train=True, download=True, transform=transform_test,)\n testset = torchvision.datasets.CIFAR100(root='data', train=False, download=True, transform=transform_test,)\n trainset2 = torchvision.datasets.CIFAR100(root='data', train=True , download=True)\n testset2 = torchvision.datasets.CIFAR100(root='data', train=False, download=True)\n\nx_train = trainset2.data; x_test = testset2.data\ny_train = trainset2.targets; y_test = testset2.targets\nindices = list(range(len(trainset)))\nsplit = int(np.floor(args.tr_size * len(trainset)))\nnp.random.shuffle(indices)\ntrain_idx, valid_idx = indices[:split], indices[split:]\ntrain_sampler = SubsetRandomSampler(train_idx)\nvalid_sampler = SubsetRandomSampler(valid_idx)\ntrainloader = torch.utils.data.DataLoader(trainset, sampler=train_sampler, batch_size=args.batch_size, shuffle=False)\nvalidloader = torch.utils.data.DataLoader(validset, sampler=valid_sampler, batch_size=args.batch_size, shuffle=False)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=args.batch_size, shuffle=False)\ntrials = 1\n#######################################################################################\n#################################### Temp Scaling #####################################\n#######################################################################################\nclass ModelWithTemperature(nn.Module):\n def __init__(self, model):\n super(ModelWithTemperature, self).__init__()\n self.model = model\n self.temperature = nn.Parameter(torch.ones(1) * 1.5)\n\n def forward(self, input):\n logits = self.model(input)\n return self.temperature_scale(logits)\n\n def temperature_scale(self, logits):\n # Expand temperature to match the size of logits\n temperature = self.temperature.unsqueeze(1).expand(logits.size(0), logits.size(1))\n return logits / temperature\n\n def set_temperature(self, validloader):\n self.cuda()\n nll_criterion = nn.CrossEntropyLoss().cuda()\n logits_list = []; labels_list = []\n with torch.no_grad():\n for input, label in validloader:\n input = input.cuda()\n logits = self.model(input)\n logits_list.append(logits); labels_list.append(label)\n logits = torch.cat(logits_list).cuda(); labels = torch.cat(labels_list).cuda()\n optimizer = optim.LBFGS([self.temperature], lr=0.01, max_iter=50)\n def eval():\n loss = nll_criterion(self.temperature_scale(logits), labels)\n loss.backward()\n return loss\n optimizer.step(eval)\n return self\n\n########################################################################################\n#################################### Model Trainer #####################################\n########################################################################################\nclass ModelTrainer():\n def __init__(self, net, trainloader, validloader, optimizer, scheduler, criterion_train, criterion_test, save_path, \n epochs = args.epochs, estop = args.estop, device = 'cuda', num_classes = args.num_classes, trials = trials):\n self.net = net\n self.best_net = net\n self.trainloader = trainloader\n self.validloader = testloader\n self.device = device\n self.optimizer = optimizer\n self.scheduler = scheduler\n self.criterion = criterion_train\n self.criterion1 = criterion_test\n self.save_path = save_path\n self.num_classes = num_classes\n self.best_loss = 1e9\n self.early = estop\n self.trials = trials\n for epoch in range(epochs):\n self.train(epoch)\n self.valid(epoch)\n if self.early > estop:\n break\n\n def train(self, epoch):\n print('\\nEpoch: %d' % epoch)\n self.net.train()\n train_loss = 0; correct = 0; total = 0\n for batch_idx, (inputs, targets) in enumerate(self.trainloader):\n inputs, targets = inputs.to(self.device), targets.to(self.device)\n self.optimizer.zero_grad()\n outputs = self.net(inputs)\n try:\n loss = self.criterion(outputs, targets)\n except:\n loss = self.criterion(outputs, targets, inputs)\n loss.backward()\n self.optimizer.step()\n train_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n progress_bar(batch_idx, len(self.trainloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)' % \n (train_loss/(batch_idx+1), 100.*correct/total, correct, total))\n self.scheduler.step()\n print('Train Loss:', train_loss)\n\n def valid(self, epoch):\n self.net.eval()\n self.valid_loss = 0; total = 0; correct = 0\n with torch.no_grad():\n for batch_idx, (inputs, targets) in enumerate(self.validloader):\n inputs, targets = inputs.to(self.device), targets.to(self.device)\n outputs = self.net(inputs)\n loss = self.criterion1(outputs, targets)\n self.valid_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n progress_bar(batch_idx, len(self.validloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)' % \n (self.valid_loss/(batch_idx+1), 100.*correct/total, correct, total))\n acc = 100.*correct/total\n print('Validation Accuracy: ', acc)\n if self.valid_loss < self.best_loss:\n print('Saving..')\n if not os.path.isdir('checkpoint'):\n os.mkdir('checkpoint')\n self.best_net = copy.deepcopy(self.net) \n self.best_loss = self.valid_loss\n self.early = 0\n else:\n self.early += 1\n\n#########################################################################################\n#################################### Model selector #####################################\n#########################################################################################\ndef get_new_model(tmp_scale = True, num_classes = args.num_classes):\n if args.model == 'resnet18':\n return ResNet18(tmp_scale = tmp_scale, num_classes = num_classes)\n elif args.model == 'resnet50':\n return ResNet50(tmp_scale = tmp_scale, num_classes = num_classes)\n elif args.model == 'resnet101':\n return ResNet101(tmp_scale = tmp_scale, num_classes = num_classes)\n elif args.model == 'inceptionv4':\n return inceptionv4(tmp_scale = tmp_scale, num_classes = num_classes)\n elif args.model == 'densenet':\n return DenseNet(tmp_scale = tmp_scale)\n\ncriterion1 = nn.CrossEntropyLoss()\nresults_dict = {}\nresults_df = pd.DataFrame()\nsmoothing_factors = [0.01, 0.05, 0.1]\nmul_factors = [1, 10, 100, 1000]\n\nfor trial in range(3):\n gc.collect()\n main_path = 'files_' + args.model + '_' + args.dataset + '/trial' + str(trial) + '/' \n if not os.path.exists(main_path):\n os.makedirs(main_path)\n\n #################################################################################################################\n #################################### Instance-based label smoothing training ####################################\n #################################################################################################################\n best_loss = 1e9; best_net = None; save_path = main_path + 'Instance_LabelSmoothing_ce_logits.bin'\n if os.path.isfile(save_path):\n print (\"Model exists....Continue\")\n else:\n print (\"Model does not exist!....Training now:\", title)\n for smoothing in smoothing_factors:\n for mul_factor in mul_factors:\n title = 'InstanceLabelSmoothing'\n print(\"Start Instance-based Label Smoothing\")\n net = get_new_model()\n net = net.to(device)\n optimizer = optim.SGD(net.parameters(), lr = args.lr, momentum = 0.9, weight_decay = 0.0001, nesterov = True)\n scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[30,60,90])\n orig_net = get_new_model()\n states = torch.load(main_path + 'CrossEntropy.bin')\n orig_net.load_state_dict(states)\n orig_net = orig_net.to(device)\n orig_net.eval()\n criterion = KDELabelSmoothingCrossEntropy(orig_net, mul_factor = mul_factor, smoothing = smoothing)\n model = ModelTrainer(net = net, trainloader = trainloader, validloader = validloader, optimizer = optimizer, scheduler = scheduler,\n criterion_train = criterion, criterion_test = criterion1, save_path = save_path, device = device)\n if model.best_loss < best_loss:\n f = open(main_path + \"ILS_logs.txt\", \"w\")\n f.write('Smoothing_Factor=' + str(smoothing) + ', Mul_Factor=' + str(mul_Factor))\n best_net = model.best_net\n best_loss = model.best_loss\n if args.mutual_info:\n with open(title+'.pkl', 'wb') as fp:\n pickle.dump(model.mutual_info_values, fp)\n save_model(best_net, save_path)\n scaled_model = ModelWithTemperature(best_net)\n scaled_model.set_temperature(validloader)\n save_path = main_path + 'ILSTmpScaling.bin'\n best_net.temperature = scaled_model.temperature\n save_model(best_net, save_path)"
] |
[
[
"torch.optim.lr_scheduler.MultiStepLR",
"torch.nn.CrossEntropyLoss",
"torch.ones",
"numpy.random.seed",
"torch.nn.functional.log_softmax",
"numpy.amin",
"torch.load",
"torch.cat",
"torch.utils.data.DataLoader",
"torch.utils.data.sampler.SubsetRandomSampler",
"numpy.random.shuffle",
"pandas.DataFrame",
"torch.from_numpy",
"torch.optim.LBFGS",
"torch.no_grad",
"torch.cuda.is_available",
"numpy.sum"
]
] |
MAYURGAIKWAD/meshrcnn
|
[
"b47ecd47ca7de7055b7d141e63ddab286c5245f3",
"b47ecd47ca7de7055b7d141e63ddab286c5245f3"
] |
[
"shapenet/modeling/mesh_arch.py",
"shapenet/utils/binvox_torch.py"
] |
[
"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport torch\nimport torch.nn as nn\nfrom detectron2.utils.registry import Registry\nfrom pytorch3d.ops import cubify\nfrom pytorch3d.structures import Meshes\nfrom pytorch3d.utils import ico_sphere\n\nfrom shapenet.modeling.backbone import build_backbone\nfrom shapenet.modeling.heads import MeshRefinementHead, VoxelHead\nfrom shapenet.utils.coords import get_blender_intrinsic_matrix, voxel_to_world\n\nMESH_ARCH_REGISTRY = Registry(\"MESH_ARCH\")\n\n\n@MESH_ARCH_REGISTRY.register()\nclass VoxMeshHead(nn.Module):\n def __init__(self, cfg):\n super(VoxMeshHead, self).__init__()\n\n # fmt: off\n backbone = cfg.MODEL.BACKBONE\n self.cubify_threshold = cfg.MODEL.VOXEL_HEAD.CUBIFY_THRESH\n self.voxel_size = cfg.MODEL.VOXEL_HEAD.VOXEL_SIZE\n # fmt: on\n\n self.register_buffer(\"K\", get_blender_intrinsic_matrix())\n # backbone\n self.backbone, feat_dims = build_backbone(backbone)\n # voxel head\n cfg.MODEL.VOXEL_HEAD.COMPUTED_INPUT_CHANNELS = feat_dims[-1]\n self.voxel_head = VoxelHead(cfg)\n # mesh head\n cfg.MODEL.MESH_HEAD.COMPUTED_INPUT_CHANNELS = sum(feat_dims)\n self.mesh_head = MeshRefinementHead(cfg)\n\n def _get_projection_matrix(self, N, device):\n return self.K[None].repeat(N, 1, 1).to(device).detach()\n\n def _dummy_mesh(self, N, device):\n verts_batch = torch.randn(N, 4, 3, device=device)\n faces = [[0, 1, 2], [0, 2, 3], [0, 3, 1], [1, 3, 2]]\n faces = torch.tensor(faces, dtype=torch.int64)\n faces_batch = faces.view(1, 4, 3).expand(N, 4, 3).to(device)\n return Meshes(verts=verts_batch, faces=faces_batch)\n\n def cubify(self, voxel_scores):\n V = self.voxel_size\n N = voxel_scores.shape[0]\n voxel_probs = voxel_scores.sigmoid()\n active_voxels = voxel_probs > self.cubify_threshold\n voxels_per_mesh = (active_voxels.view(N, -1).sum(dim=1)).tolist()\n start = V // 4\n stop = start + V // 2\n for i in range(N):\n if voxels_per_mesh[i] == 0:\n voxel_probs[i, start:stop, start:stop, start:stop] = 1\n meshes = cubify(voxel_probs, self.cubify_threshold)\n\n meshes = self._add_dummies(meshes)\n meshes = voxel_to_world(meshes)\n return meshes\n\n def _add_dummies(self, meshes):\n N = len(meshes)\n dummies = self._dummy_mesh(N, meshes.device)\n verts_list = meshes.verts_list()\n faces_list = meshes.faces_list()\n for i in range(N):\n if faces_list[i].shape[0] == 0:\n # print('Adding dummmy mesh at index ', i)\n vv, ff = dummies.get_mesh(i)\n verts_list[i] = vv\n faces_list[i] = ff\n return Meshes(verts=verts_list, faces=faces_list)\n\n def forward(self, imgs, voxel_only=False):\n N = imgs.shape[0]\n device = imgs.device\n\n img_feats = self.backbone(imgs)\n voxel_scores = self.voxel_head(img_feats[-1])\n P = self._get_projection_matrix(N, device)\n\n if voxel_only:\n dummy_meshes = self._dummy_mesh(N, device)\n dummy_refined = self.mesh_head(img_feats, dummy_meshes, P)\n return voxel_scores, dummy_refined\n\n cubified_meshes = self.cubify(voxel_scores)\n refined_meshes = self.mesh_head(img_feats, cubified_meshes, P)\n return voxel_scores, refined_meshes\n\n\n@MESH_ARCH_REGISTRY.register()\nclass SphereInitHead(nn.Module):\n def __init__(self, cfg):\n super(SphereInitHead, self).__init__()\n\n # fmt: off\n backbone = cfg.MODEL.BACKBONE\n self.ico_sphere_level = cfg.MODEL.MESH_HEAD.ICO_SPHERE_LEVEL\n # fmt: on\n\n self.register_buffer(\"K\", get_blender_intrinsic_matrix())\n # backbone\n self.backbone, feat_dims = build_backbone(backbone)\n # mesh head\n cfg.MODEL.MESH_HEAD.COMPUTED_INPUT_CHANNELS = sum(feat_dims)\n self.mesh_head = MeshRefinementHead(cfg)\n\n def _get_projection_matrix(self, N, device):\n return self.K[None].repeat(N, 1, 1).to(device).detach()\n\n def forward(self, imgs):\n N = imgs.shape[0]\n device = imgs.device\n\n img_feats = self.backbone(imgs)\n P = self._get_projection_matrix(N, device)\n\n init_meshes = ico_sphere(self.ico_sphere_level, device).extend(N)\n refined_meshes = self.mesh_head(img_feats, init_meshes, P)\n return None, refined_meshes\n\n\n@MESH_ARCH_REGISTRY.register()\nclass Pixel2MeshHead(nn.Module):\n def __init__(self, cfg):\n super(Pixel2MeshHead, self).__init__()\n\n # fmt: off\n backbone = cfg.MODEL.BACKBONE\n self.ico_sphere_level = cfg.MODEL.MESH_HEAD.ICO_SPHERE_LEVEL\n # fmt: on\n\n self.register_buffer(\"K\", get_blender_intrinsic_matrix())\n # backbone\n self.backbone, feat_dims = build_backbone(backbone)\n # mesh head\n cfg.MODEL.MESH_HEAD.COMPUTED_INPUT_CHANNELS = sum(feat_dims)\n self.mesh_head = MeshRefinementHead(cfg)\n\n def _get_projection_matrix(self, N, device):\n return self.K[None].repeat(N, 1, 1).to(device).detach()\n\n def forward(self, imgs):\n N = imgs.shape[0]\n device = imgs.device\n\n img_feats = self.backbone(imgs)\n P = self._get_projection_matrix(N, device)\n\n init_meshes = ico_sphere(self.ico_sphere_level, device).extend(N)\n refined_meshes = self.mesh_head(img_feats, init_meshes, P, subdivide=True)\n return None, refined_meshes\n\n\ndef build_model(cfg):\n name = cfg.MODEL.MESH_HEAD.NAME\n return MESH_ARCH_REGISTRY.get(name)(cfg)\n",
"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport torch\n\n\ndef read_binvox_coords(f, integer_division=True, dtype=torch.float32):\n \"\"\"\n Read a binvox file and return the indices of all nonzero voxels.\n\n This matches the behavior of binvox_rw.read_as_coord_array\n (https://github.com/dimatura/binvox-rw-py/blob/public/binvox_rw.py#L153)\n but this implementation uses torch rather than numpy, and is more efficient\n due to improved vectorization.\n\n I think that binvox_rw.read_as_coord_array actually has a bug; when converting\n linear indices into three-dimensional indices, they use floating-point\n division instead of integer division. We can reproduce their incorrect\n implementation by passing integer_division=False.\n\n Args:\n f (str): A file pointer to the binvox file to read\n integer_division (bool): If False, then match the buggy implementation from binvox_rw\n dtype: Datatype of the output tensor. Use float64 to match binvox_rw\n\n Returns:\n coords (tensor): A tensor of shape (N, 3) where N is the number of nonzero voxels,\n and coords[i] = (x, y, z) gives the index of the ith nonzero voxel. If the\n voxel grid has shape (V, V, V) then we have 0 <= x, y, z < V.\n \"\"\"\n size, translation, scale = _read_binvox_header(f)\n storage = torch.ByteStorage.from_buffer(f.read())\n data = torch.tensor([], dtype=torch.uint8)\n data.set_(source=storage)\n vals, counts = data[::2], data[1::2]\n idxs = _compute_idxs_v2(vals, counts)\n if not integer_division:\n idxs = idxs.to(dtype)\n x_idxs = idxs / (size * size)\n zy_idxs = idxs % (size * size)\n z_idxs = zy_idxs / size\n y_idxs = zy_idxs % size\n coords = torch.stack([x_idxs, y_idxs, z_idxs], dim=1)\n return coords.to(dtype)\n\n\ndef _compute_idxs_v1(vals, counts):\n \"\"\" Naive version of index computation with loops \"\"\"\n idxs = []\n cur = 0\n for i in range(vals.shape[0]):\n val, count = vals[i].item(), counts[i].item()\n if val == 1:\n idxs.append(torch.arange(cur, cur + count))\n cur += count\n idxs = torch.cat(idxs, dim=0)\n return idxs\n\n\ndef _compute_idxs_v2(vals, counts):\n \"\"\" Fast vectorized version of index computation \"\"\"\n # Consider an example where:\n # vals = [0, 1, 0, 1, 1]\n # counts = [2, 3, 3, 2, 1]\n #\n # These values of counts and vals mean that the dense binary grid is:\n # [0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1]\n #\n # So the nonzero indices we want to return are:\n # [2, 3, 4, 8, 9, 10]\n\n # After the cumsum we will have:\n # end_idxs = [2, 5, 8, 10, 11]\n end_idxs = counts.cumsum(dim=0)\n\n # After masking and computing start_idx we have:\n # end_idxs = [5, 10, 11]\n # counts = [3, 2, 1]\n # start_idxs = [2, 8, 10]\n mask = vals == 1\n end_idxs = end_idxs[mask]\n counts = counts[mask].to(end_idxs)\n start_idxs = end_idxs - counts\n\n # We initialize delta as:\n # [2, 1, 1, 1, 1, 1]\n delta = torch.ones(counts.sum().item(), dtype=torch.int64)\n delta[0] = start_idxs[0]\n\n # We compute pos = [3, 5], val = [3, 0]; then delta is\n # [2, 1, 1, 4, 1, 1]\n pos = counts.cumsum(dim=0)[:-1]\n val = start_idxs[1:] - end_idxs[:-1]\n delta[pos] += val\n\n # A final cumsum gives the idx we want: [2, 3, 4, 8, 9, 10]\n idxs = delta.cumsum(dim=0)\n return idxs\n\n\ndef _read_binvox_header(f):\n # First line of the header should be \"#binvox 1\"\n line = f.readline().strip()\n if line != b\"#binvox 1\":\n raise ValueError(\"Invalid header (line 1)\")\n\n # Second line of the header should be \"dim [int] [int] [int]\"\n # and all three int should be the same\n line = f.readline().strip()\n if not line.startswith(b\"dim \"):\n raise ValueError(\"Invalid header (line 2)\")\n dims = line.split(b\" \")\n try:\n dims = [int(d) for d in dims[1:]]\n except ValueError:\n raise ValueError(\"Invalid header (line 2)\")\n if len(dims) != 3 or dims[0] != dims[1] or dims[0] != dims[2]:\n raise ValueError(\"Invalid header (line 2)\")\n size = dims[0]\n\n # Third line of the header should be \"translate [float] [float] [float]\"\n line = f.readline().strip()\n if not line.startswith(b\"translate \"):\n raise ValueError(\"Invalid header (line 3)\")\n translation = line.split(b\" \")\n if len(translation) != 4:\n raise ValueError(\"Invalid header (line 3)\")\n try:\n translation = tuple(float(t) for t in translation[1:])\n except ValueError:\n raise ValueError(\"Invalid header (line 3)\")\n\n # Fourth line of the header should be \"scale [float]\"\n line = f.readline().strip()\n if not line.startswith(b\"scale \"):\n raise ValueError(\"Invalid header (line 4)\")\n line = line.split(b\" \")\n if not len(line) == 2:\n raise ValueError(\"Invalid header (line 4)\")\n scale = float(line[1])\n\n # Fifth line of the header should be \"data\"\n line = f.readline().strip()\n if not line == b\"data\":\n raise ValueError(\"Invalid header (line 5)\")\n\n return size, translation, scale\n"
] |
[
[
"torch.randn",
"torch.tensor"
],
[
"torch.stack",
"torch.cat",
"torch.arange",
"torch.tensor"
]
] |
joseppinilla/networkx
|
[
"c034a899070774f70119c0d73207411db7db90b6"
] |
[
"networkx/algorithms/similarity.py"
] |
[
"\"\"\" Functions measuring similarity using graph edit distance.\n\nThe graph edit distance is the number of edge/node changes needed\nto make two graphs isomorphic.\n\nThe default algorithm/implementation is sub-optimal for some graphs.\nThe problem of finding the exact Graph Edit Distance (GED) is NP-hard\nso it is often slow. If the simple interface `graph_edit_distance`\ntakes too long for your graph, try `optimize_graph_edit_distance`\nand/or `optimize_edit_paths`.\n\nAt the same time, I encourage capable people to investigate\nalternative GED algorithms, in order to improve the choices available.\n\"\"\"\n\nfrom functools import reduce\nfrom itertools import product\nimport math\nfrom operator import mul\nimport time\nimport warnings\nimport networkx as nx\n\n__all__ = [\n \"graph_edit_distance\",\n \"optimal_edit_paths\",\n \"optimize_graph_edit_distance\",\n \"optimize_edit_paths\",\n \"simrank_similarity\",\n \"simrank_similarity_numpy\",\n \"panther_similarity\",\n \"generate_random_paths\",\n]\n\n\ndef debug_print(*args, **kwargs):\n print(*args, **kwargs)\n\n\ndef graph_edit_distance(\n G1,\n G2,\n node_match=None,\n edge_match=None,\n node_subst_cost=None,\n node_del_cost=None,\n node_ins_cost=None,\n edge_subst_cost=None,\n edge_del_cost=None,\n edge_ins_cost=None,\n roots=None,\n upper_bound=None,\n timeout=None,\n):\n \"\"\"Returns GED (graph edit distance) between graphs G1 and G2.\n\n Graph edit distance is a graph similarity measure analogous to\n Levenshtein distance for strings. It is defined as minimum cost\n of edit path (sequence of node and edge edit operations)\n transforming graph G1 to graph isomorphic to G2.\n\n Parameters\n ----------\n G1, G2: graphs\n The two graphs G1 and G2 must be of the same type.\n\n node_match : callable\n A function that returns True if node n1 in G1 and n2 in G2\n should be considered equal during matching.\n\n The function will be called like\n\n node_match(G1.nodes[n1], G2.nodes[n2]).\n\n That is, the function will receive the node attribute\n dictionaries for n1 and n2 as inputs.\n\n Ignored if node_subst_cost is specified. If neither\n node_match nor node_subst_cost are specified then node\n attributes are not considered.\n\n edge_match : callable\n A function that returns True if the edge attribute dictionaries\n for the pair of nodes (u1, v1) in G1 and (u2, v2) in G2 should\n be considered equal during matching.\n\n The function will be called like\n\n edge_match(G1[u1][v1], G2[u2][v2]).\n\n That is, the function will receive the edge attribute\n dictionaries of the edges under consideration.\n\n Ignored if edge_subst_cost is specified. If neither\n edge_match nor edge_subst_cost are specified then edge\n attributes are not considered.\n\n node_subst_cost, node_del_cost, node_ins_cost : callable\n Functions that return the costs of node substitution, node\n deletion, and node insertion, respectively.\n\n The functions will be called like\n\n node_subst_cost(G1.nodes[n1], G2.nodes[n2]),\n node_del_cost(G1.nodes[n1]),\n node_ins_cost(G2.nodes[n2]).\n\n That is, the functions will receive the node attribute\n dictionaries as inputs. The functions are expected to return\n positive numeric values.\n\n Function node_subst_cost overrides node_match if specified.\n If neither node_match nor node_subst_cost are specified then\n default node substitution cost of 0 is used (node attributes\n are not considered during matching).\n\n If node_del_cost is not specified then default node deletion\n cost of 1 is used. If node_ins_cost is not specified then\n default node insertion cost of 1 is used.\n\n edge_subst_cost, edge_del_cost, edge_ins_cost : callable\n Functions that return the costs of edge substitution, edge\n deletion, and edge insertion, respectively.\n\n The functions will be called like\n\n edge_subst_cost(G1[u1][v1], G2[u2][v2]),\n edge_del_cost(G1[u1][v1]),\n edge_ins_cost(G2[u2][v2]).\n\n That is, the functions will receive the edge attribute\n dictionaries as inputs. The functions are expected to return\n positive numeric values.\n\n Function edge_subst_cost overrides edge_match if specified.\n If neither edge_match nor edge_subst_cost are specified then\n default edge substitution cost of 0 is used (edge attributes\n are not considered during matching).\n\n If edge_del_cost is not specified then default edge deletion\n cost of 1 is used. If edge_ins_cost is not specified then\n default edge insertion cost of 1 is used.\n\n roots : 2-tuple\n Tuple where first element is a node in G1 and the second\n is a node in G2.\n These nodes are forced to be matched in the comparison to\n allow comparison between rooted graphs.\n\n upper_bound : numeric\n Maximum edit distance to consider. Return None if no edit\n distance under or equal to upper_bound exists.\n\n timeout : numeric\n Maximum number of seconds to execute.\n After timeout is met, the current best GED is returned.\n\n Examples\n --------\n >>> G1 = nx.cycle_graph(6)\n >>> G2 = nx.wheel_graph(7)\n >>> nx.graph_edit_distance(G1, G2)\n 7.0\n\n >>> G1 = nx.star_graph(5)\n >>> G2 = nx.star_graph(5)\n >>> nx.graph_edit_distance(G1, G2, roots=(0, 0))\n 0.0\n >>> nx.graph_edit_distance(G1, G2, roots=(1, 0))\n 8.0\n\n See Also\n --------\n optimal_edit_paths, optimize_graph_edit_distance,\n\n is_isomorphic (test for graph edit distance of 0)\n\n References\n ----------\n .. [1] Zeina Abu-Aisheh, Romain Raveaux, Jean-Yves Ramel, Patrick\n Martineau. An Exact Graph Edit Distance Algorithm for Solving\n Pattern Recognition Problems. 4th International Conference on\n Pattern Recognition Applications and Methods 2015, Jan 2015,\n Lisbon, Portugal. 2015,\n <10.5220/0005209202710278>. <hal-01168816>\n https://hal.archives-ouvertes.fr/hal-01168816\n\n \"\"\"\n bestcost = None\n for vertex_path, edge_path, cost in optimize_edit_paths(\n G1,\n G2,\n node_match,\n edge_match,\n node_subst_cost,\n node_del_cost,\n node_ins_cost,\n edge_subst_cost,\n edge_del_cost,\n edge_ins_cost,\n upper_bound,\n True,\n roots,\n timeout,\n ):\n # assert bestcost is None or cost < bestcost\n bestcost = cost\n return bestcost\n\n\ndef optimal_edit_paths(\n G1,\n G2,\n node_match=None,\n edge_match=None,\n node_subst_cost=None,\n node_del_cost=None,\n node_ins_cost=None,\n edge_subst_cost=None,\n edge_del_cost=None,\n edge_ins_cost=None,\n upper_bound=None,\n):\n \"\"\"Returns all minimum-cost edit paths transforming G1 to G2.\n\n Graph edit path is a sequence of node and edge edit operations\n transforming graph G1 to graph isomorphic to G2. Edit operations\n include substitutions, deletions, and insertions.\n\n Parameters\n ----------\n G1, G2: graphs\n The two graphs G1 and G2 must be of the same type.\n\n node_match : callable\n A function that returns True if node n1 in G1 and n2 in G2\n should be considered equal during matching.\n\n The function will be called like\n\n node_match(G1.nodes[n1], G2.nodes[n2]).\n\n That is, the function will receive the node attribute\n dictionaries for n1 and n2 as inputs.\n\n Ignored if node_subst_cost is specified. If neither\n node_match nor node_subst_cost are specified then node\n attributes are not considered.\n\n edge_match : callable\n A function that returns True if the edge attribute dictionaries\n for the pair of nodes (u1, v1) in G1 and (u2, v2) in G2 should\n be considered equal during matching.\n\n The function will be called like\n\n edge_match(G1[u1][v1], G2[u2][v2]).\n\n That is, the function will receive the edge attribute\n dictionaries of the edges under consideration.\n\n Ignored if edge_subst_cost is specified. If neither\n edge_match nor edge_subst_cost are specified then edge\n attributes are not considered.\n\n node_subst_cost, node_del_cost, node_ins_cost : callable\n Functions that return the costs of node substitution, node\n deletion, and node insertion, respectively.\n\n The functions will be called like\n\n node_subst_cost(G1.nodes[n1], G2.nodes[n2]),\n node_del_cost(G1.nodes[n1]),\n node_ins_cost(G2.nodes[n2]).\n\n That is, the functions will receive the node attribute\n dictionaries as inputs. The functions are expected to return\n positive numeric values.\n\n Function node_subst_cost overrides node_match if specified.\n If neither node_match nor node_subst_cost are specified then\n default node substitution cost of 0 is used (node attributes\n are not considered during matching).\n\n If node_del_cost is not specified then default node deletion\n cost of 1 is used. If node_ins_cost is not specified then\n default node insertion cost of 1 is used.\n\n edge_subst_cost, edge_del_cost, edge_ins_cost : callable\n Functions that return the costs of edge substitution, edge\n deletion, and edge insertion, respectively.\n\n The functions will be called like\n\n edge_subst_cost(G1[u1][v1], G2[u2][v2]),\n edge_del_cost(G1[u1][v1]),\n edge_ins_cost(G2[u2][v2]).\n\n That is, the functions will receive the edge attribute\n dictionaries as inputs. The functions are expected to return\n positive numeric values.\n\n Function edge_subst_cost overrides edge_match if specified.\n If neither edge_match nor edge_subst_cost are specified then\n default edge substitution cost of 0 is used (edge attributes\n are not considered during matching).\n\n If edge_del_cost is not specified then default edge deletion\n cost of 1 is used. If edge_ins_cost is not specified then\n default edge insertion cost of 1 is used.\n\n upper_bound : numeric\n Maximum edit distance to consider.\n\n Returns\n -------\n edit_paths : list of tuples (node_edit_path, edge_edit_path)\n node_edit_path : list of tuples (u, v)\n edge_edit_path : list of tuples ((u1, v1), (u2, v2))\n\n cost : numeric\n Optimal edit path cost (graph edit distance).\n\n Examples\n --------\n >>> G1 = nx.cycle_graph(4)\n >>> G2 = nx.wheel_graph(5)\n >>> paths, cost = nx.optimal_edit_paths(G1, G2)\n >>> len(paths)\n 40\n >>> cost\n 5.0\n\n See Also\n --------\n graph_edit_distance, optimize_edit_paths\n\n References\n ----------\n .. [1] Zeina Abu-Aisheh, Romain Raveaux, Jean-Yves Ramel, Patrick\n Martineau. An Exact Graph Edit Distance Algorithm for Solving\n Pattern Recognition Problems. 4th International Conference on\n Pattern Recognition Applications and Methods 2015, Jan 2015,\n Lisbon, Portugal. 2015,\n <10.5220/0005209202710278>. <hal-01168816>\n https://hal.archives-ouvertes.fr/hal-01168816\n\n \"\"\"\n paths = list()\n bestcost = None\n for vertex_path, edge_path, cost in optimize_edit_paths(\n G1,\n G2,\n node_match,\n edge_match,\n node_subst_cost,\n node_del_cost,\n node_ins_cost,\n edge_subst_cost,\n edge_del_cost,\n edge_ins_cost,\n upper_bound,\n False,\n ):\n # assert bestcost is None or cost <= bestcost\n if bestcost is not None and cost < bestcost:\n paths = list()\n paths.append((vertex_path, edge_path))\n bestcost = cost\n return paths, bestcost\n\n\ndef optimize_graph_edit_distance(\n G1,\n G2,\n node_match=None,\n edge_match=None,\n node_subst_cost=None,\n node_del_cost=None,\n node_ins_cost=None,\n edge_subst_cost=None,\n edge_del_cost=None,\n edge_ins_cost=None,\n upper_bound=None,\n):\n \"\"\"Returns consecutive approximations of GED (graph edit distance)\n between graphs G1 and G2.\n\n Graph edit distance is a graph similarity measure analogous to\n Levenshtein distance for strings. It is defined as minimum cost\n of edit path (sequence of node and edge edit operations)\n transforming graph G1 to graph isomorphic to G2.\n\n Parameters\n ----------\n G1, G2: graphs\n The two graphs G1 and G2 must be of the same type.\n\n node_match : callable\n A function that returns True if node n1 in G1 and n2 in G2\n should be considered equal during matching.\n\n The function will be called like\n\n node_match(G1.nodes[n1], G2.nodes[n2]).\n\n That is, the function will receive the node attribute\n dictionaries for n1 and n2 as inputs.\n\n Ignored if node_subst_cost is specified. If neither\n node_match nor node_subst_cost are specified then node\n attributes are not considered.\n\n edge_match : callable\n A function that returns True if the edge attribute dictionaries\n for the pair of nodes (u1, v1) in G1 and (u2, v2) in G2 should\n be considered equal during matching.\n\n The function will be called like\n\n edge_match(G1[u1][v1], G2[u2][v2]).\n\n That is, the function will receive the edge attribute\n dictionaries of the edges under consideration.\n\n Ignored if edge_subst_cost is specified. If neither\n edge_match nor edge_subst_cost are specified then edge\n attributes are not considered.\n\n node_subst_cost, node_del_cost, node_ins_cost : callable\n Functions that return the costs of node substitution, node\n deletion, and node insertion, respectively.\n\n The functions will be called like\n\n node_subst_cost(G1.nodes[n1], G2.nodes[n2]),\n node_del_cost(G1.nodes[n1]),\n node_ins_cost(G2.nodes[n2]).\n\n That is, the functions will receive the node attribute\n dictionaries as inputs. The functions are expected to return\n positive numeric values.\n\n Function node_subst_cost overrides node_match if specified.\n If neither node_match nor node_subst_cost are specified then\n default node substitution cost of 0 is used (node attributes\n are not considered during matching).\n\n If node_del_cost is not specified then default node deletion\n cost of 1 is used. If node_ins_cost is not specified then\n default node insertion cost of 1 is used.\n\n edge_subst_cost, edge_del_cost, edge_ins_cost : callable\n Functions that return the costs of edge substitution, edge\n deletion, and edge insertion, respectively.\n\n The functions will be called like\n\n edge_subst_cost(G1[u1][v1], G2[u2][v2]),\n edge_del_cost(G1[u1][v1]),\n edge_ins_cost(G2[u2][v2]).\n\n That is, the functions will receive the edge attribute\n dictionaries as inputs. The functions are expected to return\n positive numeric values.\n\n Function edge_subst_cost overrides edge_match if specified.\n If neither edge_match nor edge_subst_cost are specified then\n default edge substitution cost of 0 is used (edge attributes\n are not considered during matching).\n\n If edge_del_cost is not specified then default edge deletion\n cost of 1 is used. If edge_ins_cost is not specified then\n default edge insertion cost of 1 is used.\n\n upper_bound : numeric\n Maximum edit distance to consider.\n\n Returns\n -------\n Generator of consecutive approximations of graph edit distance.\n\n Examples\n --------\n >>> G1 = nx.cycle_graph(6)\n >>> G2 = nx.wheel_graph(7)\n >>> for v in nx.optimize_graph_edit_distance(G1, G2):\n ... minv = v\n >>> minv\n 7.0\n\n See Also\n --------\n graph_edit_distance, optimize_edit_paths\n\n References\n ----------\n .. [1] Zeina Abu-Aisheh, Romain Raveaux, Jean-Yves Ramel, Patrick\n Martineau. An Exact Graph Edit Distance Algorithm for Solving\n Pattern Recognition Problems. 4th International Conference on\n Pattern Recognition Applications and Methods 2015, Jan 2015,\n Lisbon, Portugal. 2015,\n <10.5220/0005209202710278>. <hal-01168816>\n https://hal.archives-ouvertes.fr/hal-01168816\n \"\"\"\n for vertex_path, edge_path, cost in optimize_edit_paths(\n G1,\n G2,\n node_match,\n edge_match,\n node_subst_cost,\n node_del_cost,\n node_ins_cost,\n edge_subst_cost,\n edge_del_cost,\n edge_ins_cost,\n upper_bound,\n True,\n ):\n yield cost\n\n\ndef optimize_edit_paths(\n G1,\n G2,\n node_match=None,\n edge_match=None,\n node_subst_cost=None,\n node_del_cost=None,\n node_ins_cost=None,\n edge_subst_cost=None,\n edge_del_cost=None,\n edge_ins_cost=None,\n upper_bound=None,\n strictly_decreasing=True,\n roots=None,\n timeout=None,\n):\n \"\"\"GED (graph edit distance) calculation: advanced interface.\n\n Graph edit path is a sequence of node and edge edit operations\n transforming graph G1 to graph isomorphic to G2. Edit operations\n include substitutions, deletions, and insertions.\n\n Graph edit distance is defined as minimum cost of edit path.\n\n Parameters\n ----------\n G1, G2: graphs\n The two graphs G1 and G2 must be of the same type.\n\n node_match : callable\n A function that returns True if node n1 in G1 and n2 in G2\n should be considered equal during matching.\n\n The function will be called like\n\n node_match(G1.nodes[n1], G2.nodes[n2]).\n\n That is, the function will receive the node attribute\n dictionaries for n1 and n2 as inputs.\n\n Ignored if node_subst_cost is specified. If neither\n node_match nor node_subst_cost are specified then node\n attributes are not considered.\n\n edge_match : callable\n A function that returns True if the edge attribute dictionaries\n for the pair of nodes (u1, v1) in G1 and (u2, v2) in G2 should\n be considered equal during matching.\n\n The function will be called like\n\n edge_match(G1[u1][v1], G2[u2][v2]).\n\n That is, the function will receive the edge attribute\n dictionaries of the edges under consideration.\n\n Ignored if edge_subst_cost is specified. If neither\n edge_match nor edge_subst_cost are specified then edge\n attributes are not considered.\n\n node_subst_cost, node_del_cost, node_ins_cost : callable\n Functions that return the costs of node substitution, node\n deletion, and node insertion, respectively.\n\n The functions will be called like\n\n node_subst_cost(G1.nodes[n1], G2.nodes[n2]),\n node_del_cost(G1.nodes[n1]),\n node_ins_cost(G2.nodes[n2]).\n\n That is, the functions will receive the node attribute\n dictionaries as inputs. The functions are expected to return\n positive numeric values.\n\n Function node_subst_cost overrides node_match if specified.\n If neither node_match nor node_subst_cost are specified then\n default node substitution cost of 0 is used (node attributes\n are not considered during matching).\n\n If node_del_cost is not specified then default node deletion\n cost of 1 is used. If node_ins_cost is not specified then\n default node insertion cost of 1 is used.\n\n edge_subst_cost, edge_del_cost, edge_ins_cost : callable\n Functions that return the costs of edge substitution, edge\n deletion, and edge insertion, respectively.\n\n The functions will be called like\n\n edge_subst_cost(G1[u1][v1], G2[u2][v2]),\n edge_del_cost(G1[u1][v1]),\n edge_ins_cost(G2[u2][v2]).\n\n That is, the functions will receive the edge attribute\n dictionaries as inputs. The functions are expected to return\n positive numeric values.\n\n Function edge_subst_cost overrides edge_match if specified.\n If neither edge_match nor edge_subst_cost are specified then\n default edge substitution cost of 0 is used (edge attributes\n are not considered during matching).\n\n If edge_del_cost is not specified then default edge deletion\n cost of 1 is used. If edge_ins_cost is not specified then\n default edge insertion cost of 1 is used.\n\n upper_bound : numeric\n Maximum edit distance to consider.\n\n strictly_decreasing : bool\n If True, return consecutive approximations of strictly\n decreasing cost. Otherwise, return all edit paths of cost\n less than or equal to the previous minimum cost.\n\n roots : 2-tuple\n Tuple where first element is a node in G1 and the second\n is a node in G2.\n These nodes are forced to be matched in the comparison to\n allow comparison between rooted graphs.\n\n timeout : numeric\n Maximum number of seconds to execute.\n After timeout is met, the current best GED is returned.\n\n Returns\n -------\n Generator of tuples (node_edit_path, edge_edit_path, cost)\n node_edit_path : list of tuples (u, v)\n edge_edit_path : list of tuples ((u1, v1), (u2, v2))\n cost : numeric\n\n See Also\n --------\n graph_edit_distance, optimize_graph_edit_distance, optimal_edit_paths\n\n References\n ----------\n .. [1] Zeina Abu-Aisheh, Romain Raveaux, Jean-Yves Ramel, Patrick\n Martineau. An Exact Graph Edit Distance Algorithm for Solving\n Pattern Recognition Problems. 4th International Conference on\n Pattern Recognition Applications and Methods 2015, Jan 2015,\n Lisbon, Portugal. 2015,\n <10.5220/0005209202710278>. <hal-01168816>\n https://hal.archives-ouvertes.fr/hal-01168816\n\n \"\"\"\n # TODO: support DiGraph\n\n import numpy as np\n from scipy.optimize import linear_sum_assignment\n\n class CostMatrix:\n def __init__(self, C, lsa_row_ind, lsa_col_ind, ls):\n # assert C.shape[0] == len(lsa_row_ind)\n # assert C.shape[1] == len(lsa_col_ind)\n # assert len(lsa_row_ind) == len(lsa_col_ind)\n # assert set(lsa_row_ind) == set(range(len(lsa_row_ind)))\n # assert set(lsa_col_ind) == set(range(len(lsa_col_ind)))\n # assert ls == C[lsa_row_ind, lsa_col_ind].sum()\n self.C = C\n self.lsa_row_ind = lsa_row_ind\n self.lsa_col_ind = lsa_col_ind\n self.ls = ls\n\n def make_CostMatrix(C, m, n):\n # assert(C.shape == (m + n, m + n))\n lsa_row_ind, lsa_col_ind = linear_sum_assignment(C)\n\n # Fixup dummy assignments:\n # each substitution i<->j should have dummy assignment m+j<->n+i\n # NOTE: fast reduce of Cv relies on it\n # assert len(lsa_row_ind) == len(lsa_col_ind)\n indexes = zip(range(len(lsa_row_ind)), lsa_row_ind, lsa_col_ind)\n subst_ind = list(k for k, i, j in indexes if i < m and j < n)\n indexes = zip(range(len(lsa_row_ind)), lsa_row_ind, lsa_col_ind)\n dummy_ind = list(k for k, i, j in indexes if i >= m and j >= n)\n # assert len(subst_ind) == len(dummy_ind)\n lsa_row_ind[dummy_ind] = lsa_col_ind[subst_ind] + m\n lsa_col_ind[dummy_ind] = lsa_row_ind[subst_ind] + n\n\n return CostMatrix(\n C, lsa_row_ind, lsa_col_ind, C[lsa_row_ind, lsa_col_ind].sum()\n )\n\n def extract_C(C, i, j, m, n):\n # assert(C.shape == (m + n, m + n))\n row_ind = [k in i or k - m in j for k in range(m + n)]\n col_ind = [k in j or k - n in i for k in range(m + n)]\n return C[row_ind, :][:, col_ind]\n\n def reduce_C(C, i, j, m, n):\n # assert(C.shape == (m + n, m + n))\n row_ind = [k not in i and k - m not in j for k in range(m + n)]\n col_ind = [k not in j and k - n not in i for k in range(m + n)]\n return C[row_ind, :][:, col_ind]\n\n def reduce_ind(ind, i):\n # assert set(ind) == set(range(len(ind)))\n rind = ind[[k not in i for k in ind]]\n for k in set(i):\n rind[rind >= k] -= 1\n return rind\n\n def match_edges(u, v, pending_g, pending_h, Ce, matched_uv=[]):\n \"\"\"\n Parameters:\n u, v: matched vertices, u=None or v=None for\n deletion/insertion\n pending_g, pending_h: lists of edges not yet mapped\n Ce: CostMatrix of pending edge mappings\n matched_uv: partial vertex edit path\n list of tuples (u, v) of previously matched vertex\n mappings u<->v, u=None or v=None for\n deletion/insertion\n\n Returns:\n list of (i, j): indices of edge mappings g<->h\n localCe: local CostMatrix of edge mappings\n (basically submatrix of Ce at cross of rows i, cols j)\n \"\"\"\n M = len(pending_g)\n N = len(pending_h)\n # assert Ce.C.shape == (M + N, M + N)\n\n g_ind = [\n i\n for i in range(M)\n if pending_g[i][:2] == (u, u)\n or any(pending_g[i][:2] in ((p, u), (u, p)) for p, q in matched_uv)\n ]\n h_ind = [\n j\n for j in range(N)\n if pending_h[j][:2] == (v, v)\n or any(pending_h[j][:2] in ((q, v), (v, q)) for p, q in matched_uv)\n ]\n m = len(g_ind)\n n = len(h_ind)\n\n if m or n:\n C = extract_C(Ce.C, g_ind, h_ind, M, N)\n # assert C.shape == (m + n, m + n)\n\n # Forbid structurally invalid matches\n # NOTE: inf remembered from Ce construction\n for k, i in zip(range(m), g_ind):\n g = pending_g[i][:2]\n for l, j in zip(range(n), h_ind):\n h = pending_h[j][:2]\n if nx.is_directed(G1) or nx.is_directed(G2):\n if any(\n g == (p, u) and h == (q, v) or g == (u, p) and h == (v, q)\n for p, q in matched_uv\n ):\n continue\n else:\n if any(\n g in ((p, u), (u, p)) and h in ((q, v), (v, q))\n for p, q in matched_uv\n ):\n continue\n if g == (u, u):\n continue\n if h == (v, v):\n continue\n C[k, l] = inf\n\n localCe = make_CostMatrix(C, m, n)\n ij = list(\n (\n g_ind[k] if k < m else M + h_ind[l],\n h_ind[l] if l < n else N + g_ind[k],\n )\n for k, l in zip(localCe.lsa_row_ind, localCe.lsa_col_ind)\n if k < m or l < n\n )\n\n else:\n ij = []\n localCe = CostMatrix(np.empty((0, 0)), [], [], 0)\n\n return ij, localCe\n\n def reduce_Ce(Ce, ij, m, n):\n if len(ij):\n i, j = zip(*ij)\n m_i = m - sum(1 for t in i if t < m)\n n_j = n - sum(1 for t in j if t < n)\n return make_CostMatrix(reduce_C(Ce.C, i, j, m, n), m_i, n_j)\n else:\n return Ce\n\n def get_edit_ops(\n matched_uv, pending_u, pending_v, Cv, pending_g, pending_h, Ce, matched_cost\n ):\n \"\"\"\n Parameters:\n matched_uv: partial vertex edit path\n list of tuples (u, v) of vertex mappings u<->v,\n u=None or v=None for deletion/insertion\n pending_u, pending_v: lists of vertices not yet mapped\n Cv: CostMatrix of pending vertex mappings\n pending_g, pending_h: lists of edges not yet mapped\n Ce: CostMatrix of pending edge mappings\n matched_cost: cost of partial edit path\n\n Returns:\n sequence of\n (i, j): indices of vertex mapping u<->v\n Cv_ij: reduced CostMatrix of pending vertex mappings\n (basically Cv with row i, col j removed)\n list of (x, y): indices of edge mappings g<->h\n Ce_xy: reduced CostMatrix of pending edge mappings\n (basically Ce with rows x, cols y removed)\n cost: total cost of edit operation\n NOTE: most promising ops first\n \"\"\"\n m = len(pending_u)\n n = len(pending_v)\n # assert Cv.C.shape == (m + n, m + n)\n\n # 1) a vertex mapping from optimal linear sum assignment\n i, j = min(\n (k, l) for k, l in zip(Cv.lsa_row_ind, Cv.lsa_col_ind) if k < m or l < n\n )\n xy, localCe = match_edges(\n pending_u[i] if i < m else None,\n pending_v[j] if j < n else None,\n pending_g,\n pending_h,\n Ce,\n matched_uv,\n )\n Ce_xy = reduce_Ce(Ce, xy, len(pending_g), len(pending_h))\n # assert Ce.ls <= localCe.ls + Ce_xy.ls\n if prune(matched_cost + Cv.ls + localCe.ls + Ce_xy.ls):\n pass\n else:\n # get reduced Cv efficiently\n Cv_ij = CostMatrix(\n reduce_C(Cv.C, (i,), (j,), m, n),\n reduce_ind(Cv.lsa_row_ind, (i, m + j)),\n reduce_ind(Cv.lsa_col_ind, (j, n + i)),\n Cv.ls - Cv.C[i, j],\n )\n yield (i, j), Cv_ij, xy, Ce_xy, Cv.C[i, j] + localCe.ls\n\n # 2) other candidates, sorted by lower-bound cost estimate\n other = list()\n fixed_i, fixed_j = i, j\n if m <= n:\n candidates = (\n (t, fixed_j)\n for t in range(m + n)\n if t != fixed_i and (t < m or t == m + fixed_j)\n )\n else:\n candidates = (\n (fixed_i, t)\n for t in range(m + n)\n if t != fixed_j and (t < n or t == n + fixed_i)\n )\n for i, j in candidates:\n if prune(matched_cost + Cv.C[i, j] + Ce.ls):\n continue\n Cv_ij = make_CostMatrix(\n reduce_C(Cv.C, (i,), (j,), m, n),\n m - 1 if i < m else m,\n n - 1 if j < n else n,\n )\n # assert Cv.ls <= Cv.C[i, j] + Cv_ij.ls\n if prune(matched_cost + Cv.C[i, j] + Cv_ij.ls + Ce.ls):\n continue\n xy, localCe = match_edges(\n pending_u[i] if i < m else None,\n pending_v[j] if j < n else None,\n pending_g,\n pending_h,\n Ce,\n matched_uv,\n )\n if prune(matched_cost + Cv.C[i, j] + Cv_ij.ls + localCe.ls):\n continue\n Ce_xy = reduce_Ce(Ce, xy, len(pending_g), len(pending_h))\n # assert Ce.ls <= localCe.ls + Ce_xy.ls\n if prune(matched_cost + Cv.C[i, j] + Cv_ij.ls + localCe.ls + Ce_xy.ls):\n continue\n other.append(((i, j), Cv_ij, xy, Ce_xy, Cv.C[i, j] + localCe.ls))\n\n yield from sorted(other, key=lambda t: t[4] + t[1].ls + t[3].ls)\n\n def get_edit_paths(\n matched_uv,\n pending_u,\n pending_v,\n Cv,\n matched_gh,\n pending_g,\n pending_h,\n Ce,\n matched_cost,\n ):\n \"\"\"\n Parameters:\n matched_uv: partial vertex edit path\n list of tuples (u, v) of vertex mappings u<->v,\n u=None or v=None for deletion/insertion\n pending_u, pending_v: lists of vertices not yet mapped\n Cv: CostMatrix of pending vertex mappings\n matched_gh: partial edge edit path\n list of tuples (g, h) of edge mappings g<->h,\n g=None or h=None for deletion/insertion\n pending_g, pending_h: lists of edges not yet mapped\n Ce: CostMatrix of pending edge mappings\n matched_cost: cost of partial edit path\n\n Returns:\n sequence of (vertex_path, edge_path, cost)\n vertex_path: complete vertex edit path\n list of tuples (u, v) of vertex mappings u<->v,\n u=None or v=None for deletion/insertion\n edge_path: complete edge edit path\n list of tuples (g, h) of edge mappings g<->h,\n g=None or h=None for deletion/insertion\n cost: total cost of edit path\n NOTE: path costs are non-increasing\n \"\"\"\n # debug_print('matched-uv:', matched_uv)\n # debug_print('matched-gh:', matched_gh)\n # debug_print('matched-cost:', matched_cost)\n # debug_print('pending-u:', pending_u)\n # debug_print('pending-v:', pending_v)\n # debug_print(Cv.C)\n # assert list(sorted(G1.nodes)) == list(sorted(list(u for u, v in matched_uv if u is not None) + pending_u))\n # assert list(sorted(G2.nodes)) == list(sorted(list(v for u, v in matched_uv if v is not None) + pending_v))\n # debug_print('pending-g:', pending_g)\n # debug_print('pending-h:', pending_h)\n # debug_print(Ce.C)\n # assert list(sorted(G1.edges)) == list(sorted(list(g for g, h in matched_gh if g is not None) + pending_g))\n # assert list(sorted(G2.edges)) == list(sorted(list(h for g, h in matched_gh if h is not None) + pending_h))\n # debug_print()\n\n if prune(matched_cost + Cv.ls + Ce.ls):\n return\n\n if not max(len(pending_u), len(pending_v)):\n # assert not len(pending_g)\n # assert not len(pending_h)\n # path completed!\n # assert matched_cost <= maxcost.value\n maxcost.value = min(maxcost.value, matched_cost)\n yield matched_uv, matched_gh, matched_cost\n\n else:\n edit_ops = get_edit_ops(\n matched_uv,\n pending_u,\n pending_v,\n Cv,\n pending_g,\n pending_h,\n Ce,\n matched_cost,\n )\n for ij, Cv_ij, xy, Ce_xy, edit_cost in edit_ops:\n i, j = ij\n # assert Cv.C[i, j] + sum(Ce.C[t] for t in xy) == edit_cost\n if prune(matched_cost + edit_cost + Cv_ij.ls + Ce_xy.ls):\n continue\n\n # dive deeper\n u = pending_u.pop(i) if i < len(pending_u) else None\n v = pending_v.pop(j) if j < len(pending_v) else None\n matched_uv.append((u, v))\n for x, y in xy:\n len_g = len(pending_g)\n len_h = len(pending_h)\n matched_gh.append(\n (\n pending_g[x] if x < len_g else None,\n pending_h[y] if y < len_h else None,\n )\n )\n sortedx = list(sorted(x for x, y in xy))\n sortedy = list(sorted(y for x, y in xy))\n G = list(\n (pending_g.pop(x) if x < len(pending_g) else None)\n for x in reversed(sortedx)\n )\n H = list(\n (pending_h.pop(y) if y < len(pending_h) else None)\n for y in reversed(sortedy)\n )\n\n yield from get_edit_paths(\n matched_uv,\n pending_u,\n pending_v,\n Cv_ij,\n matched_gh,\n pending_g,\n pending_h,\n Ce_xy,\n matched_cost + edit_cost,\n )\n\n # backtrack\n if u is not None:\n pending_u.insert(i, u)\n if v is not None:\n pending_v.insert(j, v)\n matched_uv.pop()\n for x, g in zip(sortedx, reversed(G)):\n if g is not None:\n pending_g.insert(x, g)\n for y, h in zip(sortedy, reversed(H)):\n if h is not None:\n pending_h.insert(y, h)\n for t in xy:\n matched_gh.pop()\n\n # Initialization\n\n pending_u = list(G1.nodes)\n pending_v = list(G2.nodes)\n\n initial_cost = 0\n if roots:\n root_u, root_v = roots\n if root_u not in pending_u or root_v not in pending_v:\n raise nx.NodeNotFound(\"Root node not in graph.\")\n\n # remove roots from pending\n pending_u.remove(root_u)\n pending_v.remove(root_v)\n\n # cost matrix of vertex mappings\n m = len(pending_u)\n n = len(pending_v)\n C = np.zeros((m + n, m + n))\n if node_subst_cost:\n C[0:m, 0:n] = np.array(\n [\n node_subst_cost(G1.nodes[u], G2.nodes[v])\n for u in pending_u\n for v in pending_v\n ]\n ).reshape(m, n)\n if roots:\n initial_cost = node_subst_cost(G1.nodes[root_u], G2.nodes[root_v])\n elif node_match:\n C[0:m, 0:n] = np.array(\n [\n 1 - int(node_match(G1.nodes[u], G2.nodes[v]))\n for u in pending_u\n for v in pending_v\n ]\n ).reshape(m, n)\n if roots:\n initial_cost = 1 - node_match(G1.nodes[root_u], G2.nodes[root_v])\n else:\n # all zeroes\n pass\n # assert not min(m, n) or C[0:m, 0:n].min() >= 0\n if node_del_cost:\n del_costs = [node_del_cost(G1.nodes[u]) for u in pending_u]\n else:\n del_costs = [1] * len(pending_u)\n # assert not m or min(del_costs) >= 0\n if node_ins_cost:\n ins_costs = [node_ins_cost(G2.nodes[v]) for v in pending_v]\n else:\n ins_costs = [1] * len(pending_v)\n # assert not n or min(ins_costs) >= 0\n inf = C[0:m, 0:n].sum() + sum(del_costs) + sum(ins_costs) + 1\n C[0:m, n : n + m] = np.array(\n [del_costs[i] if i == j else inf for i in range(m) for j in range(m)]\n ).reshape(m, m)\n C[m : m + n, 0:n] = np.array(\n [ins_costs[i] if i == j else inf for i in range(n) for j in range(n)]\n ).reshape(n, n)\n Cv = make_CostMatrix(C, m, n)\n # debug_print(f\"Cv: {m} x {n}\")\n # debug_print(Cv.C)\n\n pending_g = list(G1.edges)\n pending_h = list(G2.edges)\n\n # cost matrix of edge mappings\n m = len(pending_g)\n n = len(pending_h)\n C = np.zeros((m + n, m + n))\n if edge_subst_cost:\n C[0:m, 0:n] = np.array(\n [\n edge_subst_cost(G1.edges[g], G2.edges[h])\n for g in pending_g\n for h in pending_h\n ]\n ).reshape(m, n)\n elif edge_match:\n C[0:m, 0:n] = np.array(\n [\n 1 - int(edge_match(G1.edges[g], G2.edges[h]))\n for g in pending_g\n for h in pending_h\n ]\n ).reshape(m, n)\n else:\n # all zeroes\n pass\n # assert not min(m, n) or C[0:m, 0:n].min() >= 0\n if edge_del_cost:\n del_costs = [edge_del_cost(G1.edges[g]) for g in pending_g]\n else:\n del_costs = [1] * len(pending_g)\n # assert not m or min(del_costs) >= 0\n if edge_ins_cost:\n ins_costs = [edge_ins_cost(G2.edges[h]) for h in pending_h]\n else:\n ins_costs = [1] * len(pending_h)\n # assert not n or min(ins_costs) >= 0\n inf = C[0:m, 0:n].sum() + sum(del_costs) + sum(ins_costs) + 1\n C[0:m, n : n + m] = np.array(\n [del_costs[i] if i == j else inf for i in range(m) for j in range(m)]\n ).reshape(m, m)\n C[m : m + n, 0:n] = np.array(\n [ins_costs[i] if i == j else inf for i in range(n) for j in range(n)]\n ).reshape(n, n)\n Ce = make_CostMatrix(C, m, n)\n # debug_print(f'Ce: {m} x {n}')\n # debug_print(Ce.C)\n # debug_print()\n\n class MaxCost:\n def __init__(self):\n # initial upper-bound estimate\n # NOTE: should work for empty graph\n self.value = Cv.C.sum() + Ce.C.sum() + 1\n\n maxcost = MaxCost()\n\n if timeout is not None:\n if timeout <= 0:\n raise nx.NetworkXError(\"Timeout value must be greater than 0\")\n start = time.perf_counter()\n\n def prune(cost):\n if timeout is not None:\n if time.perf_counter() - start > timeout:\n return True\n if upper_bound is not None:\n if cost > upper_bound:\n return True\n if cost > maxcost.value:\n return True\n elif strictly_decreasing and cost >= maxcost.value:\n return True\n\n # Now go!\n\n done_uv = [] if roots is None else [roots]\n\n for vertex_path, edge_path, cost in get_edit_paths(\n done_uv, pending_u, pending_v, Cv, [], pending_g, pending_h, Ce, initial_cost\n ):\n # assert sorted(G1.nodes) == sorted(u for u, v in vertex_path if u is not None)\n # assert sorted(G2.nodes) == sorted(v for u, v in vertex_path if v is not None)\n # assert sorted(G1.edges) == sorted(g for g, h in edge_path if g is not None)\n # assert sorted(G2.edges) == sorted(h for g, h in edge_path if h is not None)\n # print(vertex_path, edge_path, cost, file = sys.stderr)\n # assert cost == maxcost.value\n yield list(vertex_path), list(edge_path), cost\n\n\ndef _is_close(d1, d2, atolerance=0, rtolerance=0):\n \"\"\"Determines whether two adjacency matrices are within\n a provided tolerance.\n\n Parameters\n ----------\n d1 : dict\n Adjacency dictionary\n\n d2 : dict\n Adjacency dictionary\n\n atolerance : float\n Some scalar tolerance value to determine closeness\n\n rtolerance : float\n A scalar tolerance value that will be some proportion\n of ``d2``'s value\n\n Returns\n -------\n closeness : bool\n If all of the nodes within ``d1`` and ``d2`` are within\n a predefined tolerance, they are considered \"close\" and\n this method will return True. Otherwise, this method will\n return False.\n\n \"\"\"\n # Pre-condition: d1 and d2 have the same keys at each level if they\n # are dictionaries.\n if not isinstance(d1, dict) and not isinstance(d2, dict):\n return abs(d1 - d2) <= atolerance + rtolerance * abs(d2)\n return all(all(_is_close(d1[u][v], d2[u][v]) for v in d1[u]) for u in d1)\n\n\ndef simrank_similarity(\n G,\n source=None,\n target=None,\n importance_factor=0.9,\n max_iterations=100,\n tolerance=1e-4,\n):\n \"\"\"Returns the SimRank similarity of nodes in the graph ``G``.\n\n SimRank is a similarity metric that says \"two objects are considered\n to be similar if they are referenced by similar objects.\" [1]_.\n\n The pseudo-code definition from the paper is::\n\n def simrank(G, u, v):\n in_neighbors_u = G.predecessors(u)\n in_neighbors_v = G.predecessors(v)\n scale = C / (len(in_neighbors_u) * len(in_neighbors_v))\n return scale * sum(simrank(G, w, x)\n for w, x in product(in_neighbors_u,\n in_neighbors_v))\n\n where ``G`` is the graph, ``u`` is the source, ``v`` is the target,\n and ``C`` is a float decay or importance factor between 0 and 1.\n\n The SimRank algorithm for determining node similarity is defined in\n [2]_.\n\n Parameters\n ----------\n G : NetworkX graph\n A NetworkX graph\n\n source : node\n If this is specified, the returned dictionary maps each node\n ``v`` in the graph to the similarity between ``source`` and\n ``v``.\n\n target : node\n If both ``source`` and ``target`` are specified, the similarity\n value between ``source`` and ``target`` is returned. If\n ``target`` is specified but ``source`` is not, this argument is\n ignored.\n\n importance_factor : float\n The relative importance of indirect neighbors with respect to\n direct neighbors.\n\n max_iterations : integer\n Maximum number of iterations.\n\n tolerance : float\n Error tolerance used to check convergence. When an iteration of\n the algorithm finds that no similarity value changes more than\n this amount, the algorithm halts.\n\n Returns\n -------\n similarity : dictionary or float\n If ``source`` and ``target`` are both ``None``, this returns a\n dictionary of dictionaries, where keys are node pairs and value\n are similarity of the pair of nodes.\n\n If ``source`` is not ``None`` but ``target`` is, this returns a\n dictionary mapping node to the similarity of ``source`` and that\n node.\n\n If neither ``source`` nor ``target`` is ``None``, this returns\n the similarity value for the given pair of nodes.\n\n Examples\n --------\n If the nodes of the graph are numbered from zero to *n - 1*, where *n*\n is the number of nodes in the graph, you can create a SimRank matrix\n from the return value of this function where the node numbers are\n the row and column indices of the matrix::\n\n >>> from numpy import array\n >>> G = nx.cycle_graph(4)\n >>> sim = nx.simrank_similarity(G)\n >>> lol = [[sim[u][v] for v in sorted(sim[u])] for u in sorted(sim)]\n >>> sim_array = array(lol)\n\n References\n ----------\n .. [1] https://en.wikipedia.org/wiki/SimRank\n .. [2] G. Jeh and J. Widom.\n \"SimRank: a measure of structural-context similarity\",\n In KDD'02: Proceedings of the Eighth ACM SIGKDD\n International Conference on Knowledge Discovery and Data Mining,\n pp. 538--543. ACM Press, 2002.\n \"\"\"\n prevsim = None\n\n # build up our similarity adjacency dictionary output\n newsim = {u: {v: 1 if u == v else 0 for v in G} for u in G}\n\n # These functions compute the update to the similarity value of the nodes\n # `u` and `v` with respect to the previous similarity values.\n def avg_sim(s):\n return sum(newsim[w][x] for (w, x) in s) / len(s) if s else 0.0\n\n def sim(u, v):\n Gadj = G.pred if G.is_directed() else G.adj\n return importance_factor * avg_sim(list(product(Gadj[u], Gadj[v])))\n\n for _ in range(max_iterations):\n if prevsim and _is_close(prevsim, newsim, tolerance):\n break\n prevsim = newsim\n newsim = {\n u: {v: sim(u, v) if u is not v else 1 for v in newsim[u]} for u in newsim\n }\n\n if source is not None and target is not None:\n return newsim[source][target]\n if source is not None:\n return newsim[source]\n return newsim\n\n\ndef simrank_similarity_numpy(\n G,\n source=None,\n target=None,\n importance_factor=0.9,\n max_iterations=100,\n tolerance=1e-4,\n):\n \"\"\"Calculate SimRank of nodes in ``G`` using matrices with ``numpy``.\n\n The SimRank algorithm for determining node similarity is defined in\n [1]_.\n\n Parameters\n ----------\n G : NetworkX graph\n A NetworkX graph\n\n source : node\n If this is specified, the returned dictionary maps each node\n ``v`` in the graph to the similarity between ``source`` and\n ``v``.\n\n target : node\n If both ``source`` and ``target`` are specified, the similarity\n value between ``source`` and ``target`` is returned. If\n ``target`` is specified but ``source`` is not, this argument is\n ignored.\n\n importance_factor : float\n The relative importance of indirect neighbors with respect to\n direct neighbors.\n\n max_iterations : integer\n Maximum number of iterations.\n\n tolerance : float\n Error tolerance used to check convergence. When an iteration of\n the algorithm finds that no similarity value changes more than\n this amount, the algorithm halts.\n\n Returns\n -------\n similarity : numpy matrix, numpy array or float\n If ``source`` and ``target`` are both ``None``, this returns a\n Matrix containing SimRank scores of the nodes.\n\n If ``source`` is not ``None`` but ``target`` is, this returns an\n Array containing SimRank scores of ``source`` and that\n node.\n\n If neither ``source`` nor ``target`` is ``None``, this returns\n the similarity value for the given pair of nodes.\n\n Examples\n --------\n >>> from numpy import array\n >>> G = nx.cycle_graph(4)\n >>> sim = nx.simrank_similarity_numpy(G)\n\n References\n ----------\n .. [1] G. Jeh and J. Widom.\n \"SimRank: a measure of structural-context similarity\",\n In KDD'02: Proceedings of the Eighth ACM SIGKDD\n International Conference on Knowledge Discovery and Data Mining,\n pp. 538--543. ACM Press, 2002.\n \"\"\"\n # This algorithm follows roughly\n #\n # S = max{C * (A.T * S * A), I}\n #\n # where C is the importance factor, A is the column normalized\n # adjacency matrix, and I is the identity matrix.\n import numpy as np\n\n adjacency_matrix = nx.to_numpy_array(G)\n\n # column-normalize the ``adjacency_matrix``\n adjacency_matrix /= adjacency_matrix.sum(axis=0)\n\n newsim = np.eye(adjacency_matrix.shape[0], dtype=np.float64)\n for _ in range(max_iterations):\n prevsim = np.copy(newsim)\n newsim = importance_factor * ((adjacency_matrix.T @ prevsim) @ adjacency_matrix)\n np.fill_diagonal(newsim, 1.0)\n\n if np.allclose(prevsim, newsim, atol=tolerance):\n break\n\n if source is not None and target is not None:\n return newsim[source, target]\n if source is not None:\n return newsim[source]\n return newsim\n\n\n# TODO replace w/ math.comb(n, k) for Python 3.8+\ndef _n_choose_k(n, k):\n \"\"\"Pure Python implementation of the binomial coefficient\n\n The general equation is n! / (k! * (n - k)!). The below\n implementation is a more efficient version.\n\n Note: this will be removed in favor of Python 3.8's ``math.comb(n, k)``.\n\n Parameters\n ----------\n n : int\n Set of ``n`` elements\n k : int\n Unordered chosen subset of length ``k``\n\n Returns\n -------\n binomial_coeff : int\n The number of ways (disregarding order) that k objects\n can be chosen from among n objects.\n\n Examples\n --------\n >>> _n_choose_k(5, 2)\n 10\n >>> _n_choose_k(5, 4)\n 5\n >>> _n_choose_k(100, 100)\n 1\n\n \"\"\"\n if k > n:\n return 0\n if n == k:\n return 1\n elif k < n - k:\n return reduce(mul, range(n - k + 1, n + 1)) // math.factorial(k)\n else:\n return reduce(mul, range(k + 1, n + 1)) // math.factorial(n - k)\n\n\ndef panther_similarity(G, source, k=5, path_length=5, c=0.5, delta=0.1, eps=None):\n \"\"\"Returns the Panther similarity of nodes in the graph `G` to node ``v``.\n\n Panther is a similarity metric that says \"two objects are considered\n to be similar if they frequently appear on the same paths.\" [1]_.\n\n Parameters\n ----------\n G : NetworkX graph\n A NetworkX graph\n source : node\n Source node for which to find the top `k` similar other nodes\n k : int (default = 5)\n The number of most similar nodes to return\n path_length : int (default = 5)\n How long the randomly generated paths should be (``T`` in [1]_)\n c : float (default = 0.5)\n A universal positive constant used to scale the number\n of sample random paths to generate.\n delta : float (default = 0.1)\n The probability that the similarity $S$ is not an epsilon-approximation to (R, phi),\n where $R$ is the number of random paths and $\\phi$ is the probability\n that an element sampled from a set $A \\subseteq D$, where $D$ is the domain.\n eps : float or None (default = None)\n The error bound. Per [1]_, a good value is ``sqrt(1/|E|)``. Therefore,\n if no value is provided, the recommended computed value will be used.\n\n Returns\n -------\n similarity : dictionary\n Dictionary of nodes to similarity scores (as floats). Note:\n the self-similarity (i.e., ``v``) will not be included in\n the returned dictionary.\n\n Examples\n --------\n >>> G = nx.star_graph(10)\n >>> sim = nx.panther_similarity(G, 0)\n\n References\n ----------\n .. [1] Zhang, J., Tang, J., Ma, C., Tong, H., Jing, Y., & Li, J.\n Panther: Fast top-k similarity search on large networks.\n In Proceedings of the ACM SIGKDD International Conference\n on Knowledge Discovery and Data Mining (Vol. 2015-August, pp. 1445–1454).\n Association for Computing Machinery. https://doi.org/10.1145/2783258.2783267.\n \"\"\"\n import numpy as np\n\n num_nodes = G.number_of_nodes()\n if num_nodes < k:\n warnings.warn(\n f\"Number of nodes is {num_nodes}, but requested k is {k}. \"\n \"Setting k to number of nodes.\"\n )\n k = num_nodes\n # According to [1], they empirically determined\n # a good value for ``eps`` to be sqrt( 1 / |E| )\n if eps is None:\n eps = np.sqrt(1.0 / G.number_of_edges())\n\n inv_node_map = {name: index for index, name in enumerate(G.nodes)}\n node_map = np.array(G)\n\n # Calculate the sample size ``R`` for how many paths\n # to randomly generate\n t_choose_2 = _n_choose_k(path_length, 2)\n sample_size = int((c / eps ** 2) * (np.log2(t_choose_2) + 1 + np.log(1 / delta)))\n index_map = {}\n _ = list(\n generate_random_paths(\n G, sample_size, path_length=path_length, index_map=index_map\n )\n )\n S = np.zeros(num_nodes)\n\n inv_sample_size = 1 / sample_size\n\n source_paths = set(index_map[source])\n\n # Calculate the path similarities\n # between ``source`` (v) and ``node`` (v_j)\n # using our inverted index mapping of\n # vertices to paths\n for node, paths in index_map.items():\n # Only consider paths where both\n # ``node`` and ``source`` are present\n common_paths = source_paths.intersection(paths)\n S[inv_node_map[node]] = len(common_paths) * inv_sample_size\n\n # Retrieve top ``k`` similar\n # Note: the below performed anywhere from 4-10x faster\n # (depending on input sizes) vs the equivalent ``np.argsort(S)[::-1]``\n top_k_unsorted = np.argpartition(S, -k)[-k:]\n top_k_sorted = top_k_unsorted[np.argsort(S[top_k_unsorted])][::-1]\n\n # Add back the similarity scores\n top_k_sorted_names = map(lambda n: node_map[n], top_k_sorted)\n top_k_with_val = dict(zip(top_k_sorted_names, S[top_k_sorted]))\n\n # Remove the self-similarity\n top_k_with_val.pop(source, None)\n return top_k_with_val\n\n\ndef generate_random_paths(G, sample_size, path_length=5, index_map=None):\n \"\"\"Randomly generate `sample_size` paths of length `path_length`.\n\n Parameters\n ----------\n G : NetworkX graph\n A NetworkX graph\n sample_size : integer\n The number of paths to generate. This is ``R`` in [1]_.\n path_length : integer (default = 5)\n The maximum size of the path to randomly generate.\n This is ``T`` in [1]_. According to the paper, ``T >= 5`` is\n recommended.\n index_map : dictionary, optional\n If provided, this will be populated with the inverted\n index of nodes mapped to the set of generated random path\n indices within ``paths``.\n\n Returns\n -------\n paths : generator of lists\n Generator of `sample_size` paths each with length `path_length`.\n\n Examples\n --------\n Note that the return value is the list of paths:\n\n >>> G = nx.star_graph(3)\n >>> random_path = nx.generate_random_paths(G, 2)\n\n By passing a dictionary into `index_map`, it will build an\n inverted index mapping of nodes to the paths in which that node is present:\n\n >>> G = nx.star_graph(3)\n >>> index_map = {}\n >>> random_path = nx.generate_random_paths(G, 3, index_map=index_map)\n >>> paths_containing_node_0 = [random_path[path_idx] for path_idx in index_map.get(0, [])]\n\n References\n ----------\n .. [1] Zhang, J., Tang, J., Ma, C., Tong, H., Jing, Y., & Li, J.\n Panther: Fast top-k similarity search on large networks.\n In Proceedings of the ACM SIGKDD International Conference\n on Knowledge Discovery and Data Mining (Vol. 2015-August, pp. 1445–1454).\n Association for Computing Machinery. https://doi.org/10.1145/2783258.2783267.\n \"\"\"\n import numpy as np\n\n # Calculate transition probabilities between\n # every pair of vertices according to Eq. (3)\n adj_mat = nx.to_numpy_array(G)\n inv_row_sums = np.reciprocal(adj_mat.sum(axis=1)).reshape(-1, 1)\n transition_probabilities = adj_mat * inv_row_sums\n\n node_map = np.array(G)\n num_nodes = G.number_of_nodes()\n\n for path_index in range(sample_size):\n # Sample current vertex v = v_i uniformly at random\n node_index = np.random.randint(0, high=num_nodes)\n node = node_map[node_index]\n\n # Add v into p_r and add p_r into the path set\n # of v, i.e., P_v\n path = [node]\n\n # Build the inverted index (P_v) of vertices to paths\n if index_map is not None:\n if node in index_map:\n index_map[node].add(path_index)\n else:\n index_map[node] = {path_index}\n\n starting_index = node_index\n for _ in range(path_length):\n # Randomly sample a neighbor (v_j) according\n # to transition probabilities from ``node`` (v) to its neighbors\n neighbor_index = np.random.choice(\n num_nodes, p=transition_probabilities[starting_index]\n )\n\n # Set current vertex (v = v_j)\n starting_index = neighbor_index\n\n # Add v into p_r\n neighbor_node = node_map[neighbor_index]\n path.append(neighbor_node)\n\n # Add p_r into P_v\n if index_map is not None:\n if neighbor_node in index_map:\n index_map[neighbor_node].add(path_index)\n else:\n index_map[neighbor_node] = {path_index}\n\n yield path\n"
] |
[
[
"numpy.log",
"numpy.log2",
"numpy.allclose",
"numpy.random.choice",
"numpy.eye",
"numpy.copy",
"numpy.fill_diagonal",
"numpy.argpartition",
"numpy.argsort",
"scipy.optimize.linear_sum_assignment",
"numpy.array",
"numpy.zeros",
"numpy.empty",
"numpy.random.randint"
]
] |
Mike030668/Python--learning--UII
|
[
"4b0a3fe32b1bb4e6f98130aab09b3ab55eca2df4"
] |
[
"Lesson _8/lesson_8_light.py"
] |
[
"import time\nimport numpy as np\n\n\n# декоратор\ndef split_sings(f):\n def checker(*args, **kwargs):\n start = time.time()\n data_t = f(*args, **kwargs)\n print(f'время до декоратора {data_t[1]}')\n plus = list(filter(lambda x: x > 0, data_t[0]))\n minus = list(filter(lambda x: x < 0, data_t[0]))\n return (plus, minus), time.time() - start\n\n return checker\n\n\n@split_sings\ndef get_randdata(num):\n start = time.time()\n data = np.random.standard_normal(num) * np.random.gumbel(num)\n return data, time.time() - start\n\n\ndata, time_data = get_randdata(2000)\n\nprint(data[0])\nprint(data[1])\nprint(f'время после декоратора {time_data}')\nprint()\n\n\n# декоратор\ndef get_time(f):\n def checker(*args, **kwargs):\n start = time.time()\n data = f(*args, **kwargs)\n print(f'время процесса {time.time() - start}')\n return data\n\n return checker\n\n\n@get_time\ndef get_range_1(num):\n return [i for i in range(1, num)]\n\n@get_time\ndef get_range_2(num):\n data = []\n for i in range(1, num):\n data.append(i)\n return data\n\n@get_time\ndef get_range_3(num):\n return np.arange(1,num)\n\n@get_time\ndef get_range_4(num):\n return list(map(lambda x: x , range(1,num)))\n\n@get_time\ndef get_range_5(num):\n return list(filter(lambda x: x , range(1,num)))\n\n@get_time\ndef get_range_6(num):\n for i in range(1, num):\n yield i\n\na = get_range_1(1000000)\nprint(len(a))\nprint()\na = get_range_2(1000000)\nprint(len(a))\nprint()\na = get_range_3(1000000)\nprint(len(a))\nprint()\na = get_range_4(1000000)\nprint(len(a))\nprint()\na = get_range_5(1000000)\nprint(len(a))\nprint()\na = get_range_6(1000000)\nprint(next(a))"
] |
[
[
"numpy.arange",
"numpy.random.gumbel",
"numpy.random.standard_normal"
]
] |
nitantrajput/project-111
|
[
"bf99036974b9c7bd3e7e470608f869e005d58053"
] |
[
"main.py"
] |
[
"import plotly.figure_factory as ff\nimport plotly.graph_objects as go\nimport statistics\nimport random\nimport pandas as pd\nimport csv\n\ndf = pd.read_csv(\"z-test-master\\studentMarks.csv\")\ndata = df[\"Math_score\"].tolist()\n\n#plotting the graph\nfig = ff.create_distplot([data],[\"Math Scores\"], show_hist= False)\nfig.show()\n\n#calculating the mean and standard deviation of the population data\nmean = statistics.mean(data)\nstd_deviation = statistics.stdev(data)\n# print(\"mean of popultion:- \",mean)\n# print(\"Standard deviation of popultion:- \",std_deviation)\n\n\n#\n## code to find the mean of 100 data points 1000 times \n#function to get the mean of the given data samples\n# pass the number of data points you want as counter\ndef random_set_of_mean(counter):\n dataset = []\n for i in range(0, counter):\n random_index= random.randint(0,len(data)-1)\n value = data[random_index]\n dataset.append(value)\n mean = statistics.mean(dataset)\n return mean\n\n\n\n# Pass the number of time you want the mean of the data points as a parameter in range function in for loop\nmean_list = []\nfor i in range(0,1000):\n set_of_means= random_set_of_mean(100)\n mean_list.append(set_of_means)\n\n\n## calculating mean and standard_deviation of the sampling distribution.\nstd_deviation = statistics.stdev(mean_list)\n# mean = statistics.mean(mean_list)\n# print(\"mean of sampling distribution:- \",mean)\n# print(\"Standard deviation of sampling distribution:- \", std_deviation)\n\n# #plotting the mean of the sampling\n# fig = ff.create_distplot([mean_list], [\"student marks\"], show_hist=False)\n# fig.add_trace(go.Scatter(x=[mean, mean], y=[0, 0.20], mode=\"lines\", name=\"MEAN\"))\n# fig.show()\n# print(\"Standard deviation of sampling distribution:- \", std_deviation)\n\n\n## findig the standard deviation starting and ending values\nfirst_std_deviation_start, first_std_deviation_end = mean-std_deviation, mean+std_deviation\nsecond_std_deviation_start, second_std_deviation_end = mean-(2*std_deviation), mean+(2*std_deviation)\nthird_std_deviation_start, third_std_deviation_end = mean-(3*std_deviation), mean+(3*std_deviation)\n# print(\"std1\",first_std_deviation_start, first_std_deviation_end)\n# print(\"std2\",second_std_deviation_start, second_std_deviation_end)\n# print(\"std3\",third_std_deviation_start,third_std_deviation_end)\n\n## plotting the graph with traces\n# fig = ff.create_distplot([mean_list], [\"student marks\"], show_hist=False)\n# fig.add_trace(go.Scatter(x=[mean, mean], y=[0, 0.17], mode=\"lines\", name=\"MEAN\"))\n# fig.add_trace(go.Scatter(x=[first_std_deviation_start, first_std_deviation_start], y=[0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1 START\"))\n# fig.add_trace(go.Scatter(x=[first_std_deviation_end, first_std_deviation_end], y=[0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1 END\"))\n# fig.add_trace(go.Scatter(x=[second_std_deviation_start, second_std_deviation_start], y=[0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 2 START\"))\n# fig.add_trace(go.Scatter(x=[second_std_deviation_end, second_std_deviation_end], y=[0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 2 END\"))\n# fig.add_trace(go.Scatter(x=[third_std_deviation_start,third_std_deviation_start], y=[0,0.17], mode=\"lines\", name=\"STANDARD DEVIATION 3 START\"))\n# fig.add_trace(go.Scatter(x=[third_std_deviation_end,third_std_deviation_end], y=[0,0.17], mode=\"lines\", name=\"STANDARD DEVIATION 3 END\"))\n# fig.show()\n\n\n# finding the mean of the first data(STUDENTS WHO GOT TABLET WITH LEARNING MATERIAL) and plotting it on the plot.\n# df = pd.read_csv(\"data1.csv\")\n# data = df[\"Math_score\"].tolist()\n# mean_of_sample1 = statistics.mean(data)\n# print(\"Mean of sample1:- \",mean_of_sample1)\n# fig = ff.create_distplot([mean_list], [\"student marks\"], show_hist=False)\n# fig.add_trace(go.Scatter(x=[mean, mean], y=[0, 0.17], mode=\"lines\", name=\"MEAN\"))\n# fig.add_trace(go.Scatter(x=[mean_of_sample1, mean_of_sample1], y=[0, 0.17], mode=\"lines\", name=\"MEAN OF SAMPLE\"))\n# fig.add_trace(go.Scatter(x=[first_std_deviation_end, first_std_deviation_end], y=[0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1 END\"))\n# fig.show()\n\n\n\n# finding the mean of the SECOND data (STUDENTS WHO HAD EXTRA CLASSES ) and plotting it on the plot.\n# df = pd.read_csv(\"data2.csv\")\n# data = df[\"Math_score\"].tolist()\n# mean_of_sample2 = statistics.mean(data)\n# print(\"mean of sample 2:- \",mean_of_sample2)\n# fig = ff.create_distplot([mean_list], [\"student marks\"], show_hist=False)\n# fig.add_trace(go.Scatter(x=[mean, mean], y=[0, 0.17], mode=\"lines\", name=\"MEAN\"))\n# fig.add_trace(go.Scatter(x=[mean_of_sample2, mean_of_sample2], y=[0, 0.17], mode=\"lines\", name=\"MEAN OF STUDENTS WHO HAD EXTRA CLASSES\"))\n# fig.add_trace(go.Scatter(x=[first_std_deviation_end, first_std_deviation_end], y=[0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 1 END\"))\n# fig.add_trace(go.Scatter(x=[second_std_deviation_end, second_std_deviation_end], y=[0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 2 END\"))\n# fig.show()\n\n\n# finding the mean of the THIRD data (STUDENTS WHO GOT FUNSHEET) and plotting it on the plot.\ndf = pd.read_csv(\"z-test-master\\data3.csv\")\ndata = df[\"Math_score\"].tolist()\nmean_of_sample3 = statistics.mean(data)\nprint(\"mean of sample3:- \",mean_of_sample3)\nfig = ff.create_distplot([mean_list], [\"student marks\"], show_hist=False)\nfig.add_trace(go.Scatter(x=[mean, mean], y=[0, 0.17], mode=\"lines\", name=\"MEAN\"))\nfig.add_trace(go.Scatter(x=[mean_of_sample3, mean_of_sample3], y=[0, 0.17], mode=\"lines\", name=\"MEAN OF STUDNETS WHO GOT FUNSHEETS\"))\nfig.add_trace(go.Scatter(x=[second_std_deviation_end, second_std_deviation_end], y=[0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 2 END\"))\nfig.add_trace(go.Scatter(x=[third_std_deviation_end, third_std_deviation_end], y=[0, 0.17], mode=\"lines\", name=\"STANDARD DEVIATION 3 END\"))\nfig.show()\n"
] |
[
[
"pandas.read_csv"
]
] |
rclapp/optimus-py
|
[
"178e6638169a551ed3d92d47ca86bae99ec7a85e"
] |
[
"results.py"
] |
[
"import itertools\nimport logging\nimport os\nimport statistics\nfrom pathlib import WindowsPath\nfrom typing import List, Union\n\nimport seaborn as sns; sns.set_theme()\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nSEPARATOR = \",\"\nHEADER = [\"ID\", \"Mode\", \"Is Best\", \"Mean Query Time\", \"Query Ratio\", \"Mean Process Time\", \"Process Ratio\", \"RAM\", \"RAM in GB\"]\n\n\nclass PermutationResult:\n counter = 1\n current_ram = None\n\n def __init__(self, mode: str, cube_name: str, view_names: list, process_name: str, dimension_order: list,\n query_times_by_view: dict, process_times_by_process: dict, ram_usage: float = None, ram_percentage_change: float = None,\n reset_counter: bool = False):\n from optimuspy import ExecutionMode\n\n self.mode = ExecutionMode(mode)\n self.cube_name = cube_name\n self.view_names = view_names\n self.process_name = process_name\n self.dimension_order = dimension_order\n self.query_times_by_view = query_times_by_view\n self.process_times_by_process = process_times_by_process\n self.is_best = False\n if process_name is None:\n self.include_process = False\n else:\n self.include_process = True\n\n\n # from original dimension order\n if ram_usage:\n self.ram_usage = ram_usage\n\n # from all other dimension orders\n elif ram_percentage_change is not None:\n self.ram_usage = PermutationResult.current_ram + (\n PermutationResult.current_ram * ram_percentage_change / 100)\n\n else:\n raise RuntimeError(\"Either 'ram_usage' or 'ram_percentage_change' must be provided\")\n\n PermutationResult.current_ram = self.ram_usage\n self.ram_percentage_change = ram_percentage_change or 0\n\n if reset_counter:\n PermutationResult.counter = 1\n\n self.permutation_id = PermutationResult.counter\n PermutationResult.counter += 1\n\n def median_query_time(self, view_name: str = None) -> float:\n view_name = view_name or self.view_names[0]\n median = statistics.median(self.query_times_by_view[view_name])\n if not median:\n raise RuntimeError(f\"view '{view_name}' in cube '{self.cube_name}' is too small\")\n\n return median\n\n def median_process_time(self, process_name: str = None) -> float:\n process_name = process_name or self.process_name\n median = statistics.median(self.process_times_by_process[process_name])\n return median\n\n def build_header(self) -> list:\n dimensions = []\n for d in range(1, len(self.dimension_order) + 1):\n dimensions.append(\"Dimension\" + str(d))\n header = HEADER + dimensions\n return header\n\n def build_csv_header(self) -> str:\n return SEPARATOR.join(self.build_header()) + \"\\n\"\n\n\n def to_row(self, view_name: str, process_name: str, original_order_result: object) -> List[str]:\n from optimuspy import LABEL_MAP\n\n median_query_time = float(self.median_query_time(view_name))\n original_median_query_time = float(original_order_result.median_query_time(view_name))\n query_time_ratio = median_query_time / original_median_query_time - 1\n\n if process_name is not None:\n median_process_time = float(self.median_process_time(process_name))\n original_median_process_time = float(original_order_result.median_process_time(process_name))\n process_time_ratio = median_process_time / original_median_process_time - 1\n\n ram_in_gb = float(self.ram_usage) / (1024 ** 3)\n\n if process_name is None:\n row = row = [str(self.permutation_id),\n LABEL_MAP[self.mode],\n str(self.is_best),\n median_query_time,\n query_time_ratio,\n 0,\n 0,\n self.ram_usage,\n ram_in_gb] \\\n + list(self.dimension_order)\n\n else:\n row = [str(self.permutation_id),\n LABEL_MAP[self.mode],\n str(self.is_best),\n median_query_time,\n query_time_ratio,\n median_process_time,\n process_time_ratio,\n self.ram_usage,\n ram_in_gb] \\\n + list(self.dimension_order)\n return row\n\n def to_csv_row(self, view_name: str, process_name: str, original_order_result: object) -> str:\n row = [str(i) for i in self.to_row(view_name, process_name, original_order_result)]\n return SEPARATOR.join(row) + \"\\n\"\n\n\nclass OptimusResult:\n TEXT_FONT_SIZE = 5\n\n def __init__(self, cube_name: str, permutation_results: List[PermutationResult]):\n\n self.cube_name = cube_name\n self.permutation_results = permutation_results\n\n self.best_result = self.determine_best_result()\n if self.best_result:\n for permutation_result in permutation_results:\n if permutation_result.permutation_id == self.best_result.permutation_id:\n permutation_result.is_best = True\n\n def to_dataframe(self, view_name, process_name) -> pd.DataFrame:\n header = self.permutation_results[0].build_header()\n rows = []\n for result in self.permutation_results:\n rows.append(result.to_row(view_name, process_name, self.original_order_result))\n df = pd.DataFrame(rows, columns=header)\n return df\n\n\n def to_lines(self, view_name, process_name) -> List[str]:\n lines = itertools.chain(\n [self.permutation_results[0].build_csv_header()],\n [result.to_csv_row(view_name, process_name, self.original_order_result) for result in self.permutation_results])\n\n return list(lines)\n\n def to_csv(self, view_name: str, process_name: str,file_name: 'WindowsPath'):\n lines = self.to_lines(view_name, process_name)\n\n os.makedirs(os.path.dirname(str(file_name)), exist_ok=True)\n with open(str(file_name), \"w\") as file:\n file.writelines(lines)\n\n def to_xlsx(self, view_name: str, process_name: str, file_name: 'WindowsPath'):\n try:\n import xlsxwriter\n\n # Create a workbook and add a worksheet.\n workbook = xlsxwriter.Workbook(file_name)\n worksheet = workbook.add_worksheet()\n\n # Iterate over the data and write it out row by row.\n for row, line in enumerate(self.to_lines(view_name, process_name)):\n for col, item in enumerate(line.split(SEPARATOR)):\n worksheet.write(row, col, item)\n\n workbook.close()\n\n except ImportError:\n logging.warning(\"Failed to import xlsxwriter. Writing to csv instead\")\n file_name = file_name.with_suffix(\".csv\")\n return self.to_csv(view_name, file_name)\n\n # create scatter plot ram vs. performance\n def to_png(self, view_name: str, process_name: str, file_name: str):\n from optimuspy import COLOR_MAP\n df = self.to_dataframe(view_name, process_name)\n df_to_plot = df[[\"ID\", \"Query Ratio\", \"Mean Process Time\", \"RAM in GB\", \"Mode\"]]\n\n plt.figure(figsize=(8, 8))\n sns.set_style(\"ticks\")\n\n p = sns.scatterplot(data=df,\n x=\"RAM in GB\",\n y=\"Query Ratio\",\n size=\"Mean Process Time\" if process_name is not None else None,\n hue=\"Mode\",\n palette=\"viridis\",\n edgecolors=\"black\",\n legend=True,\n alpha=0.4,\n sizes=(20, 500) if process_name is not None else None)\n\n for index, row in df.iterrows():\n p.text(row[\"RAM in GB\"],\n row[\"Query Ratio\"],\n row[\"ID\"],\n color='black')\n\n sns.despine(trim=True, offset=2)\n p.set_xlabel(\"RAM (GB)\")\n p.set_ylabel(\"Query Time Compared to Original Order\")\n p.legend(title='Legend', loc='best')\n\n plt.grid()\n plt.tight_layout()\n #plt.show()\n\n os.makedirs(os.path.dirname(str(file_name)), exist_ok=True)\n\n plt.savefig(file_name, dpi=400)\n plt.clf()\n\n @property\n def original_order_result(self) -> PermutationResult:\n from optimuspy import ExecutionMode\n\n for result in self.permutation_results:\n if result.mode == ExecutionMode.ORIGINAL_ORDER:\n return result\n\n def determine_best_result(self) -> Union[PermutationResult, None]:\n ram_range = [result.ram_usage for result in self.permutation_results]\n min_ram, max_ram = min(ram_range), max(ram_range)\n\n query_speed_range = [result.median_query_time() for result in self.permutation_results]\n min_query_speed, max_query_speed = min(query_speed_range), max(query_speed_range)\n\n # find a good balance between speed and ram\n for value in (0.01, 0.025, 0.05, 0.075, 0.1, 0.125, 0.15, 0.2, 0.25):\n ram_threshold = min_ram + value * (max_ram - min_ram)\n query_speed_threshold = min_query_speed + value * (max_query_speed - min_query_speed)\n for permutation_result in self.permutation_results:\n if all([permutation_result.ram_usage <= ram_threshold,\n permutation_result.median_query_time() <= query_speed_threshold]):\n return permutation_result\n\n # no dimension order falls in sweet spot\n return None\n"
] |
[
[
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.savefig",
"pandas.DataFrame",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.figure"
]
] |
ianovski/google-play-store-nlp
|
[
"afdfe5517bbf30e02f3e3ba80e9267fd574d7ee7"
] |
[
"src/local_run/train.py"
] |
[
"import time\nimport random\nimport pandas as pd\nfrom glob import glob\nimport argparse\nimport json\nimport subprocess\nimport sys\nimport os\nimport tensorflow as tf\nfrom transformers import DistilBertTokenizer\nfrom transformers import TFDistilBertForSequenceClassification\nfrom transformers import TextClassificationPipeline\nfrom transformers.configuration_distilbert import DistilBertConfig\nimport wandb\nMAX_SEQ_LENGTH = 128\n\nimport optuna\nfrom functools import partial\n\nclass Train():\n def __init__(self):\n self.epochs=3\n self.learning_rate = 0.00001\n self.epsilon = 0.00000001\n self.train_batch_size=128\n self.validation_batch_size=128\n self.test_batch_size=128\n self.train_steps_per_epoch=100\n self.validation_steps=100\n self.test_steps=100\n self.train_instance_count=1\n self.train_instance_type='ml.c5.9xlarge'\n self.train_volume_size=1024\n self.use_xla=True\n self.use_amp=True\n self.freeze_bert_layer=False\n self.enable_sagemaker_debugger=True\n self.enable_checkpointing=False\n self.enable_tensorboard=False\n self.input_mode='Pipe'\n self.run_validation=True\n self.run_test=True\n self.run_sample_predictions = True\n self.train_dataset = None\n self.validation_dataset = None\n self.test_dataset = None\n self.model = None\n self.callbacks = [] \n\n def select_data_and_label_from_record(self,record):\n x = {\n 'input_ids': record['input_ids'],\n 'input_mask': record['input_mask'],\n 'segment_ids': record['segment_ids']\n }\n y = record['label_ids']\n\n return (x, y)\n\n def file_based_input_dataset_builder(self,\n channel,\n input_filenames,\n pipe_mode,\n is_training,\n drop_remainder):\n\n # For training, we want a lot of parallel reading and shuffling.\n # For eval, we want no shuffling and parallel reading doesn't matter.\n\n if pipe_mode:\n print('***** Using pipe_mode with channel {}'.format(channel))\n from sagemaker_tensorflow import PipeModeDataset\n dataset = PipeModeDataset(channel=channel,\n record_format='TFRecord')\n else:\n print('***** Using input_filenames {}'.format(input_filenames))\n dataset = tf.data.TFRecordDataset(input_filenames)\n\n dataset = dataset.repeat(100)\n dataset = dataset.prefetch(tf.data.experimental.AUTOTUNE)\n\n name_to_features = {\n \"input_ids\": tf.io.FixedLenFeature([MAX_SEQ_LENGTH], tf.int64),\n \"input_mask\": tf.io.FixedLenFeature([MAX_SEQ_LENGTH], tf.int64),\n \"segment_ids\": tf.io.FixedLenFeature([MAX_SEQ_LENGTH], tf.int64),\n \"label_ids\": tf.io.FixedLenFeature([], tf.int64),\n }\n\n def _decode_record(record, name_to_features):\n \"\"\"Decodes a record to a TensorFlow example.\"\"\"\n return tf.io.parse_single_example(record, name_to_features)\n \n dataset = dataset.apply(\n tf.data.experimental.map_and_batch(\n lambda record: _decode_record(record, name_to_features),\n # batch_size=8,\n batch_size=64,\n drop_remainder=drop_remainder,\n num_parallel_calls=tf.data.experimental.AUTOTUNE))\n\n dataset.cache()\n\n if is_training:\n dataset = dataset.shuffle(seed=42,\n buffer_size=10,\n reshuffle_each_iteration=True)\n return dataset\n\n def read_training_data(self, filepath):\n train_data = filepath\n train_data_filenames = glob('{}.tfrecord/*'.format(train_data))\n \n print('train_data_filenames {}'.format(train_data_filenames))\n\n self.train_dataset = self.file_based_input_dataset_builder(\n channel='train',\n input_filenames=train_data_filenames,\n pipe_mode=False,\n is_training=True,\n drop_remainder=False).map(self.select_data_and_label_from_record)\n \n def read_validation_data(self, filepath):\n validation_data = filepath\n validation_data_filenames = glob('{}.tfrecord/*'.format(validation_data))\n print('validation_data_filenames {}'.format(validation_data_filenames))\n\n self.validation_dataset = self.file_based_input_dataset_builder(\n channel='validation',\n input_filenames=validation_data_filenames,\n pipe_mode=False,\n is_training=False,\n drop_remainder=False).map(self.select_data_and_label_from_record)\n \n def read_test_data(self, filepath):\n test_data = filepath\n test_data_filenames = glob('{}.tfrecord/*'.format(test_data))\n print(test_data_filenames)\n self.test_dataset = self.file_based_input_dataset_builder(\n channel='test',\n input_filenames=test_data_filenames,\n pipe_mode=False,\n is_training=False,\n drop_remainder=False).map(self.select_data_and_label_from_record)\n \n def load_pretrained_bert_model(self):\n CLASSES = [1, 2, 3, 4, 5, 6,7]\n \n config = DistilBertConfig.from_pretrained('distilbert-base-uncased',\n num_labels=len(CLASSES))\n \n self.model = TFDistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased', \n config=config)\n\n def setup_custom_classifier_model(self):\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n metric=tf.keras.metrics.SparseCategoricalAccuracy('accuracy')\n\n optimizer=tf.keras.optimizers.Adam(learning_rate=self.learning_rate, epsilon=self.epsilon)\n self.model.compile(optimizer=optimizer, loss=loss, metrics=[metric])\n self.model.layers[0].trainable=not self.freeze_bert_layer\n self.model.summary()\n\n log_dir = './tmp/tensorboard/'\n tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir)\n \n self.callbacks.append(tensorboard_callback)\n\n history = self.model.fit(self.train_dataset,\n shuffle=True,\n epochs=self.epochs,\n steps_per_epoch=self.train_steps_per_epoch,\n validation_data=self.validation_dataset,\n validation_steps=self.validation_steps,\n callbacks=self.callbacks,\n batch_size=1)\n\n def evaluate_model(self):\n test_history = self.model.evaluate(self.test_dataset,\n steps=self.test_steps, \n callbacks=self.callbacks)\n print(\"model evaluation: {}\".format(test_history))\n \n def save_model(self, filename):\n model_dir = './tmp/'\n if not os.path.exists(model_dir):\n os.makedirs(model_dir)\n filepath = model_dir + filename\n self.model.save_pretrained(filepath)\n \n def init_sweep(self):\n sweep_config = {\n \"name\": \"vanilla-sweep-batch-16\",\n \"method\": \"bayes\",\n \"metric\": {\"name\": \"accuracy\", \"goal\": \"maximize\"},\n \"parameters\": {\n \"num_train_epochs\": {\"min\": 1, \"max\": 10},\n \"learning_rate\": {\"min\": 0, \"max\": 4e-4},\n },\n \"early_terminate\": {\"type\": \"hyperband\", \"min_iter\": 60}\n }\n hyperparameter_defaults = dict(\n shuffle=True,\n epochs=self.epochs,\n steps_per_epoch=self.train_steps_per_epoch,\n validation_data=self.validation_dataset,\n validation_steps=self.validation_steps,\n callbacks=self.callbacks,\n batch_size=1\n )\n wandb.init(project=\"bert-opt\", sync_tensorboard=True,config=hyperparameter_defaults)\n \n def optimize(self,trial):\n\n epochs = trial.suggest_int(\"epochs\",1,3)\n steps_per_epoch=trial.suggest_int(\"steps_per_epoch\",10,100)\n validation_steps=trial.suggest_int(\"validation_steps\",10,100)\n\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n metric=tf.keras.metrics.SparseCategoricalAccuracy('accuracy')\n\n optimizer=tf.keras.optimizers.Adam(learning_rate=self.learning_rate, epsilon=self.epsilon)\n self.model.compile(optimizer=optimizer, loss=loss, metrics=[metric])\n self.model.layers[0].trainable=not self.freeze_bert_layer\n self.model.summary()\n\n log_dir = './tmp/tensorboard/'\n tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir)\n \n self.callbacks.append(tensorboard_callback)\n print(\"[debug] fit model...................................\")\n history = self.model.fit(self.train_dataset,\n shuffle=True,\n epochs=epochs,\n steps_per_epoch=steps_per_epoch,\n validation_data=self.validation_dataset,\n validation_steps=validation_steps,\n # callbacks=self.callbacks,\n batch_size=None,\n verbose=2)\n \n self.evaluate_model()\n\ndef main():\n train = Train()\n train.read_training_data('output_train_data')\n train.read_validation_data('output_validation_data')\n train.read_test_data('output_test_data')\n train.load_pretrained_bert_model()\n\n optimization_function = partial(train.optimize)\n study = optuna.create_study(direction=\"minimize\")\n study.optimize(optimization_function, n_trials=15)\n # train.setup_custom_classifier_model()\n # train.evaluate_model()\n train.save_model(\"model\")\n\nif __name__ == \"__main__\":\n main()"
] |
[
[
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"tensorflow.data.TFRecordDataset",
"tensorflow.io.parse_single_example",
"tensorflow.io.FixedLenFeature",
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.callbacks.TensorBoard",
"tensorflow.keras.metrics.SparseCategoricalAccuracy"
]
] |
Danielaleite/Nextrout
|
[
"a513c5320e7f3c3a7ff61cade863dea075913af1"
] |
[
"nextrout_core/main.py"
] |
[
"#### import the needed stuff\nimport dmk_cont\nimport pre_extraction\nimport filtering\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport matplotlib.tri as mtri\nimport numpy as np\nimport pickle as pkl\nimport os\n\n\n\ndef nextrout(\n forcing_flag,\n extra_info,\n beta_c,\n beta_d = 1,\n ndiv=15, \n graph_type='1',\n weighting_method = 'ER',\n DMKw = 'tdens',\n min_pe = 0.01, \n min_f = 0.001,\n verbose = True, \n weighting_method_simplification = 'ER',\n BPw = 'tdens0', \n stop_thresh_f = 1e-6, \n btns_factor_source=.1, \n btns_factor_sink=.1,\n terminal_criterion = 'btns_centr',\n weight_flag = 'unit',\n storing = None\n ):\n \n inputs = {}\n inputs['continuous'] = {}\n # run the dmk_cont\n grid, subgrid, points, vertices, coord,topol,element_attributes = dmk_cont.grid_gen(ndiv)\n forcing, triang_source_indices,triang_sink_indices = dmk_cont.forcing_generator(forcing_flag, grid, coord, topol, extra_info=extra_info)\n tdpot, timefun = dmk_cont.dmk_cont(forcing,beta_c, ndiv, storing = storing)\n\n\n if storing is not None:\n triang = mtri.Triangulation(coord.transpose()[0,:], coord.transpose()[1,:], topol)\n fig1, ax1 = plt.subplots(figsize=(10, 10))\n ax1.set_aspect('equal')\n tpc = ax1.tripcolor(triang, -tdpot.tdens, cmap='gray')\n ax1.tricontour(triang, forcing, cmap='RdBu_r')\n fig1.colorbar(tpc)\n plt.savefig(storing+'/dmk_sol.png')\n plt.close()\n\n inputs['continuous']['ndiv'] = ndiv\n inputs['continuous']['forcing'] = forcing\n inputs['continuous']['pflux'] = beta_c\n\n # run the graph extraction\n\n tdens_weights = tdpot.tdens\n tdens_weights = tdens_weights/max(tdens_weights)\n Gpe = pre_extraction.pre_extr(coord, topol, tdens_weights,triang_source_indices,triang_sink_indices, min_= min_pe, graph_type=graph_type,weighting_method = weighting_method, DMKw = DMKw)\n node_colors = []\n for node in Gpe.nodes():\n \tterminal_val = Gpe.nodes[node]['terminal']\n \tif terminal_val == 1:\n \t\tnode_colors.append('g')\n \telif terminal_val == -1:\n \t\tnode_colors.append('r')\n \telse:\n \t\tnode_colors.append('k')\n\n if storing is not None:\n weights = np.array([Gpe.edges[edge][DMKw] for edge in Gpe.edges()])\n max_w = max(weights)\n weights/=max_w\n fig1, ax1 = plt.subplots(figsize=(10, 10))\n ax1.tricontour(triang, forcing, cmap='RdBu_r')\n pos_Gpe = nx.get_node_attributes(Gpe,'pos')\n nx.draw(Gpe,pos_Gpe, node_size = 10, node_color = node_colors, width = weights*3, ax = ax1)\n plt.savefig(storing+'/Gpe.png')\n plt.close()\n\n # source/sink generations\n \n sources,sinks = filtering.terminals_from_cont(Gpe, forcing_flag, extra_info, \n btns_factor_source=btns_factor_source, btns_factor_sink=btns_factor_sink, \n terminal_criterion=terminal_criterion)\n\n # run the dmk_discrete\n\n # get the connected components\n cc_list = list(nx.connected_components(Gpe))\n\n # apply dmk in the cc\n Gf = nx.Graph()\n count=0\n for cc in cc_list:\n count+=1\n temp_Gpe = Gpe.subgraph(cc)\n temp_sources = [node for node in sources if node in cc]\n temp_sinks = [node for node in sinks if node in cc]\n\n if len(temp_sources) ==0 or len(temp_sinks) == 0:\n raise ValueError('Not enough sources or sinks. Increase btns_factor.')\n\n temp_Gf,weights,colors, inputs_discr = filtering.filtering(\n temp_Gpe, \n temp_sources, \n temp_sinks, \n beta_d = beta_d, \n tdens0 = 2, # 2 means not unitary (i.e., taken from Gpe)\n threshold = min_f, \n BPweights = BPw, \n weight_flag = 'length',\n stopping_threshold_f = stop_thresh_f)\n \n # put everything together\n\n Gf = nx.disjoint_union(Gf, temp_Gf)\n\n if storing is not None and len(cc_list)!=1:\n fig1, ax1 = plt.subplots(figsize=(10, 10))\n ax1.tricontour(triang, forcing, cmap='RdBu_r')\n pos = nx.get_node_attributes(temp_Gf,'pos')\n nx.draw(temp_Gf,pos, node_size = 30, node_color = colors, width = abs(weights)*2 ,ax = ax1)\n plt.savefig(storing+'/Gf_'+str(count)+'.png')\n plt.close()\n\n \n\n deg = nx.degree_centrality(Gf)\n\n if weighting_method_simplification == 'ER':\n\n N = len(Gf.nodes())\n\n for edge in Gf.edges():\n\n Gf.edges[(edge[0], edge[1])][BPw] = Gf.nodes[edge[0]][\n 'weight'] / (\n deg[edge[0]] * (N - 1)) + \\\n Gf.nodes[edge[1]][\n 'weight'] / (\n deg[edge[1]] * (N - 1))\n elif weighting_method_simplification == 'IBP':\n \n raise ValueError('not implemented yet.')\n '''\n Gf_relabeled = relabeling(Gf, Gpe)\n for edge in Gf_relabeled.edges():\n Gf.edges[edge[0],edge[1]][BPw]=Gpe.edges[edge[0],edge[1]]['weight']\n '''\n \n elif weighting_method_simplification == 'BPW':\n pass\n\n \n\n if storing is not None:\n if len(cc_list)==1:\n color = colors\n else:\n color = 'k'\n weights = np.array([abs(Gf.edges[edge][BPw]) for edge in Gf.edges()])\n max_w = max(weights)\n weights/=max_w\n print('max',max_w)\n\n edge_labels = {}\n for edge in Gf.edges():\n edge_labels[edge]=round(abs(Gf.edges[edge][BPw])/max_w,2)\n if edge_labels[edge] == 0:\n edge_labels[edge] = 0\n\n fig1, ax1 = plt.subplots(figsize=(10, 10))\n ax1.tricontour(triang, forcing, cmap='RdBu_r')\n pos = nx.get_node_attributes(Gf,'pos')\n nx.draw(Gf,pos, node_size = 30, node_color = color, width = abs(weights)*3, ax = ax1 )\n #nx.draw_networkx_edge_labels(Gf,pos,edge_labels=edge_labels,font_color='red', font_size = 8, ax = ax1)\n plt.savefig(storing+'/Gf.png')\n plt.close()\n\n \n # storing the results\n\n if storing is not None:\n if verbose:print('storing at:'+storing)\n files = [('Gpe',Gpe),('Gf',Gf)]\n for ff in files:\n with open(storing + '/'+ff[0]+'.pkl', 'wb') as file:\n pkl.dump(ff[1], file)\n\n # storing inputs\n inputs['discrete'] = inputs_discr\n\n with open(storing + '/inputs.pkl', 'wb') as file:\n pkl.dump(inputs, file)\n\n pos = nx.get_node_attributes(Gf,'pos')\n\n with open(storing + '/Gf_node_locations.pkl', 'wb') as file:\n pkl.dump(pos, file)\n\n #print('isolated nodes?:',len(list(nx.isolates(Gf))))\n\n return Gf\n\n\n"
] |
[
[
"matplotlib.pyplot.close",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig"
]
] |
hoostus/prime-harvesting
|
[
"6606b94ea7859fbf217dbea4ace856e3fa4d154e"
] |
[
"market.py"
] |
[
"from decimal import Decimal\nimport itertools\nimport pandas\nimport collections\nfrom adt import AnnualChange\nimport random\n\ndef namedtuple_with_defaults(typename, field_names, default_values=()):\n T = collections.namedtuple(typename, field_names)\n T.__new__.__defaults__ = (None,) * len(T._fields)\n if isinstance(default_values, collections.Mapping):\n prototype = T(**default_values)\n else:\n prototype = T(*default_values)\n T.__new__.__defaults__ = tuple(prototype)\n return T\n\n\ndef constant_returns(stocks=Decimal('.04'), bonds=Decimal('.02'), inflation=Decimal('.02')):\n return itertools.repeat(AnnualChange(year = 0, stocks = stocks, bonds = bonds, inflation = inflation))\ndef nirp_returns():\n return constant_returns(stocks=Decimal('.02'), bonds=Decimal('-.01'), inflation=Decimal('.02'))\ndef zirp_returns():\n return constant_returns(stocks=Decimal('.04'), bonds=Decimal('0'), inflation=Decimal('.02'))\n\ndef big_drop(after=10):\n # 20 years of ZIRP to exhaust bonds under Prime Harvesting\n for i in range(after):\n yield AnnualChange(year=0, stocks=Decimal('.04'), bonds=Decimal('0'), inflation=Decimal('.02'))\n\n # big drop of stocks to allow rebalacing to \"buy stocks cheap\"\n yield AnnualChange(year=0, stocks=Decimal('-.25'), bonds=Decimal('0'), inflation=Decimal('.02'))\n\n # now we just have normal (but not amazing) returns.....\n while True:\n yield AnnualChange(year=0, stocks=Decimal('.08'), bonds=Decimal('.04'), inflation=Decimal('.03'))\n\nclass PortfolioCharts_1927:\n \"\"\" All of the other code only deals with stocks and bonds. Rewriting all\n of it to deal with arbitrary asset classes is not appealing at the moment.\n I also don't know of an actual use case for it. So we'll do a bit of a hack.\n You need to pass in a Weights tuple that tells this how to weight the returns\n of the various subclasses. That means the asset allocation is fixed and can't\n vary over time. But it also means I don't have to rewrite everything right now. \"\"\"\n asset_classes = [x + y for x in (\"LC\", \"MC\", \"SC\") for y in (\"B\", \"G\", \"V\")]\n Weights = namedtuple_with_defaults(\"Weights\", asset_classes, default_values=[0] * len(asset_classes))\n\n def __init__(self, weights):\n self.dataframe = pandas.read_csv('stock-index-calculator-20160620-v2.csv')\n self.years_of_data = len(self.dataframe)\n self.weights = weights\n\n def fmt(self, row):\n stock_performance = [row[x] * self.weights._asdict()[x] for x in self.asset_classes]\n stock_performance = sum(stock_performance)\n return AnnualChange(\n year=row['Year'],\n stocks=Decimal(stock_performance) / 100,\n bonds=Decimal(row['IT Bonds']) / 100,\n inflation=Decimal(row['CPI-U']) / 100\n )\n\n def random_year(self):\n i = random.randint(0, len(self.dataframe) - 1)\n return self.fmt(self.dataframe.iloc[i])\n\n def get_year(self, year):\n i = random.randint(0, len(self.dataframe) - 1)\n return self.fmt(self.dataframe.iloc[year-1927])\n\n\n def iter_from(self, year, length=None):\n start = year - 1927\n assert start >= 0\n count = 0\n for row in self.dataframe.iloc[start:].iterrows():\n yield self.fmt(row[1])\n count += 1\n if length != None and count >= length:\n raise StopIteration\n\nclass JST:\n \"\"\" The Jordà-Schularick-Taylor Macrohistory Database stata file containing\n country data from \"The Return of Everything\"\n http://www.macrohistory.net/data/\n \"\"\"\n\n Countries = ['AUS', 'BEL', 'CAN', 'DNK', 'FIN', 'FRA', 'DEU', 'ITA', 'JPN',\n 'NLD', 'NOR', 'PRT', 'ESP', 'SWE', 'CHE', 'GBR', 'USA']\n\n def __init__(self, country):\n df = pandas.read_stata('JSTdatasetR4.dta')\n # the year comes through as a float for some reason...coerce back to int\n df['year'] = df['year'].astype(int)\n df = df[df['iso'] == country]\n df = df[['year', 'iso', 'eq_tr', 'bond_tr', 'cpi']]\n\n # the 'cpi' is a CPI-level...not a year-over-year change. ugh.\n df['cpi'] = (df['cpi'] / df['cpi'].shift(1)) - 1\n df = df.dropna()\n\n self.start_year = df['year'].min()\n self.last_year = df['year'].max()\n self.country = country\n\n\n self.data = df\n\n def __len__(self):\n return len(self.data)\n\n def fmt(self, row):\n # the database only provides the consumer price index level, not the\n # annual change. I don't feel like going back and calculating it.\n return AnnualChange(\n year=row.year,\n stocks=Decimal(row.eq_tr),\n bonds=Decimal(row.bond_tr),\n inflation=Decimal(row.cpi)\n )\n\n def iter_from(self, year, length=None):\n assert year >= self.start_year\n if length:\n assert (year+length) <= self.last_year\n\n count = 0\n for row in self.data[self.data['year'] >= year].iterrows():\n yield self.fmt(row[1])\n count += 1\n if length != None and count >= length:\n return\n\nclass UK1900:\n def __init__(self, wrap=False):\n self.start_year = 1900\n self.dataframe = pandas.read_csv('uk1900.csv', index_col=0, parse_dates=True)\n\n if wrap:\n self.dataframe += self.dataframe\n\n def __len__(self):\n return len(self.dataframe)\n\n def random_year(self):\n i = random.randint(0, len(self.dataframe) - 1)\n return self.fmt(self.dataframe.iloc[i])\n\n def fmt(self, row):\n (stocks, bonds, inflation) = (Decimal(row[x]) for x in (\"Real Equity\", \"Real Gilt\", \"Inflation\"))\n\n return AnnualChange(\n year=row.name.year,\n stocks=stocks + inflation,\n bonds=bonds + inflation,\n inflation=inflation\n )\n\n def iter_from(self, year, length=None):\n start = year - 1900\n assert start >= 0\n count = 0\n for row in self.dataframe.iloc[start:].iterrows():\n yield self.fmt(row[1])\n count += 1\n if length != None and count >= length:\n return\n\nclass US_1871_Monthly:\n def __init__(self):\n self.data = pandas.read_csv('US_1871_Monthly.csv', index_col=0, parse_dates=True)\n\n def fmt(self, row):\n return AnnualChange(\n year=row.name.year,\n stocks=Decimal(row['S&P %']),\n bonds=Decimal(row['Bond %']),\n inflation=0 # it is already reported in real terms\n )\n\n def iter_from(self, date, length=None):\n count = 0\n for row in self.data.loc[date:].iterrows():\n yield self.fmt(row[1])\n count += 1\n if length and count >= length:\n raise StopIteration\n\n\nclass Japan_1957:\n def __init__(self):\n self.start_year = 1957\n self.dataframe = pandas.read_csv('japan-1957-2016.csv',\n index_col=0,\n dtype={'Date': int,\n 'CPI Japan': object,\n 'Spliced Bond': object,\n 'NIKKEI225' : object},\n converters={'CPI Japan': Decimal,\n 'Spliced Bond' : Decimal,\n 'NIKKEI225' : Decimal})\n\n def __len__(self):\n return len(self.dataframe)\n\n def random_year(self):\n i = random.randint(0, len(self.dataframe) - 1)\n return self.fmt(self.dataframe.iloc[i])\n\n def fmt(self, row):\n return AnnualChange(\n year=row.name,\n stocks=row['NIKKEI225'],\n bonds=row['Spliced Bond'],\n inflation=row['CPI Japan']\n )\n\n def iter_from(self, year, length=None):\n start = year - 1957\n assert start >= 0\n assert start < 2016\n count = 0\n for row in self.dataframe.iloc[start:].iterrows():\n yield self.fmt(row[1])\n count += 1\n if length and count >= length:\n return\n\nclass Japan_1975:\n def __init__(self):\n self.dataframe = pandas.read_csv('japan-1975-2016.csv',\n index_col=0,\n dtype={'Year': int,\n 'CPI': object,\n 'IT Bond': object,\n 'Equities' : object},\n converters={'CPI': Decimal,\n 'IT Bond' : Decimal,\n 'Equities' : Decimal})\n\n def fmt(self, row):\n return AnnualChange(\n year=row.name,\n stocks=row['Equities'],\n bonds=row['IT Bond'],\n inflation=row['CPI']\n )\n\n def iter_from(self, year, length=None):\n start = year - 1975\n assert start >= 0\n assert start < 2016\n count = 0\n for row in self.dataframe.iloc[start:].iterrows():\n yield self.fmt(row[1])\n count += 1\n if length and count >= length:\n return\n\n\nclass Returns_US_1871:\n def __init__(self, wrap=False):\n # import US based data from 1871 from the simba backtesting\n # spreadsheet found on bogleheads.org\n # https://www.bogleheads.org/forum/viewtopic.php?p=2753812#p2753812\n self.start_year = 1871\n self.dataframe = pandas.read_csv('1871_returns.csv')\n self.years_of_data = len(self.dataframe)\n\n if wrap:\n self.dataframe += self.dataframe\n\n def __len__(self):\n return len(self.dataframe)\n\n def __iter__(self):\n return self.iter_from(1871)\n\n def get_year(self, index):\n return self.dataframe.iloc[index]['Year']\n\n def shuffle(self):\n index = list(self.dataframe.index)\n random.shuffle(index)\n self.dataframe = self.dataframe.ix[index]\n self.dataframe.reset_index()\n return self\n\n def random_year(self):\n i = random.randint(0, len(self.dataframe) - 1)\n return self.fmt(self.dataframe.iloc[i])\n\n def fmt(self, row):\n (stocks, bonds, inflation) = (Decimal(row[x]) / 100 for x in (\"VFINX\", \"IT Bonds\", \"CPI-U\"))\n return AnnualChange(\n year=row['Year'],\n stocks=stocks,\n bonds=bonds,\n inflation=inflation\n )\n\n def iter_from(self, year, length=None):\n start = year - 1871\n assert start >= 0\n assert start < 2016\n count = 0\n for row in self.dataframe.iloc[start:].iterrows():\n yield self.fmt(row[1])\n count += 1\n if length and count >= length:\n return\n"
] |
[
[
"pandas.read_stata",
"pandas.read_csv"
]
] |
Summer0328/Landuse_DL
|
[
"4a3c46979678a089065a02b595022668e60adc50"
] |
[
"multiArea_test/analyze_dataAug_results.py"
] |
[
"#!/usr/bin/env python\n# Filename: analyze_dataAug_results \n\"\"\"\nintroduction:\n\nauthors: Huang Lingcao\nemail:[email protected]\nadd time: 29 March, 2021\n\"\"\"\n\nimport os, sys\ncode_dir = os.path.expanduser('~/codes/PycharmProjects/Landuse_DL')\nsys.path.insert(0, code_dir)\nimport basic_src.io_function as io_function\n\nimport pandas as pd\n\ndef output_max_min_miou(pd_table):\n data_aug_options = pd_table['data_augmentation'].tolist()\n # train_class_0\ttrain_class_1\tval_class_0\tval_class_1\tclass_1\toverall time_total_h\n train_c0_count = pd_table['train_class_0'].tolist()\n train_c1_count = pd_table['train_class_1'].tolist()\n val_c0_count = pd_table['val_class_0'].tolist()\n val_c1_count = pd_table['val_class_1'].tolist()\n mIOU_c1 = pd_table['class_1'].tolist()\n mIOU_overall = pd_table['overall'].tolist()\n total_time = pd_table['time_total_h'].tolist()\n\n # find max and min mIOU for class_1\n max_index = mIOU_c1.index(max(mIOU_c1))\n print('class_1::: mIOU: %f, train_c0_num:%d, train_c1_num:%d, val_c0_count:%d, val_c1_count:%d,'\n 'total_time_h: %f,augmentation option: %s, '%( mIOU_c1[max_index], train_c0_count[max_index], train_c1_count[max_index],\n val_c0_count[max_index], val_c1_count[max_index], total_time[max_index],data_aug_options[max_index],))\n\n min_index = mIOU_c1.index(min(mIOU_c1))\n print('class_1::: mIOU: %f, train_c0_num:%d, train_c1_num:%d, val_c0_count:%d, val_c1_count:%d,'\n 'total_time_h: %f, augmentation option: %s '%( mIOU_c1[min_index], train_c0_count[min_index], train_c1_count[min_index],\n val_c0_count[min_index], val_c1_count[min_index], total_time[min_index],data_aug_options[min_index]))\n\n # find max and min mIOU for overall\n max_index = mIOU_overall.index(max(mIOU_overall))\n print('overall::: mIOU: %f, train_c0_num:%d, train_c1_num:%d, val_c0_count:%d, val_c1_count:%d,'\n 'total_time_h: %f,augmentation option: %s, '%( mIOU_overall[max_index], train_c0_count[max_index], train_c1_count[max_index],\n val_c0_count[max_index], val_c1_count[max_index], total_time[max_index],data_aug_options[max_index],))\n\n min_index = mIOU_overall.index(min(mIOU_overall))\n print('overall::: mIOU: %f, train_c0_num:%d, train_c1_num:%d, val_c0_count:%d, val_c1_count:%d,'\n 'total_time_h: %f, augmentation option: %s '%( mIOU_overall[min_index], train_c0_count[min_index], train_c1_count[min_index],\n val_c0_count[min_index], val_c1_count[min_index], total_time[min_index],data_aug_options[min_index]))\n\ndef output_miou_for_each_dataAug_options(pd_table):\n data_aug_options = pd_table['data_augmentation'].tolist()\n mIOU_c1 = pd_table['class_1'].tolist()\n mIOU_overall = pd_table['overall'].tolist()\n\n aug_options_c1 = {}\n aug_options_overall = {}\n\n for opt, miou_c1, miou_o in zip(data_aug_options, mIOU_c1, mIOU_overall):\n # print(opt, miou_c1, miou_o)\n opt_list = [item.strip() for item in opt.split(',')]\n for aug in opt_list:\n if aug in aug_options_c1.keys():\n aug_options_c1[aug].append(miou_c1)\n else:\n aug_options_c1[aug] = [miou_c1]\n\n if aug in aug_options_overall.keys():\n aug_options_overall[aug].append(miou_o)\n else:\n aug_options_overall[aug] = [miou_o]\n\n for key in aug_options_c1:\n value_ist = aug_options_c1[key]\n print('class_1: exp count: %d, mean, max, and min miou_c1: %f %f %f, aug option: %s'%\n (len(value_ist), sum(value_ist)/len(value_ist), max(value_ist), min(value_ist),key))\n\n for key in aug_options_overall:\n value_ist = aug_options_overall[key]\n print('overall: exp count: %d, mean, max, and min miou_c1: %f %f %f, aug option: %s'%\n (len(value_ist), sum(value_ist)/len(value_ist), max(value_ist), min(value_ist),key))\n\ndef find_info_realted_to_train_dir(train_val_table, train_dir, info_key):\n folder_list = train_val_table['folder'].tolist()\n info_list = train_val_table[info_key].tolist()\n for dir, info in zip(folder_list, info_list):\n if dir == train_dir:\n return info\n\n return None\n\ndef output_mean_max_miou_all_test_data(test_xlsx_list, train_val_table):\n\n mean_miou_c1_each_test = {}\n max_miou_c1_each_test = {}\n max_miou_c1_test_aug_options = {}\n for xlsx in test_xlsx_list:\n print(xlsx)\n test_pd_table = pd.read_excel(xlsx)\n miou_c1_list = test_pd_table['class_1'].tolist()\n train_dir_list = test_pd_table['train_dir'].tolist()\n key = os.path.splitext(os.path.basename(xlsx))[0]\n mean_miou_c1_each_test[key] = sum(miou_c1_list)/len(miou_c1_list)\n max_miou_c1_each_test[key] = max(miou_c1_list)\n\n # get trianing_dir\n max_idx = miou_c1_list.index(max_miou_c1_each_test[key])\n train_dir = train_dir_list[max_idx]\n data_aug_options = find_info_realted_to_train_dir(train_val_table,train_dir,'data_augmentation')\n max_miou_c1_test_aug_options[key] = data_aug_options\n\n key_list = list(mean_miou_c1_each_test.keys())\n key_list.sort()\n mean_list = []\n max_list = []\n aug_option_list = []\n for key in key_list:\n print('%s mean miou c1: %f, max miou c1: %f'%(key, mean_miou_c1_each_test[key], max_miou_c1_each_test[key]))\n mean_list.append(mean_miou_c1_each_test[key])\n max_list.append(max_miou_c1_each_test[key])\n aug_option_list.append(max_miou_c1_test_aug_options[key])\n\n\n # data augmentation count:\n data_option_count = {}\n for key in key_list:\n opt_list = [ item.strip() for item in max_miou_c1_test_aug_options[key].split(',')]\n for opt in opt_list:\n if opt in data_option_count.keys():\n data_option_count[opt] += 1\n else:\n data_option_count[opt] = 1\n\n print(data_option_count)\n\n save_dict = {'test_images':key_list, 'mean_miou_class_1':mean_list,\n 'max_miou_class_1':max_list, 'max_miou_aug_options':aug_option_list}\n\n save_dict_pd = pd.DataFrame(save_dict)\n with pd.ExcelWriter('miou_mean_max_test_data.xlsx') as writer:\n save_dict_pd.to_excel(writer, sheet_name='table')\n\n print(\"save to %s\"%'miou_mean_max_test_data.xlsx')\n\ndef main():\n # miou for the validation data (10%)\n dataAug_table = pd.read_excel(dataAug_res_WR)\n # output_max_min_miou(dataAug_table)\n # output_miou_for_each_dataAug_options(dataAug_table)\n\n # miou for test data (different dates)\n output_mean_max_miou_all_test_data(test_dataAug_res_WR_list,dataAug_table)\n\n\n pass\n\nif __name__ == '__main__':\n\n # 255 experiments of data augmentation result, mIOU for class_1 and overall\n dataAug_res_WR = os.path.expanduser('~/Data/Arctic/canada_arctic/autoMapping/tune_dataAug_para_tesia.xlsx')\n\n # Apply each trained model (255 ones) to other images acquired in 2020 but different dates (not entire images,\n # but only the subImages extracted from training polygons)\n test_dataAug_res_WR_dir = os.path.expanduser('~/Data/Arctic/canada_arctic/autoMapping/eval_on_multi_datasets')\n test_dataAug_res_WR_list = io_function.get_file_list_by_ext('.xlsx',test_dataAug_res_WR_dir, bsub_folder=False)\n\n main()\n\n pass\n\n\n\n"
] |
[
[
"pandas.read_excel",
"pandas.DataFrame",
"pandas.ExcelWriter"
]
] |
mehrdad-shokri/tvm
|
[
"86d5de6a166922d1422d24d252d9190f94a32176"
] |
[
"topi/tests/python/test_topi_reduce.py"
] |
[
"\"\"\"Test code for reduce.\"\"\"\nimport os\nimport numpy as np\nimport tvm\nimport topi\n\ndef _my_npy_argmax(arr, axis, keepdims):\n if not keepdims:\n return arr.argmax(axis=axis)\n else:\n if axis is not None:\n out_shape = list(arr.shape)\n out_shape[axis] = 1\n else:\n out_shape = [1 for _ in range(len(arr.shape))]\n return arr.argmax(axis=axis).reshape(out_shape)\n\n\ndef _my_npy_argmin(arr, axis, keepdims):\n if not keepdims:\n return arr.argmin(axis=axis)\n else:\n out_shape = list(arr.shape)\n out_shape[axis] = 1\n return arr.argmin(axis=axis).reshape(out_shape)\n\n\ndef verify_reduce_map_ele(in_shape, axis, keepdims, type=\"sum\"):\n # Build the logic and compile the function\n dat_dtype = \"float32\"\n A = tvm.placeholder(shape=in_shape, name=\"A\", dtype=dat_dtype)\n A1 = topi.sqrt(topi.exp(A))\n out_dtype = \"float32\"\n if type == \"sum\":\n B = topi.sum(A1, axis=axis, keepdims=keepdims)\n elif type == \"max\":\n B = topi.max(A1, axis=axis, keepdims=keepdims)\n elif type == \"min\":\n B = topi.min(A1, axis=axis, keepdims=keepdims)\n elif type == \"argmax\":\n B = topi.argmax(A1, axis=axis, keepdims=keepdims)\n out_dtype = \"int32\"\n elif type == \"argmin\":\n B = topi.argmin(A1, axis=axis, keepdims=keepdims)\n out_dtype = \"int32\"\n else:\n raise NotImplementedError\n\n def check_device(device):\n if not tvm.module.enabled(device):\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n with tvm.target.create(device):\n s = topi.generic.schedule_reduce(B)\n ctx = tvm.context(device, 0)\n foo = tvm.build(s, [A, B], device, name=\"sum\")\n # Test\n in_npy = np.random.uniform(size=in_shape).astype(np.float32)\n in_npy_map = np.sqrt(np.exp(in_npy)).astype(np.float32)\n if type == \"sum\":\n out_npy = in_npy_map.sum(axis=axis, keepdims=keepdims)\n elif type == \"max\":\n out_npy = in_npy_map.max(axis=axis, keepdims=keepdims)\n elif type == \"min\":\n out_npy = in_npy_map.min(axis=axis, keepdims=keepdims)\n elif type == \"argmax\":\n out_npy = _my_npy_argmax(in_npy_map, axis=axis, keepdims=keepdims)\n elif type == \"argmin\":\n out_npy = _my_npy_argmin(in_npy_map, axis=axis, keepdims=keepdims)\n else:\n raise NotImplementedError\n data_tvm = tvm.nd.array(in_npy, ctx=ctx)\n out_tvm = tvm.nd.empty(shape=out_npy.shape, ctx=ctx, dtype=out_dtype)\n for _ in range(1):\n foo(data_tvm, out_tvm)\n np.testing.assert_allclose(out_tvm.asnumpy(), out_npy, 1E-3, 1E-3)\n for device in [\"cuda\", \"opencl\", \"metal\", \"llvm\", \"rocm\"]:\n check_device(device)\n\n\ndef test_reduce_map():\n verify_reduce_map_ele(in_shape=(128, 24, 128, 24),\n axis=(1, 2, 3),\n keepdims=True,\n type=\"sum\")\n verify_reduce_map_ele(in_shape=(128, 24 * 128 * 24),\n axis=(1,),\n keepdims=False,\n type=\"max\")\n verify_reduce_map_ele(in_shape=(32, 128, 24),\n axis=None,\n keepdims=True,\n type=\"sum\")\n verify_reduce_map_ele(in_shape=(128, 24, 128, 24),\n axis=(0, 2),\n keepdims=False,\n type=\"min\")\n verify_reduce_map_ele(in_shape=(32, 128),\n axis=1,\n keepdims=True,\n type=\"argmax\")\n verify_reduce_map_ele(in_shape=(32, 24, 32, 24),\n axis=2,\n keepdims=False,\n type=\"argmin\")\n verify_reduce_map_ele(in_shape=(31, 21, 15),\n axis=None,\n keepdims=True,\n type=\"argmax\")\n verify_reduce_map_ele(in_shape=(31, 21, 15),\n axis=None,\n keepdims=False,\n type=\"sum\")\n\nif __name__ == \"__main__\":\n test_reduce_map()\n"
] |
[
[
"numpy.random.uniform",
"numpy.exp"
]
] |
Wanggcong/SolutionSimilarityLearning
|
[
"26279b61686b3c34745c369b2cc4175c71c55403"
] |
[
"models/rnn.py"
] |
[
"import torch\r\nimport torch.nn as nn\r\nfrom torch.autograd import Variable\r\n\r\n\r\nclass RNN(nn.Module):\r\n def __init__(self, input_size, hidden_size, output_size, num_layers=2):\r\n super(RNN, self).__init__()\r\n self.hidden_size = hidden_size\r\n self.num_layers = num_layers\r\n self.fc = nn.Linear(hidden_size, output_size)\r\n self.softmax = nn.LogSoftmax()\r\n self.rnn = nn.GRU(input_size, hidden_size, self.num_layers)\r\n\r\n def forward(self, x, h0):\r\n x, hn = self.rnn(x, h0)\r\n x = self.fc(x[x.size(0)-1,:,:])\r\n x = self.softmax(x)\r\n return x\r\n def initHidden(self):\r\n return Variable(torch.zeros(self.num_layers, 1, self.hidden_size))\r\n\r\n def initCell(self):\r\n return Variable(torch.zeros(self.num_layers, 1, self.hidden_size))\r\n\r\n\r\n"
] |
[
[
"torch.nn.GRU",
"torch.nn.Linear",
"torch.nn.LogSoftmax",
"torch.zeros"
]
] |
shubhambhokare1/vision
|
[
"2fe0c2d0b2108440ec5efbf297d48cf26d0d8624"
] |
[
"torchvision/prototype/transforms/_augment.py"
] |
[
"import math\nimport numbers\nimport warnings\nfrom typing import Any, Dict, Tuple\n\nimport torch\nfrom torchvision.prototype.transforms import Transform, functional as F\n\nfrom ._utils import query_image\n\n\nclass RandomErasing(Transform):\n _DISPATCHER = F.erase\n\n def __init__(\n self,\n p: float = 0.5,\n scale: Tuple[float, float] = (0.02, 0.33),\n ratio: Tuple[float, float] = (0.3, 3.3),\n value: float = 0,\n ):\n super().__init__()\n if not isinstance(value, (numbers.Number, str, tuple, list)):\n raise TypeError(\"Argument value should be either a number or str or a sequence\")\n if isinstance(value, str) and value != \"random\":\n raise ValueError(\"If value is str, it should be 'random'\")\n if not isinstance(scale, (tuple, list)):\n raise TypeError(\"Scale should be a sequence\")\n if not isinstance(ratio, (tuple, list)):\n raise TypeError(\"Ratio should be a sequence\")\n if (scale[0] > scale[1]) or (ratio[0] > ratio[1]):\n warnings.warn(\"Scale and ratio should be of kind (min, max)\")\n if scale[0] < 0 or scale[1] > 1:\n raise ValueError(\"Scale should be between 0 and 1\")\n if p < 0 or p > 1:\n raise ValueError(\"Random erasing probability should be between 0 and 1\")\n # TODO: deprecate p in favor of wrapping the transform in a RandomApply\n self.p = p\n self.scale = scale\n self.ratio = ratio\n self.value = value\n\n def _get_params(self, sample: Any) -> Dict[str, Any]:\n image = query_image(sample)\n img_h, img_w = F.get_image_size(image)\n img_c = F.get_image_num_channels(image)\n\n if isinstance(self.value, (int, float)):\n value = [self.value]\n elif isinstance(self.value, str):\n value = None\n elif isinstance(self.value, tuple):\n value = list(self.value)\n else:\n value = self.value\n\n if value is not None and not (len(value) in (1, img_c)):\n raise ValueError(\n f\"If value is a sequence, it should have either a single value or {img_c} (number of input channels)\"\n )\n\n area = img_h * img_w\n\n log_ratio = torch.log(torch.tensor(self.ratio))\n for _ in range(10):\n erase_area = area * torch.empty(1).uniform_(self.scale[0], self.scale[1]).item()\n aspect_ratio = torch.exp(\n torch.empty(1).uniform_(\n log_ratio[0], # type: ignore[arg-type]\n log_ratio[1], # type: ignore[arg-type]\n )\n ).item()\n\n h = int(round(math.sqrt(erase_area * aspect_ratio)))\n w = int(round(math.sqrt(erase_area / aspect_ratio)))\n if not (h < img_h and w < img_w):\n continue\n\n if value is None:\n v = torch.empty([img_c, h, w], dtype=torch.float32).normal_()\n else:\n v = torch.tensor(value)[:, None, None]\n\n i = torch.randint(0, img_h - h + 1, size=(1,)).item()\n j = torch.randint(0, img_w - w + 1, size=(1,)).item()\n break\n else:\n i, j, h, w, v = 0, 0, img_h, img_w, image\n\n return dict(zip(\"ijhwv\", (i, j, h, w, v)))\n\n def _transform(self, input: Any, params: Dict[str, Any]) -> Any:\n if torch.rand(1) >= self.p:\n return input\n\n return super()._transform(input, params)\n\n\nclass RandomMixup(Transform):\n _DISPATCHER = F.mixup\n\n def __init__(self, *, alpha: float) -> None:\n super().__init__()\n self.alpha = alpha\n self._dist = torch.distributions.Beta(torch.tensor([alpha]), torch.tensor([alpha]))\n\n def _get_params(self, sample: Any) -> Dict[str, Any]:\n return dict(lam=float(self._dist.sample(())))\n\n\nclass RandomCutmix(Transform):\n _DISPATCHER = F.cutmix\n\n def __init__(self, *, alpha: float) -> None:\n super().__init__()\n self.alpha = alpha\n self._dist = torch.distributions.Beta(torch.tensor([alpha]), torch.tensor([alpha]))\n\n def _get_params(self, sample: Any) -> Dict[str, Any]:\n lam = float(self._dist.sample(()))\n\n image = query_image(sample)\n H, W = F.get_image_size(image)\n\n r_x = torch.randint(W, ())\n r_y = torch.randint(H, ())\n\n r = 0.5 * math.sqrt(1.0 - lam)\n r_w_half = int(r * W)\n r_h_half = int(r * H)\n\n x1 = int(torch.clamp(r_x - r_w_half, min=0))\n y1 = int(torch.clamp(r_y - r_h_half, min=0))\n x2 = int(torch.clamp(r_x + r_w_half, max=W))\n y2 = int(torch.clamp(r_y + r_h_half, max=H))\n box = (x1, y1, x2, y2)\n\n lam_adjusted = float(1.0 - (x2 - x1) * (y2 - y1) / (W * H))\n\n return dict(box=box, lam_adjusted=lam_adjusted)\n"
] |
[
[
"torch.randint",
"torch.empty",
"torch.tensor",
"torch.rand",
"torch.clamp"
]
] |
colfrog/deepsnek-py
|
[
"6731f91e2b65fa7f09b624c21017a10f64a07cc9"
] |
[
"dqn_agent.py"
] |
[
"import random\nimport math\nfrom collections import deque, namedtuple\nfrom tensorflow import keras\nimport numpy as np\n\ndef max_index(array):\n\tmaxval = None\n\tmaxindex = 0\n\tfor i in range(len(array)):\n\t\ttry:\n\t\t\ttest = iter(array[i])\n\t\t\t_, val = max_index(array[i])\n\t\texcept TypeError:\n\t\t\tval = array[i]\n\n\t\tif maxval is None or val > maxval:\n\t\t\tmaxindex, maxval = i, val\n\n\treturn maxindex, maxval\n\nclass EpsilonGreedy():\n\tdef __init__(self, start, end, decay):\n\t\tself.epsilon = start\n\t\tself.start = start\n\t\tself.end = end\n\t\tself.decay = decay\n\t\tself.steps = 0\n\n\tdef update(self):\n\t\tself.steps += 1\n\t\tself.epsilon = self.end + (self.start - self.end)*math.exp(-self.steps*self.decay)\n\nexperience = namedtuple('experience', ['state', 'next_state', 'action', 'reward'])\nclass DQN_Agent():\n\tmemory = deque([])\n\tdef __init__(self, q_net,\n\t\tepsilon = EpsilonGreedy(1, 0.1, 0.00005),\n\t\tdiscount_factor = 0.1,\n\t\tlearning_rate = 1,\n\t\tbatch_size = 32,\n\t\tmemory_len = 1000,\n steps_to_target_net_update = 100):\n\t\tself.epsilon = epsilon\n\t\tself.discount_factor = discount_factor\n\t\tself.learning_rate = learning_rate\n\t\tself.batch_size = batch_size\n\t\tself.memory_len = memory_len\n\t\tself.steps_to_target_net_update = steps_to_target_net_update\n\t\tself.q_net = q_net\n\t\tself.target_net = keras.models.clone_model(self.q_net)\n\t\tself.update_target_network()\n\n\tdef step(self, action):\n\t\treturn\n\n\tdef reinit_env(self):\n\t\treturn\n\n\tdef train_q_network(self, states, targets):\n\t\tself.q_net.train_on_batch(states, targets)\n\t\n\tdef update_target_network(self):\n\t\tself.target_net.set_weights(self.q_net.get_weights())\n\n\tdef explore_action(self):\n\t\treturn random.randrange(0, self.nactions)\n\t\n\tdef exploit_action(self, state):\n\t\tout = self.q_net.predict(state)[0]\n\t\treturn max_index(out)[0]\n\n\tdef get_action(self, state):\n\t\tn = random.randrange(0, 100)/100\n\t\tif n < self.epsilon.epsilon:\n\t\t\treturn self.explore_action()\n\t\telse:\n\t\t\treturn self.exploit_action(state)\n\n\tdef sort_sample(self, sample):\n\t\tstates = np.zeros((len(sample), sample[0].state.shape[1]))\n\t\ttargets = np.zeros((len(sample), 3))\n\n\t\ti = 0\n\t\tfor e in sample:\n\t\t\tstates[i] = e.state[0]\n\n\t\t\tif e.next_state is None:\n\t\t\t\tnext_max_q = 0\n\t\t\telse:\n\t\t\t\tnext_max_q = np.max(self.target_net.predict(e.next_state))\n\n\t\t\ttarget = self.q_net.predict(e.state)[0]\n\t\t\ttarget[e.action] = e.reward + self.discount_factor*next_max_q\n\t\t\ttargets[i] = target\n\n\t\treturn states, targets\n\n\tdef teach_sample(self):\n\t\tsample = random.sample(self.memory, self.batch_size)\n\t\tstates, targets = self.sort_sample(sample)\n\t\tself.train_q_network(states, targets)\n\n\tdef train(self, initial_state, min_steps = 0, max_steps = 15000):\n\t\ti = 0\n\t\tnext_state = initial_state\n\t\tself.update_target_network()\n\n\t\twhile next_state is not None:\n\t\t\tstate = next_state\n\t\t\taction = self.get_action(state)\n\t\t\tnext_state, reward = self.step(action)\n\t\t\te = experience(state, next_state, action, reward)\n\n\t\t\tif i%self.steps_to_target_net_update:\n\t\t\t\tself.update_target_network()\n\n\t\t\tself.memory.append(e)\n\t\t\tif len(self.memory) > self.memory_len:\n\t\t\t\tself.memory.popleft()\n\t\t\t\tself.epsilon.update()\n\t\t\t\tself.teach_sample()\n\n\t\t\ti += 1\n\t\t\tif i <= min_steps and next_state is None:\n\t\t\t\tnext_state = self.reinit_env()\n\t\t\tif i > max_steps:\n\t\t\t\treturn\n\n\tdef run(self, initial_state):\n\t\tnext_state = initial_state\n\t\twhile next_state is not None:\n\t\t\tstate = next_state\n\t\t\taction = self.exploit_action(state)\n\t\t\tnext_state, reward = self.step(action)\n"
] |
[
[
"tensorflow.keras.models.clone_model"
]
] |
hassan11196/Torch-TensorRT
|
[
"a2d0d0e935bf223523a7c28d7814cdbd32f323b2",
"a2d0d0e935bf223523a7c28d7814cdbd32f323b2"
] |
[
"py/torch_tensorrt/fx/test/converters/acc_op/test_any.py",
"py/torch_tensorrt/fx/tracer/acc_tracer/acc_ops.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch_tensorrt.fx.tracer.acc_tracer.acc_ops as acc_ops\nfrom parameterized import parameterized\nfrom torch.testing._internal.common_fx2trt import AccTestCase\nfrom torch.testing._internal.common_utils import run_tests\n\n\nclass TestAnyConverters(AccTestCase):\n @parameterized.expand(\n [\n (\"bool\", torch.bool),\n (\"int\", torch.int),\n (\"float\", torch.float),\n ]\n )\n def test_ops(self, _, input_dtype):\n class TestModule(nn.Module):\n def forward(self, x):\n return torch.any(x)\n\n inputs = [torch.randn(2, 3).to(input_dtype)]\n self.run_test(\n TestModule(),\n inputs,\n expected_ops={acc_ops.any},\n test_implicit_batch_dim=False,\n )\n\n @parameterized.expand(\n [\n (\"bool\", torch.bool, 0),\n (\"int\", torch.int, 1),\n (\"float\", torch.float, 0),\n ]\n )\n def test_ops_dim(self, _, input_dtype, dim):\n class TestModule(nn.Module):\n def forward(self, x):\n return torch.any(x, dim, keepdim=True)\n\n inputs = [torch.randn(2, 3).to(input_dtype)]\n self.run_test(\n TestModule(), inputs, expected_ops={}, test_implicit_batch_dim=False\n )\n\n @parameterized.expand(\n [\n (\"bool\", torch.bool),\n (\"int\", torch.int),\n (\"float\", torch.float),\n ]\n )\n def test_ops_method(self, _, input_dtype):\n class TestModule(nn.Module):\n def forward(self, x):\n return x.any()\n\n inputs = [torch.randn(2, 3).to(input_dtype)]\n self.run_test(\n TestModule(),\n inputs,\n expected_ops={acc_ops.any},\n test_implicit_batch_dim=False,\n )\n\n\nif __name__ == \"__main__\":\n run_tests()\n",
"# encoding: utf-8\nimport operator\nimport warnings\n\nimport torch # isort:skip\nfrom typing import cast, Iterable, List, Sequence\n\nimport torch.nn as nn\nfrom torch.fx.passes.shape_prop import _extract_tensor_metadata\n\nfrom . import acc_utils\nfrom .acc_normalizer import (\n register_acc_op,\n register_acc_op_mapping,\n register_custom_acc_mapper_fn,\n)\nfrom .acc_op_properties import AccOpProperty, register_acc_op_properties\n\nthis_arg_is_optional = True\nmove_to_qparams = True\ndont_move_to_qparams = False\n\n\n@register_acc_op_mapping(op_and_target=(\"call_function\", nn.functional.linear))\n@register_acc_op\ndef linear(*, input, weight, bias):\n return nn.functional.linear(input=input, weight=weight, bias=bias)\n\n\n@register_acc_op_properties(AccOpProperty.quantized)\n@register_acc_op\ndef quantized_linear(*, input, weight, bias, acc_out_ty=None):\n assert acc_out_ty is not None\n qparams = acc_out_ty.qparams\n return nn.quantized.functional.linear(\n input,\n weight,\n bias,\n qparams[\"scale\"],\n qparams[\"zero_point\"],\n )\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op_mapping(\n op_and_target=(\"call_method\", \"flatten\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"start_dim\", \"start_dim\", this_arg_is_optional),\n (\"end_dim\", \"end_dim\", this_arg_is_optional),\n ],\n)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.flatten))\n@register_acc_op\ndef flatten(*, input, start_dim=0, end_dim=-1):\n return torch.flatten(input=input, start_dim=start_dim, end_dim=end_dim)\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op_mapping(\n op_and_target=(\"call_method\", \"squeeze\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim\", \"dim\", this_arg_is_optional),\n ],\n)\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.squeeze),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim\", \"dim\", this_arg_is_optional),\n ],\n)\n@register_acc_op\ndef squeeze(*, input, dim=None):\n if dim is None:\n return input.squeeze()\n return input.squeeze(dim=dim)\n\n\n@register_acc_op_mapping(op_and_target=(\"call_function\", nn.functional.embedding))\n@register_acc_op\ndef embedding(\n *,\n input,\n weight,\n padding_idx,\n max_norm,\n norm_type,\n scale_grad_by_freq,\n sparse,\n):\n return torch.nn.functional.embedding(**locals())\n\n\n@register_acc_op_mapping(op_and_target=(\"call_function\", nn.functional.max_pool1d))\n@register_acc_op\ndef max_pool1d(\n *,\n input,\n kernel_size,\n stride,\n padding,\n dilation,\n ceil_mode,\n return_indices,\n):\n return nn.functional.max_pool1d(\n input=input,\n kernel_size=kernel_size,\n stride=stride,\n padding=padding,\n dilation=dilation,\n ceil_mode=ceil_mode,\n return_indices=return_indices,\n )\n\n\n@register_acc_op_mapping(op_and_target=(\"call_function\", nn.functional.max_pool2d))\n@register_acc_op\ndef max_pool2d(\n *,\n input,\n kernel_size,\n stride,\n padding,\n dilation,\n ceil_mode,\n return_indices,\n):\n return nn.functional.max_pool2d(\n input=input,\n kernel_size=kernel_size,\n stride=stride,\n padding=padding,\n dilation=dilation,\n ceil_mode=ceil_mode,\n return_indices=return_indices,\n )\n\n\n@register_acc_op_mapping(op_and_target=(\"call_function\", nn.functional.max_pool3d))\n@register_acc_op\ndef max_pool3d(\n *, input, kernel_size, stride, padding, dilation, ceil_mode, return_indices\n):\n return nn.functional.max_pool3d(\n input=input,\n kernel_size=kernel_size,\n stride=stride,\n padding=padding,\n dilation=dilation,\n ceil_mode=ceil_mode,\n return_indices=return_indices,\n )\n\n\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", nn.functional.adaptive_avg_pool2d)\n)\n@register_acc_op\ndef adaptive_avg_pool2d(*, input, output_size):\n return nn.functional.adaptive_avg_pool2d(input=input, output_size=output_size)\n\n\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", nn.functional.adaptive_avg_pool3d)\n)\n@register_acc_op\ndef adaptive_avg_pool3d(*, input, output_size):\n return nn.functional.adaptive_avg_pool3d(input=input, output_size=output_size)\n\n\n@register_acc_op_mapping(op_and_target=(\"call_function\", nn.functional.avg_pool1d))\n@register_acc_op\ndef avg_pool1d(\n *,\n input,\n kernel_size,\n stride,\n padding,\n ceil_mode,\n count_include_pad,\n):\n return nn.functional.avg_pool1d(\n input=input,\n kernel_size=kernel_size,\n stride=stride,\n padding=padding,\n ceil_mode=ceil_mode,\n count_include_pad=count_include_pad,\n )\n\n\n@register_acc_op_mapping(op_and_target=(\"call_function\", nn.functional.avg_pool2d))\n@register_acc_op\ndef avg_pool2d(\n *,\n input,\n kernel_size,\n stride,\n padding,\n ceil_mode,\n count_include_pad,\n divisor_override,\n):\n return nn.functional.avg_pool2d(\n input=input,\n kernel_size=kernel_size,\n stride=stride,\n padding=padding,\n ceil_mode=ceil_mode,\n count_include_pad=count_include_pad,\n divisor_override=divisor_override,\n )\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.sign))\n@register_acc_op\ndef sign(*, input):\n return torch.sign(input)\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"type\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dtype\", \"dtype\", this_arg_is_optional),\n ],\n)\ndef custom_type_mapper(node: torch.fx.Node, _: nn.Module) -> torch.fx.Node:\n input_obj = node.kwargs[\"input\"]\n dtype_obj = node.kwargs.get(\"dtype\")\n with node.graph.inserting_before(node):\n if dtype_obj == None:\n dtype_node = node.graph.call_function(dtype, kwargs={\"input\": input_obj})\n dtype_node.meta[\"type\"] = torch.dtype\n return dtype_node\n else:\n new_kwargs = {\n \"input\": input_obj,\n \"acc_out_ty\": acc_utils.build_raw_tensor_meta(dtype=dtype_obj),\n }\n new_node = node.graph.call_function(to_dtype, kwargs=new_kwargs)\n new_node.meta = node.meta\n return new_node\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"type_as\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"tensor\", \"tensor\"),\n ],\n)\ndef custom_type_as_mapper(node: torch.fx.Node, _: nn.Module) -> torch.fx.Node:\n input_obj = node.kwargs[\"input\"]\n other_obj = node.kwargs[\"tensor\"]\n with node.graph.inserting_before(node):\n dtype_node = node.graph.call_function(dtype, kwargs={\"input\": other_obj})\n dtype_node.meta[\"type\"] = torch.dtype\n device_node = node.graph.call_function(device, kwargs={\"input\": other_obj})\n device_node.meta[\"type\"] = torch.device\n\n new_kwargs = {\n \"input\": input_obj,\n \"acc_out_ty\": acc_utils.build_raw_tensor_meta(dtype=dtype_node),\n \"device\": device_node,\n }\n new_node = node.graph.call_function(to_dtype, kwargs=new_kwargs)\n new_node.meta = node.meta\n return new_node\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op\ndef dtype(*, input):\n return input.dtype\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op\ndef size(*, input):\n return input.size()\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op\ndef device(*, input):\n return input.device\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.numel))\n@register_acc_op\ndef numel(*, input):\n return torch.numel(input)\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", getattr),\n arg_replacement_tuples=[],\n)\ndef custom_getattr_mapper(node: torch.fx.Node, _: nn.Module) -> torch.fx.Node:\n \"\"\"\n Custom function for mapping a call_function getattr to other ops. Currently only\n supports loading a getattr called on a torch.Tensor with attr name \"shape\", which is\n supported by mapping it to acc_ops.size().\n \"\"\"\n # Have to use args here since getattr forces positional args.\n input_obj = node.args[0]\n attr_name = node.args[1]\n assert isinstance(input_obj, torch.fx.Node)\n assert (\n input_obj.meta[\"type\"] == torch.Tensor\n ), f\"Expected torch.Tensor type for {input_obj.meta['type']}\"\n assert (\n attr_name == \"shape\" or attr_name == \"device\" or attr_name == \"dtype\"\n ), f\"Only supporting shape, device and dtype getattr for now, not {attr_name}\"\n if attr_name == \"shape\":\n func = size\n elif attr_name == \"device\":\n func = device\n elif attr_name == \"dtype\":\n func = dtype\n with node.graph.inserting_before(node):\n size_node = node.graph.call_function(func, kwargs={\"input\": input_obj})\n size_node.meta = node.meta.copy()\n return size_node\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"size\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim\", \"dim\", this_arg_is_optional),\n ],\n)\ndef tensor_size_mapper(node: torch.fx.Node, _: nn.Module) -> torch.fx.Node:\n \"\"\"\n Mapping from Tensor.size() to acc_ops.size. We map size() to acc_ops.size directly\n and map size(dim) to acc_ops.size + acc_ops.getitem.\n \"\"\"\n\n with node.graph.inserting_before(node):\n size_node = node.graph.call_function(\n size, kwargs={\"input\": node.kwargs[\"input\"]}\n )\n\n if \"dim\" not in node.kwargs:\n size_node.meta = node.meta.copy()\n return size_node\n\n size_node.meta[\"type\"] = torch.Size\n getitem_node = node.graph.call_function(\n getitem, kwargs={\"input\": size_node, \"idx\": node.kwargs[\"dim\"]}\n )\n getitem_node.meta = node.meta.copy()\n return getitem_node\n\n\n@register_acc_op_properties(AccOpProperty.pointwise)\n@register_acc_op_mapping(op_and_target=(\"call_function\", operator.add))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"add\"))\n@register_acc_op\ndef add(*, input, other):\n return input + other\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"unsqueeze\"))\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.unsqueeze))\n@register_acc_op\ndef unsqueeze(*, input, dim):\n return torch.unsqueeze(input=input, dim=dim)\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"tile\"))\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.tile))\n@register_acc_op\ndef tile(*, input, dims):\n return torch.tile(input=input, dims=dims)\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"repeat\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"*\", \"sizes\"),\n ],\n)\ndef repeat_mapper(node: torch.fx.Node, _: nn.Module) -> torch.fx.Node:\n \"\"\"\n Map repeat to tile.\n \"\"\"\n with node.graph.inserting_before(node):\n inputs = node.kwargs[\"input\"]\n dims = node.kwargs[\"sizes\"]\n new_node = node.graph.create_node(\n \"call_function\",\n tile,\n kwargs={\"input\": inputs, \"dims\": dims},\n name=f\"{node.name}_repeat_map\",\n )\n new_node.meta = node.meta.copy()\n return new_node\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"repeat_interleave\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"repeats\", \"repeats\"),\n (\"dim\", \"dim\", this_arg_is_optional),\n (\"output_size\", \"output_size\", this_arg_is_optional),\n ],\n)\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", torch.repeat_interleave),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"repeats\", \"repeats\"),\n (\"dim\", \"dim\", this_arg_is_optional),\n (\"output_size\", \"output_size\", this_arg_is_optional),\n ],\n)\ndef repeat_interleave_mapper(node: torch.fx.Node, _: nn.Module):\n input_node = node.kwargs[\"input\"]\n repeats = cast(int, node.kwargs[\"repeats\"])\n dim = node.kwargs[\"dim\"]\n assert (\n type(repeats) is int\n ), \"We currently only support `repeat_interleave` with int repeats\"\n rank = node.meta[\"tensor_rank\"]\n if dim is None:\n repeat_dim = rank - 1\n else:\n assert type(dim) is int, \"dim should be an int\"\n repeat_dim = dim\n tile_dims = [1] * (rank + 1)\n tile_dims[repeat_dim + 1] = repeats\n\n with node.graph.inserting_before(node):\n unsqueeze_node = node.graph.create_node(\n \"call_function\",\n unsqueeze,\n kwargs={\"input\": input_node, \"dim\": repeat_dim + 1},\n name=f\"{node.name}_unsqueeze\",\n )\n tile_node = node.graph.create_node(\n \"call_function\",\n tile,\n kwargs={\"input\": unsqueeze_node, \"dims\": tile_dims},\n name=f\"{node.name}_repeat_interleave_map_tile\",\n )\n new_shape = []\n if dim is not None:\n if dim < 0:\n repeat_dim = dim + rank\n else:\n repeat_dim = dim\n size_node = node.graph.create_node(\n \"call_function\",\n size,\n kwargs={\"input\": input_node},\n name=f\"{node.name}_size\",\n )\n size_node.meta[\"type\"] = torch.Size\n for i in range(rank):\n shape_i = node.graph.create_node(\n \"call_function\",\n getitem,\n kwargs={\"input\": size_node, \"idx\": i},\n name=f\"{node.name}_size_{i}\",\n )\n if i == repeat_dim:\n new_shape.append(-1)\n else:\n new_shape.append(shape_i)\n else:\n new_shape.append(-1)\n\n reshaped_node = node.graph.create_node(\n \"call_function\",\n reshape,\n kwargs={\n \"input\": tile_node,\n \"acc_out_ty\": acc_utils.build_raw_tensor_meta(shape=new_shape),\n },\n name=f\"{node.name}_reshape\",\n )\n reshaped_node.meta = node.meta.copy()\n return reshaped_node\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", torch.stack),\n arg_replacement_tuples=[\n (\"tensors\", \"tensors\"),\n (\"dim\", \"dim\"),\n ],\n)\ndef stack_mapper(node: torch.fx.Node, _: nn.Module) -> torch.fx.Node:\n \"\"\"\n Map torch.stack to unsqueeze + cat.\n \"\"\"\n with node.graph.inserting_before(node):\n inputs = node.kwargs[\"tensors\"]\n unsqueeze_nodes = []\n assert isinstance(inputs, Sequence)\n for i, t in enumerate(inputs):\n new_node = node.graph.create_node(\n \"call_function\",\n unsqueeze,\n kwargs={\"input\": t, \"dim\": node.kwargs[\"dim\"]},\n name=f\"{node.name}_unsqueeze_{i}\",\n )\n new_node.meta[\"type\"] = torch.Tensor\n unsqueeze_nodes.append(new_node)\n cat_node = node.graph.create_node(\n \"call_function\",\n cat,\n kwargs={\"tensors\": unsqueeze_nodes, \"dim\": node.kwargs[\"dim\"]},\n )\n cat_node.meta = node.meta.copy()\n return cat_node\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.clamp))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"clamp\"))\n@register_acc_op\ndef clamp(*, input, min=None, max=None):\n return torch.clamp(input=input, min=min, max=max)\n\n\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.cat))\n@register_acc_op\ndef cat(*, tensors, dim):\n return torch.cat(tensors=tensors, dim=dim)\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", torch.transpose),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim0\", \"dim0\"),\n (\"dim1\", \"dim1\"),\n ],\n)\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"transpose\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim0\", \"dim0\"),\n (\"dim1\", \"dim1\"),\n ],\n)\ndef transpose_mapper(node: torch.fx.Node, _: nn.Module) -> torch.fx.Node:\n # Get the dim-permutation/shuffle\n ranks = node.meta[\"tensor_rank\"]\n shuffle = list(range(ranks))\n dim0 = cast(int, node.kwargs[\"dim0\"])\n dim1 = cast(int, node.kwargs[\"dim1\"])\n shuffle[dim0] = dim1\n shuffle[dim1] = dim0\n\n # Create the new acc_ops.permute node. Update all uses of the transpose\n # node and then delete the transpose node.\n with node.graph.inserting_after(node):\n permute_node = node.graph.call_function(\n the_function=permute,\n kwargs={\n \"input\": node.kwargs.get(\"input\"),\n \"permutation\": shuffle,\n },\n )\n permute_node.meta = node.meta.copy()\n node.replace_all_uses_with(permute_node)\n\n permute_node.graph.erase_node(node)\n return permute_node\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"contiguous\"))\n@register_acc_op\ndef contiguous(*, input):\n return input.contiguous()\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op_mapping(\n op_and_target=(\"call_method\", \"softmax\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim\", \"dim\"),\n (\"dtype\", \"dtype\", this_arg_is_optional),\n ],\n)\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.nn.functional.softmax),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim\", \"dim\"),\n (\"dtype\", \"dtype\", this_arg_is_optional),\n ],\n)\n@register_acc_op\ndef softmax(*, input, dim, dtype=None):\n \"\"\"\n _stacklevel are ignored here.\n \"\"\"\n return torch.nn.functional.softmax(input=input, dim=dim, dtype=dtype)\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", torch.addmm),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"mat1\", \"mat1\"),\n (\"mat2\", \"mat2\"),\n (\"beta\", \"beta\"),\n (\"alpha\", \"alpha\"),\n ],\n)\ndef addmm_mapper(node: torch.fx.Node, _: nn.Module) -> torch.fx.Node:\n \"\"\"\n Mapping from torch.addmm to acc_ops.mm -> acc_ops.add, if alpha or beta is not 1\n then we also insert acc_ops.mul to the right place.\n \"\"\"\n with node.graph.inserting_before(node):\n mm_kwargs = {\"input\": node.kwargs[\"mat1\"], \"other\": node.kwargs[\"mat2\"]}\n mm_node = node.graph.create_node(\n \"call_function\", matmul, kwargs=mm_kwargs, name=f\"{node.name}_mm\"\n )\n mm_node.meta = node.meta.copy()\n\n if node.kwargs[\"alpha\"] != 1:\n mul_kwargs = {\"input\": mm_node, \"other\": node.kwargs[\"alpha\"]}\n mm_node = node.graph.create_node(\n \"call_function\", mul, kwargs=mul_kwargs, name=f\"{mm_node.name}_mul\"\n )\n mm_node.meta = node.meta.copy()\n\n input_node = node.kwargs[\"input\"]\n if node.kwargs[\"beta\"] != 1:\n mul_kwargs = {\"input\": input_node, \"other\": node.kwargs[\"beta\"]}\n new_input_node = node.graph.create_node(\n \"call_function\", mul, kwargs=mul_kwargs, name=f\"{node.name}_input_mul\"\n )\n assert isinstance(input_node, torch.fx.Node)\n new_input_node.meta = input_node.meta.copy()\n input_node = new_input_node\n\n add_kwargs = {\"input\": mm_node, \"other\": input_node}\n add_node = node.graph.create_node(\n \"call_function\", add, kwargs=add_kwargs, name=f\"{node.name}_add\"\n )\n add_node.meta = node.meta.copy()\n return add_node\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", torch.t),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n ],\n)\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"t\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n ],\n)\ndef t_mapper(node: torch.fx.Node, _: nn.Module):\n ranks = node.meta[\"tensor_rank\"]\n shuffle = [1, 0] if (ranks > 1) else [0]\n\n with node.graph.inserting_before(node):\n new_node = node.graph.create_node(\n \"call_function\",\n permute,\n kwargs={\"input\": node.kwargs[\"input\"], \"permutation\": shuffle},\n )\n new_node.meta = node.meta.copy()\n return new_node\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op_mapping(\n op_and_target=(\"call_method\", \"permute\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"*\", \"permutation\"),\n ],\n)\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.permute),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dims\", \"permutation\"),\n ],\n)\n@register_acc_op\ndef permute(*, input, permutation):\n return input.permute(*permutation)\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", torch.square),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n ],\n)\ndef square_mapper(node: torch.fx.Node, _: nn.Module) -> torch.fx.Node:\n input_node = node.kwargs[\"input\"]\n with node.graph.inserting_before(node):\n new_node = node.graph.call_function(\n mul, kwargs={\"input\": input_node, \"other\": input_node}\n )\n new_node.meta = node.meta.copy()\n return new_node\n\n\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", operator.matmul),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"mat2\", \"other\"),\n ],\n)\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.bmm),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"mat2\", \"other\"),\n ],\n)\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.mm),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"mat2\", \"other\"),\n ],\n)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.matmul))\n@register_acc_op\ndef matmul(*, input, other):\n return torch.matmul(input=input, other=other)\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", nn.functional.dropout),\n arg_replacement_tuples=[(\"input\", \"input\")],\n)\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"detach\"), arg_replacement_tuples=[(\"input\", \"input\")]\n)\ndef dropout_mapper(node: torch.fx.Node, mod: nn.Module):\n \"\"\"\n Remove dropout node and directly map its input to output.\n \"\"\"\n return node.kwargs[\"input\"]\n\n\ntry:\n from torchvision.ops import stochastic_depth\n\n assert callable(stochastic_depth)\nexcept Exception as e:\n warnings.warn(f\"Unable to import torchvision related libraries.: {e}\")\nelse:\n\n @register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", stochastic_depth),\n arg_replacement_tuples=[(\"input\", \"input\")],\n )\n def stochastic_depth_mapper(node: torch.fx.Node, mod: nn.Module):\n \"\"\"\n Remove dropout node and directly map its input to output.\n \"\"\"\n return node.kwargs[\"input\"]\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", nn.functional.hardtanh),\n)\n@register_acc_op\ndef hardtanh(*, input, min_val=-1.0, max_val=1.0):\n return nn.functional.hardtanh(input=input, min_val=min_val, max_val=max_val)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", nn.functional.hardsigmoid))\n@register_acc_op\ndef hardsigmoid(*, input):\n return nn.functional.hardsigmoid(input)\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", nn.functional.silu),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n ],\n)\ndef silu(node: torch.fx.Node, _: nn.Module) -> torch.fx.Node:\n input_node = node.kwargs[\"input\"]\n with node.graph.inserting_before(node):\n sigmoid_node = node.graph.call_function(sigmoid, kwargs={\"input\": input_node})\n sigmoid_node.meta = node.meta.copy()\n new_node = node.graph.call_function(\n mul, kwargs={\"input\": sigmoid_node, \"other\": input_node}\n )\n new_node.meta = node.meta.copy()\n return new_node\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", nn.functional.hardswish),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n ],\n)\ndef hardswish_mapper(node: torch.fx.Node, _: nn.Module) -> torch.fx.Node:\n input_node = node.kwargs[\"input\"]\n with node.graph.inserting_before(node):\n new_sigmoid_node = node.graph.call_function(\n hardsigmoid, kwargs={\"input\": input_node}\n )\n new_sigmoid_node.meta = node.meta.copy()\n new_node = node.graph.call_function(\n mul, kwargs={\"input\": new_sigmoid_node, \"other\": input_node}\n )\n new_node.meta = node.meta.copy()\n return new_node\n\n\n@register_acc_op_properties(AccOpProperty.quantized)\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.ops.quantized.add),\n arg_replacement_tuples=[\n (\"qa\", \"input\"),\n (\"qb\", \"other\"),\n (\"scale\", \"scale\"),\n (\"zero_point\", \"zero_point\"),\n ],\n kwargs_to_move_to_acc_out_ty=[\n (\"scale\", \"scale\", move_to_qparams),\n (\"zero_point\", \"zero_point\", move_to_qparams),\n ],\n)\n@register_acc_op\ndef quantized_add(*, input, other, acc_out_ty=None):\n assert acc_out_ty is not None\n qparams = acc_out_ty.qparams\n return torch.ops.quantized.add(\n input,\n other,\n qparams[\"scale\"],\n qparams[\"zero_point\"],\n )\n\n\n@register_acc_op_properties(AccOpProperty.quantized)\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.ops.quantized.mul),\n arg_replacement_tuples=[\n (\"qa\", \"input\"),\n (\"qb\", \"other\"),\n (\"scale\", \"scale\"),\n (\"zero_point\", \"zero_point\"),\n ],\n kwargs_to_move_to_acc_out_ty=[\n (\"scale\", \"scale\", move_to_qparams),\n (\"zero_point\", \"zero_point\", move_to_qparams),\n ],\n)\n@register_acc_op\ndef quantized_mul(*, input, other, acc_out_ty=None):\n assert acc_out_ty is not None\n qparams = acc_out_ty.qparams\n return torch.ops.quantized.mul(\n input,\n other,\n qparams[\"scale\"],\n qparams[\"zero_point\"],\n )\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_properties(AccOpProperty.quantized)\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.quantize_per_tensor),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"scale\", \"scale\"),\n (\"zero_point\", \"zero_point\"),\n (\"dtype\", \"dtype\"),\n ],\n kwargs_to_move_to_acc_out_ty=[\n (\"scale\", \"scale\", move_to_qparams),\n (\"zero_point\", \"zero_point\", move_to_qparams),\n (\"dtype\", \"dtype\", dont_move_to_qparams),\n ],\n)\n@register_acc_op\ndef quantize_per_tensor(*, input, acc_out_ty=None):\n assert acc_out_ty is not None\n qparams = acc_out_ty.qparams\n dtype = acc_out_ty.dtype\n return torch.quantize_per_tensor(\n input, qparams[\"scale\"], qparams[\"zero_point\"], dtype\n )\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.quantize_per_channel),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"scales\", \"scales\"),\n (\"zero_points\", \"zero_points\"),\n (\"axis\", \"axis\"),\n (\"dtype\", \"dtype\"),\n ],\n kwargs_to_move_to_acc_out_ty=[\n (\"scales\", \"scale\", move_to_qparams),\n (\"zero_points\", \"zero_point\", move_to_qparams),\n (\"axis\", \"axis\", move_to_qparams),\n (\"dtype\", \"dtype\", dont_move_to_qparams),\n ],\n)\n@register_acc_op\ndef quantize_per_channel(*, input, acc_out_ty=None):\n assert acc_out_ty is not None\n qparams = acc_out_ty.qparams\n dtype = acc_out_ty.dtype\n return torch.quantize_per_channel(\n input,\n torch.tensor(qparams[\"scale\"]),\n torch.tensor(qparams[\"zero_point\"]),\n qparams[\"axis\"],\n dtype,\n ) # type: ignore[call-overload]\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"dequantize\"))\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.dequantize))\n@register_acc_op\ndef dequantize(*, input):\n return torch.dequantize(input)\n\n\n@register_acc_op_properties(\n AccOpProperty.pointwise, AccOpProperty.unary, AccOpProperty.quantized\n)\n@register_acc_op\ndef rescale_quantize_per_tensor(*, input, acc_out_ty=None):\n assert acc_out_ty is not None\n d = dequantize(input=input)\n return quantize_per_tensor(input=d, acc_out_ty=acc_out_ty)\n\n\n@register_acc_op_properties(AccOpProperty.unary, AccOpProperty.quantized)\n@register_acc_op\ndef rescale_quantize_per_channel(*, input, acc_out_ty=None):\n assert acc_out_ty is not None\n d = dequantize(input=input)\n return quantize_per_channel(input=d, acc_out_ty=acc_out_ty)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise)\n@register_acc_op_mapping(op_and_target=(\"call_function\", operator.sub))\n@register_acc_op\ndef sub(*, input, other):\n return input - other\n\n\n@register_acc_op_properties(AccOpProperty.pointwise)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.mul))\n@register_acc_op_mapping(op_and_target=(\"call_function\", operator.mul))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"mul\"))\n@register_acc_op\ndef mul(*, input, other):\n return input * other\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", torch.div),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"other\", \"other\"),\n (\"rounding_mode\", \"rounding_mode\", this_arg_is_optional),\n ],\n)\ndef div_mapper(node: torch.fx.Node, mod: torch.fx.GraphModule) -> torch.fx.Node:\n with node.graph.inserting_before(node):\n div_kwargs = dict(node.kwargs)\n if \"rounding_mode\" not in div_kwargs or div_kwargs[\"rounding_mode\"] is None:\n div_node = node.graph.call_function(\n div, kwargs={\"input\": div_kwargs[\"input\"], \"other\": div_kwargs[\"other\"]}\n )\n elif div_kwargs[\"rounding_mode\"] == \"trunc\":\n div_node = node.graph.call_function(\n trunc_div,\n kwargs={\"input\": div_kwargs[\"input\"], \"other\": div_kwargs[\"other\"]},\n )\n elif div_kwargs[\"rounding_mode\"] == \"floor\":\n div_node = node.graph.call_function(\n floor_div,\n kwargs={\"input\": div_kwargs[\"input\"], \"other\": div_kwargs[\"other\"]},\n )\n else:\n raise RuntimeError(\n f\"Unhandled div rounding mode {div_kwargs['rounding_mode']}\"\n )\n div_node.meta = node.meta.copy()\n return div_node\n\n\n@register_acc_op_properties(AccOpProperty.pointwise)\n@register_acc_op_mapping(op_and_target=(\"call_function\", operator.truediv))\n@register_acc_op\ndef div(*, input, other):\n return input / other\n\n\n@register_acc_op_properties(AccOpProperty.pointwise)\n@register_acc_op_mapping(op_and_target=(\"call_function\", operator.floordiv))\n@register_acc_op\ndef floor_div(*, input, other):\n # This is temp fix because currently operator.floor_div for tensors would\n # traslate into torch.floor_divide which would throw an error. After it's\n # fixed we can stick to `input // other`.\n if isinstance(input, torch.Tensor) or isinstance(other, torch.Tensor):\n return torch.div(input, other, rounding_mode=\"floor\")\n return input // other\n\n\n# torch.floor_divide rounds result toward zero, rather than -Inf.\n# https://github.com/pytorch/pytorch/issues/43874\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.floor_divide))\n@register_acc_op_properties(AccOpProperty.pointwise)\n@register_acc_op\ndef trunc_div(*, input, other):\n return torch.div(input, other, rounding_mode=\"trunc\")\n\n\n@register_acc_op_properties(AccOpProperty.pointwise)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.pow))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"pow\"))\n@register_acc_op\ndef pow(*, input, exponent):\n return torch.pow(input, exponent)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", nn.functional.relu))\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.relu),\n arg_replacement_tuples=[(\"input\", \"input\")],\n)\n@register_acc_op_mapping(\n op_and_target=(\"call_method\", \"relu\"),\n arg_replacement_tuples=[(\"input\", \"input\")],\n)\n@register_acc_op\ndef relu(*, input, inplace=False):\n return nn.functional.relu(input=input, inplace=inplace)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.nn.functional.leaky_relu)\n)\n@register_acc_op\ndef leaky_relu(*, input, negative_slope=0.01, inplace=False):\n return nn.functional.leaky_relu(\n input=input, negative_slope=negative_slope, inplace=inplace\n )\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.nn.functional.elu))\n@register_acc_op\ndef elu(*, input, alpha=1.0, inplace=False):\n return nn.functional.elu(input=input, alpha=alpha, inplace=inplace)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.nn.functional.selu))\n@register_acc_op\ndef selu(*, input, inplace=False):\n return nn.functional.selu(input=input, inplace=inplace)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.nn.functional.softsign))\n@register_acc_op\ndef softsign(*, input):\n return nn.functional.softsign(input=input)\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", torch.log1p),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n ],\n)\ndef torch_log1p_mapper(node: torch.fx.Node, _: torch.nn.Module) -> torch.fx.Node:\n with node.graph.inserting_before(node):\n add_kwargs = {\"input\": node.kwargs[\"input\"], \"other\": 1.0}\n add_node = node.graph.call_function(add, kwargs=add_kwargs)\n add_node.meta = node.meta.copy()\n log_kwargs = {\"input\": add_node}\n log_node = node.graph.call_function(log, kwargs=log_kwargs)\n log_node.meta = node.meta.copy()\n return log_node\n\n\ndef reduce_op_mapper(\n node: torch.fx.Node, mod: torch.fx.GraphModule, func\n) -> torch.fx.Node:\n with node.graph.inserting_before(node):\n kwargs = dict(node.kwargs)\n if \"dim\" in kwargs and isinstance(kwargs[\"dim\"], int):\n kwargs[\"dim\"] = (kwargs[\"dim\"],)\n new_node = node.graph.call_function(func, kwargs=kwargs)\n new_node.meta = node.meta.copy()\n return new_node\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op\ndef sum(*, input, dim=None, keepdim=False, dtype=None):\n if dim is not None:\n return torch.sum(input, dim=dim, keepdim=keepdim, dtype=dtype)\n else:\n return input.sum(dtype=dtype)\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"sum\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim\", \"dim\", this_arg_is_optional),\n (\"keepdim\", \"keepdim\", this_arg_is_optional),\n (\"dtype\", \"dtype\", this_arg_is_optional),\n ],\n)\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", torch.sum),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim\", \"dim\", this_arg_is_optional),\n (\"keepdim\", \"keepdim\", this_arg_is_optional),\n (\"dtype\", \"dtype\", this_arg_is_optional),\n ],\n)\ndef sum_mapper(node: torch.fx.Node, mod: torch.fx.GraphModule) -> torch.fx.Node:\n return reduce_op_mapper(node, mod, sum)\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op\ndef prod(*, input, dim=None, keepdim=False, dtype=None):\n if dim is not None:\n return torch.prod(input, dim=dim, keepdim=keepdim, dtype=dtype)\n else:\n return input.prod(dtype=dtype)\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"prod\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim\", \"dim\", this_arg_is_optional),\n (\"keepdim\", \"keepdim\", this_arg_is_optional),\n (\"dtype\", \"dtype\", this_arg_is_optional),\n ],\n)\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", torch.prod),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim\", \"dim\", this_arg_is_optional),\n (\"keepdim\", \"keepdim\", this_arg_is_optional),\n (\"dtype\", \"dtype\", this_arg_is_optional),\n ],\n)\ndef prod_mapper(node: torch.fx.Node, mod: torch.fx.GraphModule) -> torch.fx.Node:\n func = prod\n with node.graph.inserting_before(node):\n kwargs = dict(node.kwargs)\n new_node = node.graph.call_function(func, kwargs=kwargs)\n new_node.meta = node.meta.copy()\n return new_node\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op\ndef mean(*, input, dim=None, keepdim=False, dtype=None):\n if dim is not None:\n return torch.mean(input, dim=dim, keepdim=keepdim, dtype=dtype)\n else:\n return input.mean(dtype=dtype)\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"mean\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim\", \"dim\", this_arg_is_optional),\n (\"keepdim\", \"keepdim\", this_arg_is_optional),\n (\"dtype\", \"dtype\", this_arg_is_optional),\n ],\n)\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", torch.mean),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim\", \"dim\", this_arg_is_optional),\n (\"keepdim\", \"keepdim\", this_arg_is_optional),\n (\"dtype\", \"dtype\", this_arg_is_optional),\n ],\n)\ndef mean_mapper(node, mod):\n return reduce_op_mapper(node, mod, mean)\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"std\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim\", \"dim\"),\n (\"unbiased\", \"unbiased\", this_arg_is_optional),\n (\"keepdim\", \"keepdim\", this_arg_is_optional),\n (\"dtype\", \"dtype\", this_arg_is_optional),\n ],\n)\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", torch.std),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim\", \"dim\"),\n (\"unbiased\", \"unbiased\", this_arg_is_optional),\n (\"keepdim\", \"keepdim\", this_arg_is_optional),\n (\"dtype\", \"dtype\", this_arg_is_optional),\n ],\n)\ndef std_mapper(node, mod):\n \"\"\"\n Formula of std: sqrt(sum(pow(X-mean(X))))/N)\n This op is mapped to a few existing ops\n \"\"\"\n input_node = node.kwargs[\"input\"]\n # unbiased = node.kwargs.get(\"unbiased\")\n dim = node.kwargs.get(\"dim\")\n keepdim = node.kwargs.get(\"keepdim\")\n # assert unbiased is False or unbiased is None, \"We currently do not support `std` with unbiased=True where n-1 is used\"\n assert (\n dim is not None and keepdim is not None\n ), \"We currently do not support `std` with dim=None and keepdim=None\"\n\n with node.graph.inserting_before(node):\n # mean(X)\n mean_kwargs = {\n \"input\": input_node,\n \"dim\": dim,\n \"keepdim\": keepdim,\n }\n mean_node = node.graph.call_function(mean, kwargs=mean_kwargs)\n mean_node.meta[\"type\"] = torch.Tensor\n # X-mean(X)\n sub_kwargs = {\n \"input\": input_node,\n \"other\": mean_node,\n }\n sub_node = node.graph.call_function(sub, kwargs=sub_kwargs)\n sub_node.meta[\"type\"] = torch.Tensor\n # pow(X-mean(X))\n pow_kwargs = {\n \"input\": sub_node,\n \"exponent\": 2.0,\n }\n pow_node = node.graph.call_function(pow, kwargs=pow_kwargs)\n pow_node.meta[\"type\"] = torch.Tensor\n # sum(pow(X-mean(X))))/N\n post_mean_kwargs = {\n \"input\": pow_node,\n \"dim\": dim,\n \"keepdim\": keepdim,\n }\n post_mean_node = node.graph.call_function(mean, kwargs=post_mean_kwargs)\n post_mean_node.meta[\"type\"] = torch.Tensor\n # sqrt(sum(pow(X-mean(X))))/N)\n sqrt_kwargs = {\n \"input\": post_mean_node,\n }\n sqrt_node = node.graph.call_function(sqrt, kwargs=sqrt_kwargs)\n sqrt_node.meta[\"type\"] = torch.Tensor\n\n output_node = sqrt_node\n output_node.meta = node.meta.copy()\n return output_node\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"max\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n ((\"dim\", \"other\"), \"dim_or_other\", this_arg_is_optional),\n (\"keepdim\", \"keepdim\", this_arg_is_optional),\n ],\n)\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", torch.max),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n ((\"dim\", \"other\"), \"dim_or_other\", this_arg_is_optional),\n (\"keepdim\", \"keepdim\", this_arg_is_optional),\n ],\n)\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"min\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n ((\"dim\", \"other\"), \"dim_or_other\", this_arg_is_optional),\n (\"keepdim\", \"keepdim\", this_arg_is_optional),\n ],\n)\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", torch.min),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n ((\"dim\", \"other\"), \"dim_or_other\", this_arg_is_optional),\n (\"keepdim\", \"keepdim\", this_arg_is_optional),\n ],\n)\ndef add_maximum_minimum_mapper(\n node: torch.fx.Node, mod: torch.fx.GraphModule\n) -> torch.fx.Node:\n # there are effectively three versions of torch.max / torch.min\n # full reduce: torch.max(input) -> Tensor\n # dimensional reduce: torch.max(input, dim, keepdim=False, *, out=None) -> (Tensor, LongTensor)\n # elementwise: torch.max(input, other, *, out=None) -> Tensor\n\n # the mapper function is remapping for both min and max situations\n # this helper function makes the choices available clearer and provides an easier way\n # to lookup the right function\n def target_map(op, target):\n if (op, target) in ((\"call_method\", \"max\"), (\"call_function\", torch.max)):\n return {\n \"full_reduce\": max_full_reduce,\n \"dim_reduce\": max_dim_reduce,\n \"elementwise\": maximum,\n }\n elif (op, target) in ((\"call_method\", \"min\"), (\"call_function\", torch.min)):\n return {\n \"full_reduce\": min_full_reduce,\n \"dim_reduce\": min_dim_reduce,\n \"elementwise\": minimum,\n }\n\n with node.graph.inserting_before(node):\n new_targets = target_map(node.op, node.target)\n max_kwargs = {}\n max_kwargs[\"input\"] = node.kwargs[\"input\"]\n if (\"dim_or_other\" not in node.kwargs) or (node.kwargs[\"dim_or_other\"] is None):\n nt = new_targets[\"full_reduce\"]\n max_node = node.graph.call_function(nt, kwargs=max_kwargs)\n elif isinstance(node.kwargs[\"dim_or_other\"], int):\n nt = new_targets[\"dim_reduce\"]\n dim = node.kwargs[\"dim_or_other\"]\n max_kwargs[\"dim\"] = dim\n max_kwargs[\"keepdim\"] = node.kwargs.get(\"keepdim\", False)\n max_node = node.graph.call_function(nt, kwargs=max_kwargs)\n else:\n other = node.kwargs[\"dim_or_other\"]\n assert isinstance(other, torch.fx.Node)\n # Lowering path for when provided \"other\", where we do elem-wise max\n nt = new_targets[\"elementwise\"]\n max_kwargs[\"other\"] = other\n max_node = node.graph.call_function(nt, kwargs=max_kwargs)\n max_node.meta = node.meta.copy()\n return max_node\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op\ndef max_full_reduce(*, input):\n return torch.max(input=input)\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op\ndef max_dim_reduce(*, input, dim=None, keepdim=False):\n return torch.max(input=input, dim=dim, keepdim=keepdim)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.maximum))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"maximum\"))\n@register_acc_op\ndef maximum(*, input, other):\n return torch.maximum(input=input, other=other)\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op\ndef min_full_reduce(*, input):\n return torch.min(input=input)\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op\ndef min_dim_reduce(*, input, dim=None, keepdim=False):\n return torch.min(input, dim=dim, keepdim=keepdim)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.minimum))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"minimum\"))\n@register_acc_op\ndef minimum(*, input, other):\n return torch.minimum(input=input, other=other)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise)\n@register_acc_op_mapping(op_and_target=(\"call_function\", operator.ne))\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.ne))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"ne\"))\n@register_acc_op\ndef ne(*, input, other):\n return operator.ne(input, other)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise)\n@register_acc_op_mapping(op_and_target=(\"call_function\", operator.eq))\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.eq))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"eq\"))\n@register_acc_op\ndef eq(*, input, other):\n return operator.eq(input, other)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise)\n@register_acc_op_mapping(op_and_target=(\"call_function\", operator.gt))\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.gt))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"gt\"))\n@register_acc_op\ndef gt(*, input, other):\n return operator.gt(input, other)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise)\n@register_acc_op_mapping(op_and_target=(\"call_function\", operator.lt))\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.lt))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"lt\"))\n@register_acc_op\ndef lt(*, input, other):\n return operator.lt(input, other)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise)\n@register_acc_op_mapping(op_and_target=(\"call_function\", operator.and_))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"bitwise_and\"))\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.bitwise_and))\ndef bitwise_and(*, input, other):\n return operator.and_(input, other)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.logical_and))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"logical_and\"))\n@register_acc_op\ndef logical_and(*, input, other):\n return torch.logical_and(input=input, other=other)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise)\n@register_acc_op_mapping(op_and_target=(\"call_function\", operator.or_))\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.logical_or))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"logical_or\"))\n@register_acc_op\ndef logical_or(*, input, other):\n return torch.logical_or(input=input, other=other)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.logical_not))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"logical_not\"))\n@register_acc_op\ndef logical_not(*, input):\n return torch.logical_not(input=input)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise)\n@register_acc_op_mapping(op_and_target=(\"call_function\", operator.xor))\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.logical_xor))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"logical_xor\"))\n@register_acc_op\ndef logical_xor(*, input, other):\n return torch.logical_xor(input=input, other=other)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.isinf))\n@register_acc_op\ndef isinf(*, input):\n return torch.isinf(input=input)\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op\ndef any(*, input, dim=None, keepdim=False):\n if dim is not None:\n return torch.any(input, dim, keepdim=keepdim)\n else:\n return torch.any(input)\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", torch.any),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim\", \"dim\", this_arg_is_optional),\n (\"keepdim\", \"keepdim\", this_arg_is_optional),\n ],\n)\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"any\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim\", \"dim\", this_arg_is_optional),\n (\"keepdim\", \"keepdim\", this_arg_is_optional),\n ],\n)\ndef any_mapper(node: torch.fx.Node, mod: torch.fx.GraphModule) -> torch.fx.Node:\n with node.graph.inserting_before(node):\n new_node = node.graph.call_function(any, kwargs=node.kwargs)\n new_node.meta = node.meta.copy()\n return new_node\n\n\n@register_acc_op_properties(AccOpProperty.pointwise)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.fmod))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"fmod\"))\n@register_acc_op\ndef fmod(*, input, other):\n return torch.fmod(input=input, other=other)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.sigmoid))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"sigmoid\"))\n@register_acc_op\ndef sigmoid(*, input):\n return torch.sigmoid(input=input)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.sinh))\n@register_acc_op\ndef sinh(*, input):\n return torch.sinh(input=input)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.cosh))\n@register_acc_op\ndef cosh(*, input):\n return torch.cosh(input=input)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.tanh))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"tanh\"))\n@register_acc_op\ndef tanh(*, input):\n return torch.tanh(input=input)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.asin))\n@register_acc_op\ndef asin(*, input):\n return torch.asin(input=input)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.acos))\n@register_acc_op\ndef acos(*, input):\n return torch.acos(input=input)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.atan))\n@register_acc_op\ndef atan(*, input):\n return torch.atan(input=input)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.exp))\n@register_acc_op\ndef exp(*, input):\n return torch.exp(input=input)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.log))\n@register_acc_op\ndef log(*, input):\n return torch.log(input=input)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.sqrt))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"sqrt\"))\n@register_acc_op\ndef sqrt(*, input):\n return torch.sqrt(input=input)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.reciprocal))\n@register_acc_op\ndef reciprocal(*, input):\n return torch.reciprocal(input=input)\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"rsqrt\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n ],\n)\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", torch.rsqrt),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n ],\n)\ndef rsqrt_mapper(node: torch.fx.Node, mod: torch.fx.GraphModule) -> torch.fx.Node:\n input_node = node.kwargs[\"input\"]\n with node.graph.inserting_before(node):\n new_kwargs = {\n \"input\": input_node,\n }\n sqrt_node = node.graph.call_function(sqrt, kwargs=new_kwargs)\n sqrt_node.meta[\"type\"] = torch.Tensor\n new_kwargs = {\n \"input\": sqrt_node,\n }\n rec_node = node.graph.call_function(reciprocal, kwargs=new_kwargs)\n rec_node.meta[\"type\"] = torch.Tensor\n output_node = rec_node\n output_node.meta = node.meta.copy()\n return output_node\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.abs))\n@register_acc_op\ndef abs(*, input):\n return torch.abs(input=input)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", operator.neg))\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.neg))\n@register_acc_op\ndef neg(*, input):\n return torch.neg(input=input)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.floor))\n@register_acc_op\ndef floor(*, input):\n return torch.floor(input=input)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.ceil))\n@register_acc_op\ndef ceil(*, input):\n return torch.ceil(input=input)\n\n\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.nn.functional.pad))\n@register_acc_op\ndef pad(*, input, pad, mode, value):\n return torch.nn.functional.pad(input=input, pad=pad, mode=mode, value=value)\n\n\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.conv1d))\n@register_acc_op\ndef conv1d(*, input, weight, bias, stride, padding, dilation, groups):\n return nn.functional.conv1d(\n input=input,\n weight=weight,\n bias=bias,\n stride=stride,\n padding=padding,\n dilation=dilation,\n groups=groups,\n )\n\n\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.conv2d))\n@register_acc_op\ndef conv2d(*, input, weight, bias, stride, padding, dilation, groups):\n return nn.functional.conv2d(\n input=input,\n weight=weight,\n bias=bias,\n stride=stride,\n padding=padding,\n dilation=dilation,\n groups=groups,\n )\n\n\n@register_acc_op_properties(AccOpProperty.quantized)\n@register_acc_op\ndef quantized_conv2d(\n *,\n input,\n weight,\n bias,\n stride,\n padding,\n dilation,\n groups,\n padding_mode,\n acc_out_ty,\n):\n qparams = acc_out_ty.qparams\n return torch.nn.quantized.functional.conv2d(\n input=input,\n weight=weight,\n bias=bias,\n stride=stride,\n padding=padding,\n dilation=dilation,\n groups=groups,\n padding_mode=padding_mode,\n scale=qparams[\"scale\"],\n zero_point=qparams[\"zero_point\"],\n )\n\n\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.conv3d))\n@register_acc_op\ndef conv3d(*, input, weight, bias, stride, padding, dilation, groups):\n return nn.functional.conv3d(\n input=input,\n weight=weight,\n bias=bias,\n stride=stride,\n padding=padding,\n dilation=dilation,\n groups=groups,\n )\n\n\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.nn.functional.conv_transpose2d)\n)\n@register_acc_op\ndef conv_transpose2d(\n *,\n input,\n weight,\n bias,\n stride,\n padding,\n output_padding,\n groups,\n dilation,\n):\n return nn.functional.conv_transpose2d(\n input=input,\n weight=weight,\n bias=bias,\n stride=stride,\n padding=padding,\n output_padding=output_padding,\n groups=groups,\n dilation=dilation,\n )\n\n\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.nn.functional.conv_transpose3d)\n)\n@register_acc_op\ndef conv_transpose3d(\n *,\n input,\n weight,\n bias,\n stride,\n padding,\n output_padding,\n groups,\n dilation,\n):\n return nn.functional.conv_transpose3d(\n input=input,\n weight=weight,\n bias=bias,\n stride=stride,\n padding=padding,\n output_padding=output_padding,\n groups=groups,\n dilation=dilation,\n )\n\n\n@register_acc_op_mapping(op_and_target=(\"call_function\", nn.functional.batch_norm))\n@register_acc_op\ndef batch_norm(\n *,\n input,\n running_mean,\n running_var,\n weight,\n bias,\n training,\n momentum,\n eps,\n):\n return nn.functional.batch_norm(\n input=input,\n running_mean=running_mean,\n running_var=running_var,\n weight=weight,\n bias=bias,\n training=training,\n momentum=momentum,\n eps=eps,\n )\n\n\n@register_acc_op_mapping(op_and_target=(\"call_function\", nn.functional.layer_norm))\n@register_acc_op\ndef layer_norm(*, input, normalized_shape, weight, bias, eps):\n return nn.functional.layer_norm(\n input=input,\n normalized_shape=normalized_shape,\n weight=weight,\n bias=bias,\n eps=eps,\n )\n\n\ndef argmin_max_mapper_impl(node: torch.fx.Node, largest: bool) -> torch.fx.Node:\n \"\"\"\n Map torch.argmin or torch.argmax to acc_ops.flatten (depend on dim) + acc_ops.topk\n + acc_ops.getitem + acc_ops.squeeze (depends on keepdim).\n \"\"\"\n input_node = node.kwargs[\"input\"]\n dim = node.kwargs[\"dim\"]\n keepdim = node.kwargs[\"keepdim\"]\n\n if dim is None and keepdim:\n raise RuntimeError(\n \"We currently don't support argmin/argmax with dim=None and keepdim=True\"\n )\n\n with node.graph.inserting_before(node):\n if dim is None:\n flatten_kwargs = {\n \"input\": node.kwargs[\"input\"],\n \"start_dim\": 0,\n \"end_dim\": -1,\n }\n flatten_node = node.graph.call_function(flatten, kwargs=flatten_kwargs)\n flatten_node.meta[\"type\"] = torch.Tensor\n input_node = flatten_node\n dim = -1\n\n topk_kwargs = {\n \"input\": input_node,\n \"k\": 1,\n \"dim\": dim,\n \"largest\": largest,\n \"sorted\": False,\n }\n topk_node = node.graph.call_function(topk, kwargs=topk_kwargs)\n # It's actually more like NamedTuple but tuple here should be fine.\n topk_node.meta[\"type\"] = tuple\n\n getitem_kwargs = {\"input\": topk_node, \"idx\": 1}\n getitem_node = node.graph.call_function(getitem, kwargs=getitem_kwargs)\n getitem_node.meta[\"type\"] = torch.Tensor\n output_node = getitem_node\n\n if not keepdim:\n squeeze_kwargs = {\"input\": getitem_node, \"dim\": dim}\n output_node = node.graph.call_function(squeeze, kwargs=squeeze_kwargs)\n\n output_node.meta = node.meta.copy()\n return output_node\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", torch.argmin),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim\", \"dim\"),\n (\"keepdim\", \"keepdim\"),\n ],\n)\ndef torch_argmin_mapper(node: torch.fx.Node, _: torch.nn.Module) -> torch.fx.Node:\n \"\"\"\n Map torch.argmin to acc_ops.flatten (depend on dim) + acc_ops.topk + acc_ops.getitem\n + acc_ops.squeeze (depends on keepdim).\n \"\"\"\n return argmin_max_mapper_impl(node, largest=False)\n\n\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.linalg.norm))\n@register_acc_op\ndef linalg_norm(*, input, ord, dim, keepdim):\n return torch.linalg.norm(input=input, ord=ord, dim=dim, keepdim=keepdim)\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"split\"),\n arg_replacement_tuples=[\n (\"tensor\", \"input\"),\n (\"split_size_or_sections\", \"split_size_or_sections\"),\n (\"dim\", \"dim\"),\n ],\n)\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"split_with_sizes\"),\n arg_replacement_tuples=[\n (\"tensor\", \"input\"),\n (\"split_sizes\", \"split_size_or_sections\"),\n (\"dim\", \"dim\"),\n ],\n)\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", torch.split),\n arg_replacement_tuples=[\n (\"tensor\", \"input\"),\n (\"split_size_or_sections\", \"split_size_or_sections\"),\n (\"dim\", \"dim\"),\n ],\n)\ndef torch_split_mapper(node: torch.fx.Node, mod: nn.Module) -> torch.fx.Node:\n \"\"\"\n If split_size_or_sections is sections, map the node to slice_tensors\n + tuple_construct. Otherwise, if split_size_or_sections is split_size,\n map the node to acc_ops.split.\n \"\"\"\n split_size_or_sections = node.kwargs[\"split_size_or_sections\"]\n with node.graph.inserting_before(node):\n if isinstance(split_size_or_sections, int):\n new_kwargs = {\n \"input\": node.kwargs[\"input\"],\n \"split_size\": split_size_or_sections,\n \"dim\": node.kwargs[\"dim\"],\n }\n new_node = node.graph.call_function(split, kwargs=new_kwargs)\n new_node.meta = node.meta.copy()\n return new_node\n\n assert isinstance(split_size_or_sections, Sequence)\n start = 0\n slice_nodes = []\n for i in split_size_or_sections:\n assert isinstance(i, int)\n new_kwargs = {\n \"input\": node.kwargs[\"input\"],\n \"dim\": node.kwargs[\"dim\"],\n \"start\": start,\n \"stop\": start + i,\n \"step\": 1,\n }\n new_node = node.graph.call_function(slice_tensor, kwargs=new_kwargs)\n new_node.meta[\"type\"] = torch.Tensor\n slice_nodes.append(new_node)\n start += i\n\n new_node = node.graph.call_function(\n tuple_construct, kwargs={\"tensors\": tuple(slice_nodes)}\n )\n new_node.meta = node.meta.copy()\n return new_node\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op\ndef split(*, input, split_size, dim):\n return torch.split(input, split_size, dim)\n\n\n@register_acc_op\ndef tuple_construct(*, tensors):\n return tuple(tensors)\n\n\n@register_acc_op_properties(AccOpProperty.quantized)\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.ops.quantized.batch_norm2d),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"weight\", \"weight\"),\n (\"bias\", \"bias\"),\n (\"running_mean\", \"running_mean\"),\n (\"running_var\", \"running_var\"),\n (\"eps\", \"eps\"),\n (\"scale\", \"scale\"),\n (\"zero_point\", \"zero_point\"),\n ],\n kwargs_to_move_to_acc_out_ty=[\n (\"scale\", \"scale\", move_to_qparams),\n (\"zero_point\", \"zero_point\", move_to_qparams),\n ],\n)\n@register_acc_op\ndef quantized_batch_norm2d(\n *,\n input,\n running_mean,\n running_var,\n weight,\n bias,\n eps,\n acc_out_ty,\n):\n qparams = acc_out_ty.qparams\n return torch.ops.quantized.batch_norm2d(\n input,\n weight,\n bias,\n running_mean,\n running_var,\n eps,\n qparams[\"scale\"],\n qparams[\"zero_point\"],\n )\n\n\n@register_acc_op_mapping(op_and_target=(\"call_function\", nn.functional.embedding_bag))\n@register_acc_op\ndef embedding_bag(\n *,\n input,\n weight,\n offsets,\n max_norm,\n norm_type,\n scale_grad_by_freq,\n mode,\n sparse,\n per_sample_weights,\n include_last_offset,\n padding_idx,\n):\n return nn.functional.embedding_bag(\n input=input,\n weight=weight,\n offsets=offsets,\n max_norm=max_norm,\n norm_type=norm_type,\n scale_grad_by_freq=scale_grad_by_freq,\n mode=mode,\n sparse=sparse,\n per_sample_weights=per_sample_weights,\n include_last_offset=include_last_offset,\n padding_idx=padding_idx,\n )\n\n\n@register_acc_op_mapping(\n op_and_target=(\n \"call_function\",\n torch.ops.quantized.embedding_bag_byte_rowwise_offsets,\n )\n)\n@register_acc_op\ndef embedding_bag_byte_rowwise_offsets(\n *,\n weight,\n indices,\n offsets,\n scale_grad_by_freq,\n mode,\n pruned_weights,\n per_sample_weights,\n compressed_indices_mapping,\n include_last_offset,\n):\n return torch.ops.quantized.embedding_bag_byte_rowwise_offsets(\n weight=weight,\n indices=indices,\n offsets=offsets,\n scale_grad_by_freq=scale_grad_by_freq,\n mode=mode,\n pruned_weights=pruned_weights,\n per_sample_weights=per_sample_weights,\n compressed_indices_mapping=compressed_indices_mapping,\n include_last_offset=include_last_offset,\n )\n\n\n@register_acc_op_mapping(\n op_and_target=(\n \"call_function\",\n torch.ops.quantized.embedding_bag_4bit_rowwise_offsets,\n )\n)\n@register_acc_op\ndef embedding_bag_4bit_rowwise_offsets(\n *,\n weight,\n indices,\n offsets,\n scale_grad_by_freq,\n mode,\n pruned_weights,\n per_sample_weights,\n compressed_indices_mapping,\n include_last_offset,\n):\n return torch.ops.quantized.embedding_bag_4bit_rowwise_offsets(\n weight=weight,\n indices=indices,\n offsets=offsets,\n scale_grad_by_freq=scale_grad_by_freq,\n mode=mode,\n pruned_weights=pruned_weights,\n per_sample_weights=per_sample_weights,\n compressed_indices_mapping=compressed_indices_mapping,\n include_last_offset=include_last_offset,\n )\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.sin))\n@register_acc_op\ndef sin(*, input):\n return torch.sin(input=input)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.cos))\n@register_acc_op\ndef cos(*, input):\n return torch.cos(input=input)\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.tan))\n@register_acc_op\ndef tan(*, input):\n return torch.tan(input=input)\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.topk))\n@register_acc_op\ndef topk(*, input, k, dim, largest, sorted):\n return torch.topk(input=input, k=k, dim=dim, largest=largest, sorted=sorted)\n\n\n@register_acc_op_mapping(op_and_target=(\"call_function\", operator.getitem))\n@register_acc_op\ndef getitem(*, input, idx):\n return input[idx]\n\n\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.nan_to_num))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"nan_to_num\"))\n@register_acc_op\ndef nan_to_num(*, input, nan=0.0, posinf=None, neginf=None):\n return torch.nan_to_num(input, nan=nan, posinf=posinf, neginf=neginf)\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op_mapping(\n op_and_target=(\"call_method\", \"expand\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"*\", \"sizes\"),\n ],\n)\n@register_acc_op\ndef expand(*, input, sizes):\n return input.expand(*sizes)\n\n\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.masked_fill),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"mask\", \"mask\"),\n (\"value\", \"value\"),\n ],\n)\n@register_acc_op_mapping(\n op_and_target=(\"call_method\", \"masked_fill\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"mask\", \"mask\"),\n (\"value\", \"value\"),\n ],\n)\n@register_acc_op\ndef masked_fill(*, input, mask, value):\n return input.masked_fill(mask, value)\n\n\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.where))\n@register_acc_op\ndef where(*, condition, x, y):\n return torch.where(condition, x, y)\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op\ndef slice_tensor(*, input, dim, start, stop, step):\n slc = slice(start, stop, step)\n if dim >= 0:\n slices: List[slice] = [slice(None, None, None) for _ in range(dim)]\n slices.append(slc)\n else:\n slices = [Ellipsis, slc] # type: ignore[list-item]\n slices.extend([slice(None, None, None) for _ in range(-dim - 1)])\n\n return input[tuple(slices)]\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", torch.narrow),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim\", \"dim\"),\n (\"start\", \"start\"),\n (\"length\", \"length\"),\n ],\n)\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"narrow\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim\", \"dim\"),\n (\"start\", \"start\"),\n (\"length\", \"length\"),\n ],\n)\ndef custom_narrow_mapper(node: torch.fx.Node, mod: nn.Module) -> torch.fx.Node:\n assert isinstance(node.kwargs[\"start\"], int) and isinstance(\n node.kwargs[\"length\"], int\n )\n kwargs = {\n \"input\": node.kwargs[\"input\"],\n \"dim\": node.kwargs[\"dim\"],\n \"start\": node.kwargs[\"start\"],\n \"stop\": node.kwargs[\"start\"] + node.kwargs[\"length\"],\n \"step\": 1,\n }\n with node.graph.inserting_before(node):\n new_node = node.graph.call_function(slice_tensor, kwargs=kwargs)\n new_node.meta = node.meta.copy()\n return new_node\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.reshape),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"shape\", \"shape\"),\n ],\n kwargs_to_move_to_acc_out_ty=[(\"shape\", \"shape\")],\n)\n@register_acc_op\ndef reshape(*, input, acc_out_ty=None):\n assert acc_out_ty is not None\n return input.reshape(acc_out_ty.shape)\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"reshape\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"*\", \"shape\"),\n ],\n)\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"view\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"*\", \"shape\"),\n ],\n)\ndef custom_tensor_reshape_mapper(node: torch.fx.Node, _: nn.Module) -> torch.fx.Node:\n \"\"\"\n For Tensor.reshape and Tensor.view nodes, args could be (input, 1, 2, 3) or (input,\n (1, 2, 3)). Here we do some special handling with the `shape` arg in order to map\n it to acc_ops.reshape. It also handles the case when `shape` is a list instead of\n tuple.\n \"\"\"\n input_node = node.kwargs[\"input\"]\n shape = node.kwargs[\"shape\"]\n\n assert isinstance(shape, Sequence)\n if isinstance(shape[0], (tuple, list)): # type: ignore[index]\n shape = shape[0] # type: ignore[index]\n\n with node.graph.inserting_before(node):\n new_node = node.graph.call_function(\n reshape,\n kwargs={\n \"input\": input_node,\n \"acc_out_ty\": acc_utils.build_raw_tensor_meta(shape=shape),\n },\n )\n new_node.meta = node.meta.copy()\n return new_node\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"half\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n ],\n)\ndef custom_half_mapper(node: torch.fx.Node, _: nn.Module):\n with node.graph.inserting_before(node):\n new_kwargs = {\n \"input\": node.kwargs[\"input\"],\n \"acc_out_ty\": acc_utils.build_raw_tensor_meta(dtype=torch.float16),\n }\n new_node = node.graph.call_function(to_dtype, kwargs=new_kwargs)\n new_node.meta = node.meta\n return new_node\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"int\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n ],\n)\ndef custom_int_mapper(node: torch.fx.Node, _: nn.Module):\n with node.graph.inserting_before(node):\n new_kwargs = {\n \"input\": node.kwargs[\"input\"],\n \"acc_out_ty\": acc_utils.build_raw_tensor_meta(dtype=torch.int),\n }\n new_node = node.graph.call_function(to_dtype, kwargs=new_kwargs)\n new_node.meta = node.meta\n return new_node\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"float\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n ],\n)\ndef custom_float_mapper(node: torch.fx.Node, _: nn.Module):\n with node.graph.inserting_before(node):\n new_kwargs = {\n \"input\": node.kwargs[\"input\"],\n \"acc_out_ty\": acc_utils.build_raw_tensor_meta(dtype=torch.float),\n }\n new_node = node.graph.call_function(to_dtype, kwargs=new_kwargs)\n new_node.meta = node.meta\n return new_node\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op\ndef to_dtype(input, acc_out_ty=None, device=None):\n assert acc_out_ty is not None\n return input.to(dtype=acc_out_ty.dtype, device=device)\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"to\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dtype\", \"dtype\"),\n (\"device\", \"device\", this_arg_is_optional),\n ],\n)\ndef custom_tensor_to_mapper(node: torch.fx.Node, _: nn.Module):\n dest = node.kwargs[\"dtype\"]\n mem_format = node.kwargs.get(\"memory_format\")\n dest_other = node.kwargs.get(\"device\")\n assert dest is not None\n assert mem_format is None or mem_format == torch.preserve_format\n\n dest_dtype = dest_device = None\n if isinstance(dest, torch.fx.node.Node):\n meta_type = dest.meta[\"type\"]\n # consider the device is gpu only, meta info is limited to give clear device type\n if dest.meta[\"type\"] == torch.device:\n dest_device = dest\n elif dest.meta[\"type\"] == torch.dtype:\n dest_dtype = dest\n elif dest.meta[\"type\"] == torch.Tensor:\n input_obj = node.kwargs[\"input\"]\n other_obj = dest\n with node.graph.inserting_before(node):\n dtype_node = node.graph.call_function(\n dtype, kwargs={\"input\": other_obj}\n )\n dtype_node.meta[\"type\"] = torch.dtype\n device_node = node.graph.call_function(\n device, kwargs={\"input\": other_obj}\n )\n device_node.meta[\"type\"] = torch.device\n new_kwargs = {\n \"input\": input_obj,\n \"acc_out_ty\": acc_utils.build_raw_tensor_meta(dtype=dtype_node),\n \"device\": device_node,\n }\n new_node = node.graph.call_function(to_dtype, kwargs=new_kwargs)\n new_node.meta = node.meta\n return new_node\n else:\n raise RuntimeError(f\"We currently do not support to({meta_type})\")\n elif isinstance(dest, torch.device):\n # only device is set, dtype=None\n if dest_other is None:\n dest_device = dest\n # device and dtype are both set\n else:\n dest_dtype = dest_other\n dest_device = dest\n # only dtype is set\n else:\n dest_dtype = dest\n\n new_kwargs = {\n \"input\": node.kwargs[\"input\"],\n \"acc_out_ty\": acc_utils.build_raw_tensor_meta(dtype=dest_dtype),\n \"device\": dest_device,\n }\n\n with node.graph.inserting_before(node):\n new_node = node.graph.create_node(\n \"call_function\", to_dtype, kwargs=new_kwargs, name=node.name\n )\n new_node.meta = node.meta\n return new_node\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", torch.add),\n # Note that we may have aliases for inputs here due to issues with deterministically\n # knowing the correct target that will be resolved by pytorch.\n arg_replacement_tuples=[\n ((\"input\", \"a\"), \"input\"),\n ((\"other\", \"b\"), \"other\"),\n (\"alpha\", \"alpha\", this_arg_is_optional),\n ],\n)\ndef custom_torch_add_mapper(node: torch.fx.Node, mod: nn.Module) -> torch.fx.Node:\n \"\"\"\n Add custom mapping for torch.add because it has an `alpha` parameter which scales\n the `other` input, and we want to make that mul a separate node.\n \"\"\"\n with node.graph.inserting_before(node):\n # If alpha is in kwargs check if we need to add a mul, and use correct kwargs.\n if \"alpha\" in node.kwargs:\n # Add mul node only if it has a numerical impact, i.e. alpha != 1.0.\n if node.kwargs[\"alpha\"] != 1.0:\n other_node = node.graph.create_node(\n \"call_function\",\n mul,\n kwargs={\n \"input\": node.kwargs[\"other\"],\n \"other\": node.kwargs[\"alpha\"],\n },\n name=node.name + \"_mul_alpha\",\n )\n other_node.meta = node.meta\n else:\n other_node = node.kwargs[\"other\"]\n add_kwargs = {\"input\": node.kwargs[\"input\"], \"other\": other_node}\n else:\n add_kwargs = node.kwargs\n\n new_node = node.graph.create_node(\n \"call_function\", add, kwargs=add_kwargs, name=node.name\n )\n new_node.meta = node.meta\n return new_node\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_module\", nn.quantized.Linear),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n ],\n)\ndef packed_quantized_linear_mapper(\n node: torch.fx.Node, mod: nn.Module\n) -> torch.fx.Node:\n \"\"\"\n Mapping from quantized_linear module to acc_op.linear. We unpack weight and bias\n in this mapper and pass them directly to linear node.\n \"\"\"\n assert isinstance(node.target, str)\n linear_module = dict(mod.named_modules())[node.target]\n prefix = node.target.replace(\".\", \"_\")\n weight_name = f\"{prefix}_weight\"\n bias_name = f\"{prefix}_bias\"\n\n # Store weight and bias in the main module\n mod.register_buffer(weight_name, linear_module.weight())\n if linear_module.bias() is not None:\n mod.register_buffer(bias_name, linear_module.bias())\n\n with node.graph.inserting_before(node):\n # Insert get_attr nodes for weight and bias\n get_weight = node.graph.get_attr(weight_name)\n get_weight.meta[\"tensor_meta\"] = _extract_tensor_metadata(\n linear_module.weight()\n )\n\n get_bias = None\n if linear_module.bias() is not None:\n get_bias = node.graph.get_attr(bias_name)\n get_bias.meta[\"tensor_meta\"] = _extract_tensor_metadata(\n linear_module.bias()\n )\n\n qparams = {\"scale\": linear_module.scale, \"zero_point\": linear_module.zero_point}\n # Create kwargs for acc_op.quantized_linear\n kwargs = {\n \"input\": node.kwargs[\"input\"],\n \"weight\": get_weight,\n \"bias\": get_bias,\n \"acc_out_ty\": acc_utils.build_raw_tensor_meta(qparams=qparams),\n }\n\n new_node = node.graph.call_function(quantized_linear, kwargs=kwargs)\n new_node.meta = node.meta.copy()\n return new_node\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_module\", nn.quantized.Conv2d),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n ],\n)\ndef packed_quantized_conv2d_mapper(\n node: torch.fx.Node, mod: nn.Module\n) -> torch.fx.Node:\n \"\"\"\n Mapping from quantzed Conv2d module to acc_op.conv. We unpack all the parameters\n in this mapper and pass them directly to conv2d node.\n \"\"\"\n assert isinstance(node.target, str)\n conv_module = dict(mod.named_modules())[node.target]\n prefix = node.target.replace(\".\", \"_\")\n weight_name = f\"{prefix}_weight\"\n bias_name = f\"{prefix}_bias\"\n\n # Store weight and bias in the main module\n mod.register_buffer(weight_name, conv_module.weight())\n if conv_module.bias() is not None:\n mod.register_buffer(bias_name, conv_module.bias())\n\n with node.graph.inserting_before(node):\n # Insert get_attr nodes for weight and bias\n get_weight = node.graph.get_attr(weight_name)\n get_weight.meta[\"tensor_meta\"] = _extract_tensor_metadata(conv_module.weight())\n\n get_bias = None\n if conv_module.bias() is not None:\n get_bias = node.graph.get_attr(bias_name)\n get_bias.meta[\"tensor_meta\"] = _extract_tensor_metadata(conv_module.bias())\n\n qparams = {\"scale\": conv_module.scale, \"zero_point\": conv_module.zero_point}\n\n # Create kwargs for acc_op.conv\n kwargs = {\n \"input\": node.kwargs[\"input\"],\n \"weight\": get_weight,\n \"bias\": get_bias,\n \"stride\": conv_module.stride,\n \"padding\": conv_module.padding,\n \"dilation\": conv_module.dilation,\n \"groups\": conv_module.groups,\n \"padding_mode\": conv_module.padding_mode,\n \"acc_out_ty\": acc_utils.build_raw_tensor_meta(qparams=qparams),\n }\n\n new_node = node.graph.call_function(quantized_conv2d, kwargs=kwargs)\n new_node.meta = node.meta\n return new_node\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_function\", torch.ops.quantized.add_relu),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"other\", \"other\"),\n (\"scale\", \"scale\"),\n (\"zero_point\", \"zero_point\"),\n ],\n)\ndef add_relu_unfuse_mapper(\n node: torch.fx.Node, mod: torch.fx.GraphModule\n) -> torch.fx.Node:\n with node.graph.inserting_before(node):\n qparams = {\n \"scale\": node.kwargs[\"scale\"],\n \"zero_point\": node.kwargs[\"zero_point\"],\n }\n add_kwargs = {\n \"input\": node.kwargs[\"input\"],\n \"other\": node.kwargs[\"other\"],\n \"acc_out_ty\": acc_utils.build_raw_tensor_meta(qparams=qparams),\n }\n add_node = node.graph.call_function(quantized_add, kwargs=add_kwargs)\n add_node.meta = node.meta.copy()\n\n relu_node = node.graph.call_function(\n relu, kwargs={\"input\": add_node, \"inplace\": False}\n )\n relu_node.meta = node.meta\n return relu_node\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_module\", nn.intrinsic.quantized.ConvReLU2d),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n ],\n)\ndef packed_quantized_convrelu2d_mapper(\n node: torch.fx.Node, mod: nn.Module\n) -> torch.fx.Node:\n \"\"\"\n Mapping from quantized ConvReLU2d module to acc_op.relu. We use packed_quantized_conv2d_mapper to unpack all the parameters\n in this mapper and pass the returned conv2d node directly to relu node.\n \"\"\"\n\n with node.graph.inserting_before(node):\n # conv2d op\n conv2d_node = packed_quantized_conv2d_mapper(node, mod)\n\n # relu op\n relu_node = node.graph.call_function(\n relu, kwargs={\"input\": conv2d_node, \"inplace\": False}\n )\n relu_node.meta = node.meta\n return relu_node\n\n\n@register_acc_op_properties(AccOpProperty.pointwise, AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.nn.functional.gelu))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"gelu\"))\n@register_acc_op\ndef gelu(*, input):\n return torch.nn.functional.gelu(input=input)\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.cumsum))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"cumsum\"))\n@register_acc_op\ndef cumsum(*, input, dim, dtype=None):\n return torch.cumsum(input=input, dim=dim, dtype=dtype)\n\n\n@register_acc_op_properties(AccOpProperty.unary)\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.chunk))\n@register_acc_op_mapping(op_and_target=(\"call_method\", \"chunk\"))\n@register_acc_op\ndef chunk(*, input, chunks, dim=0):\n return torch.chunk(input=input, chunks=chunks, dim=dim)\n\n\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.gather),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim\", \"dim\"),\n (\"index\", \"index\"),\n (\"sparse_grad\", \"sparse_grad\", this_arg_is_optional),\n ],\n)\n@register_acc_op\ndef gather(*, input, dim, index, sparse_grad=False):\n return torch.gather(input=input, dim=dim, index=index, sparse_grad=sparse_grad)\n\n\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.index_select),\n)\n@register_acc_op\ndef index_select(*, input, dim, index):\n return torch.index_select(input, dim, index)\n\n\n@register_custom_acc_mapper_fn(\n op_and_target=(\"call_method\", \"expand_as\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"other\", \"other\"),\n ],\n)\ndef expand_as_mapper(node: torch.fx.Node, _: nn.Module) -> torch.fx.Node:\n \"\"\"\n Maps expand_as(other) to expand(other.size())\n \"\"\"\n with node.graph.inserting_before(node):\n size_node = node.graph.call_function(\n size, kwargs={\"input\": node.kwargs[\"other\"]}\n )\n size_node.meta[\"type\"] = torch.Size\n\n expand_node = node.graph.call_function(\n expand, kwargs={\"input\": node.kwargs[\"input\"], \"sizes\": size_node}\n )\n expand_node.meta = node.meta.copy()\n return expand_node\n\n\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.nn.functional.interpolate),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"size\", \"size\", this_arg_is_optional),\n (\"scale_factor\", \"scale_factor\", this_arg_is_optional),\n (\"mode\", \"mode\", this_arg_is_optional),\n (\"align_corners\", \"align_corners\", this_arg_is_optional),\n ],\n)\n@register_acc_op\ndef interpolate(\n *,\n input,\n size=None,\n scale_factor=None,\n mode=\"nearest\",\n align_corners=None,\n):\n return torch.nn.functional.interpolate(\n input=input,\n size=size,\n scale_factor=scale_factor,\n mode=mode,\n align_corners=align_corners,\n )\n\n\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.tensor_split),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n ((\"tensor_indices_or_sections\", \"sections\", \"indices\"), \"indices_or_sections\"),\n (\"dim\", \"dim\", this_arg_is_optional),\n ],\n)\n@register_acc_op_mapping(\n op_and_target=(\"call_method\", \"tensor_split\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n ((\"tensor_indices_or_sections\", \"sections\", \"indices\"), \"indices_or_sections\"),\n (\"dim\", \"dim\", this_arg_is_optional),\n ],\n)\n@register_acc_op\ndef tensor_split(*, input, indices_or_sections, dim=0):\n # Need to de-coalesce the indices_or_sections because tensor_split accepts\n # one of three kwarg signatures:\n # * (Tensor input, Tensor tensor_indices_or_sections, int dim)\n # * (Tensor input, int sections, int dim)\n # * (Tensor input, tuple of ints indices, int dim)\n if isinstance(indices_or_sections, torch.Tensor):\n indices_or_sections = indices_or_sections.tolist()\n if isinstance(indices_or_sections, int):\n return torch.tensor_split(input, sections=indices_or_sections, dim=dim)\n elif isinstance(indices_or_sections, Iterable):\n return torch.tensor_split(input, indices=tuple(indices_or_sections), dim=dim)\n else:\n raise RuntimeError(\n f\"Expected int, Iterable or Tensor for \"\n f\"indices_or_sections arg, got: {type(indices_or_sections)}\"\n )\n\n\n@register_acc_op_mapping(\n op_and_target=(\"call_method\", \"new_ones\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"size\", \"size\"),\n (\"dtype\", \"dtype\", this_arg_is_optional),\n (\"device\", \"device\", this_arg_is_optional),\n (\"requires_grad\", \"requires_grad\", this_arg_is_optional),\n ],\n)\n@register_acc_op\ndef new_ones(*, input, size, dtype=None, device=None, requires_grad=False):\n assert requires_grad is False, f\"requires_grad != False, it is {requires_grad}\"\n return input.new_ones(size, dtype=dtype, device=device)\n\n\n@register_acc_op_mapping(\n op_and_target=(\"call_method\", \"new_empty\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"size\", \"size\"),\n (\"dtype\", \"dtype\", this_arg_is_optional),\n (\"device\", \"device\", this_arg_is_optional),\n (\"requires_grad\", \"requires_grad\", this_arg_is_optional),\n ],\n)\n@register_acc_op\ndef new_empty(*, input, size, dtype=None, device=None, requires_grad=False):\n assert requires_grad is False, f\"requires_grad != False, it is {requires_grad}\"\n return input.new_empty(size, dtype=dtype, device=device)\n\n\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.einsum),\n arg_replacement_tuples=[\n (\"equation\", \"equation\"),\n (\"*\", \"operands\"),\n ],\n)\n@register_acc_op\ndef einsum(*, equation, operands):\n return torch.einsum(equation, *operands)\n\n\n@register_acc_op_mapping(\n op_and_target=(\"call_function\", torch.as_strided),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"size\", \"size\"),\n (\"stride\", \"stride\"),\n (\"storage_offset\", \"storage_offset\", this_arg_is_optional),\n ],\n)\n@register_acc_op_mapping(\n op_and_target=(\"call_method\", \"as_strided\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"size\", \"size\"),\n (\"stride\", \"stride\"),\n (\"storage_offset\", \"storage_offset\", this_arg_is_optional),\n ],\n)\n@register_acc_op\ndef as_strided(*, input, size, stride, storage_offset=0):\n return torch.as_strided(\n input=input, size=size, stride=stride, storage_offset=storage_offset\n )\n\n\n@register_acc_op_mapping(op_and_target=(\"call_function\", torch.var))\n@register_acc_op_mapping(\n op_and_target=(\"call_method\", \"var\"),\n arg_replacement_tuples=[\n (\"input\", \"input\"),\n (\"dim\", \"dim\"),\n (\"unbiased\", \"unbiased\"),\n (\"keepdim\", \"keepdim\"),\n ],\n)\n@register_acc_op\ndef var(*, input, dim, unbiased, keepdim=False):\n return torch.var(input=input, dim=dim, unbiased=unbiased, keepdim=keepdim)\n"
] |
[
[
"torch.any",
"torch.randn",
"torch.testing._internal.common_utils.run_tests"
],
[
"torch.fmod",
"torch.nn.quantized.functional.conv2d",
"torch.max",
"torch.sin",
"torch.neg",
"torch.numel",
"torch.acos",
"torch.where",
"torch.topk",
"torch.ops.quantized.embedding_bag_4bit_rowwise_offsets",
"torch.pow",
"torch.sqrt",
"torch.tile",
"torch.logical_xor",
"torch.quantize_per_tensor",
"torch.nn.functional.conv_transpose2d",
"torch.nn.functional.avg_pool2d",
"torch.min",
"torch.exp",
"torch.minimum",
"torch.tan",
"torch.any",
"torch.gather",
"torch.nn.functional.avg_pool1d",
"torch.abs",
"torch.nn.functional.softsign",
"torch.sign",
"torch.sum",
"torch.split",
"torch.logical_and",
"torch.nn.functional.max_pool3d",
"torch.einsum",
"torch.nn.functional.adaptive_avg_pool3d",
"torch.tensor",
"torch.reciprocal",
"torch.nn.functional.elu",
"torch.atan",
"torch.ops.quantized.embedding_bag_byte_rowwise_offsets",
"torch.isinf",
"torch.floor",
"torch.nn.functional.conv3d",
"torch.nn.functional.conv1d",
"torch.linalg.norm",
"torch.nn.functional.hardtanh",
"torch.as_strided",
"torch.nan_to_num",
"torch.matmul",
"torch.maximum",
"torch.cat",
"torch.nn.functional.interpolate",
"torch.nn.functional.conv_transpose3d",
"torch.tensor_split",
"torch.nn.functional.relu",
"torch.nn.functional.selu",
"torch.index_select",
"torch.nn.functional.pad",
"torch.cos",
"torch.nn.functional.layer_norm",
"torch.nn.functional.hardsigmoid",
"torch.nn.functional.conv2d",
"torch.unsqueeze",
"torch.nn.functional.adaptive_avg_pool2d",
"torch.log",
"torch.nn.functional.leaky_relu",
"torch.logical_or",
"torch.cosh",
"torch.ceil",
"torch.ops.quantized.mul",
"torch.ops.quantized.batch_norm2d",
"torch.dequantize",
"torch.chunk",
"torch.cumsum",
"torch.sinh",
"torch.nn.functional.max_pool1d",
"torch.nn.functional.batch_norm",
"torch.nn.functional.softmax",
"torch.mean",
"torch.nn.quantized.functional.linear",
"torch.tanh",
"torch.flatten",
"torch.logical_not",
"torch.nn.functional.embedding_bag",
"torch.asin",
"torch.prod",
"torch.nn.functional.linear",
"torch.nn.functional.max_pool2d",
"torch.div",
"torch.sigmoid",
"torch.nn.functional.gelu",
"torch.var",
"torch.clamp",
"torch.ops.quantized.add"
]
] |
filiparag/petnica-2018-fpga-image-filter
|
[
"fe05e8205c23a14d6ed101bdc7a523146dfd492c"
] |
[
"Software/PriorityDecoder.py"
] |
[
"#! /usr/bin/env python3\n\nimport numpy as np\nimport converter as convert\n\ndef arch_priority_decoder(in_write, in_value):\n\n out_values = np.zeros([256], dtype=np.uint8)\n\n if in_write:\n for value in range(256):\n if convert.bin_to_num(in_value) <= value:\n out_values[value] = 1\n else:\n out_values[value] = 0\n\n return out_values\n\ndef test_priority_decoder():\n\n with open('priority_decoder.in.test', 'r') as test_in, \\\n open('priority_decoder.out', 'w') as test_out:\n \n in_value = convert.binstr_to_bin(test_in.readline().replace('\\n', ''))\n out_values = arch_priority_decoder(1, in_value)\n test_out.write(convert.bin_to_binstr(out_values))\n\ntest_priority_decoder()"
] |
[
[
"numpy.zeros"
]
] |
NSLS-II/databroker
|
[
"a2a5d6600ecf75efdd1c70cb67a0ebe2a1584bbd"
] |
[
"databroker/mongo_normalized.py"
] |
[
"import builtins\nimport collections\nimport collections.abc\nimport copy\nfrom datetime import datetime, timedelta\nimport functools\nimport itertools\nimport json\nimport logging\nimport os\nimport sys\nimport threading\n\nfrom bson.objectid import ObjectId, InvalidId\nimport cachetools\nimport entrypoints\nimport event_model\nfrom dask.array.core import cached_cumsum, normalize_chunks\nimport numpy\nimport pymongo\nimport pymongo.errors\nimport toolz.itertoolz\nimport xarray\n\nfrom tiled.adapters.xarray import DatasetAdapter\nfrom tiled.structures.array import (\n ArrayStructure,\n ArrayMacroStructure,\n BuiltinDtype,\n Kind,\n StructDtype,\n)\nfrom tiled.structures.xarray import (\n DataArrayStructure,\n DataArrayMacroStructure,\n DatasetMacroStructure,\n)\nfrom tiled.adapters.mapping import MapAdapter\nfrom tiled.query_registration import QueryTranslationRegistry\nfrom tiled.queries import FullText\nfrom tiled.utils import (\n SpecialUsers,\n)\nfrom tiled.adapters.utils import (\n tree_repr,\n IndexersMixin,\n)\nfrom tiled.utils import import_object, OneShotCachedMap, UNCHANGED\n\nfrom .common import BlueskyEventStreamMixin, BlueskyRunMixin, CatalogOfBlueskyRunsMixin\nfrom .queries import (\n BlueskyMapAdapter,\n RawMongo,\n _PartialUID,\n _ScanID,\n TimeRange,\n partial_uid,\n scan_id,\n time_range,\n)\nfrom .server import router\n\n\nCHUNK_SIZE_LIMIT = os.getenv(\"DATABROKER_CHUNK_SIZE_LIMIT\", \"100MB\")\nMAX_AD_FRAMES_PER_CHUNK = int(os.getenv(\"DATABROKER_MAX_AD_FRAMES_PER_CHUNK\", \"10\"))\n\nlogger = logging.getLogger(__name__)\n\n\ndef _try_descr(field_metadata):\n descr = field_metadata.get(\"dtype_descr\")\n if descr:\n if len(descr) == 1 and descr[0][0] == \"\":\n return None\n dtype = StructDtype.from_numpy_dtype(numpy.dtype(descr))\n if dtype.max_depth() > 1:\n raise RuntimeError(\n \"We can not yet cope with multiple nested structured dtypes. \"\n f\"{descr}\"\n )\n return dtype\n else:\n return None\n\n\ndef structure_from_descriptor(descriptor, sub_dict, max_seq_num, unicode_columns=None):\n # Build the time coordinate.\n time_shape = (max_seq_num - 1,)\n time_chunks = normalize_chunks(\n (\"auto\",) * len(time_shape),\n shape=time_shape,\n limit=CHUNK_SIZE_LIMIT,\n dtype=FLOAT_DTYPE.to_numpy_dtype(),\n )\n time_variable = ArrayStructure(\n macro=ArrayMacroStructure(\n shape=time_shape,\n chunks=time_chunks,\n dims=[\"time\"],\n ),\n micro=FLOAT_DTYPE,\n )\n time_data_array = DataArrayStructure(\n macro=DataArrayMacroStructure(\n variable=time_variable, coords={}, coord_names=[], name=\"time\"\n ),\n micro=None,\n )\n if unicode_columns is None:\n unicode_columns = {}\n dim_counter = itertools.count()\n data_vars = {}\n metadata = {\"data_vars\": {}, \"coords\": {\"time\": {\"attrs\": {}}}}\n\n for key, field_metadata in descriptor[\"data_keys\"].items():\n # if the EventDescriptor doesn't provide names for the\n # dimensions (it's optional) use the same default dimension\n # names that xarray would.\n try:\n dims = [\"time\"] + field_metadata[\"dims\"]\n except KeyError:\n ndim = len(field_metadata[\"shape\"])\n dims = [\"time\"] + [f\"dim_{next(dim_counter)}\" for _ in range(ndim)]\n attrs = {}\n # Record which object (i.e. device) this column is associated with,\n # which enables one to find the relevant configuration, if any.\n for object_name, keys_ in descriptor.get(\"object_keys\", {}).items():\n for item in keys_:\n if item == key:\n attrs[\"object\"] = object_name\n break\n units = field_metadata.get(\"units\")\n if units:\n if isinstance(units, str):\n attrs[\"units_string\"] = units\n # TODO We may soon add a more structured units type, which\n # would likely be a dict here.\n if sub_dict == \"data\":\n shape = tuple((max_seq_num - 1, *field_metadata[\"shape\"]))\n # if we have a descr, then this is a\n dtype = _try_descr(field_metadata)\n dt_str = field_metadata.get(\"dtype_str\")\n if dtype is not None:\n if len(shape) > 2:\n raise RuntimeError(\n \"We do not yet support general structured arrays, only 1D ones.\"\n )\n # if we have a detailed string, trust that\n elif dt_str is not None:\n dtype = BuiltinDtype.from_numpy_dtype(numpy.dtype(dt_str))\n # otherwise guess!\n else:\n dtype = JSON_DTYPE_TO_MACHINE_DATA_TYPE[field_metadata[\"dtype\"]]\n if dtype.kind == Kind.unicode:\n array = unicode_columns[key]\n dtype = BuiltinDtype.from_numpy_dtype(\n numpy.dtype(f\"<U{array.itemsize // 4}\")\n )\n else:\n # assert sub_dict == \"timestamps\"\n shape = tuple((max_seq_num - 1,))\n dtype = FLOAT_DTYPE\n\n numpy_dtype = dtype.to_numpy_dtype()\n if \"chunks\" in field_metadata:\n # If the Event Descriptor tells us a preferred chunking, use that.\n suggested_chunks = field_metadata[\"chunks\"]\n elif (0 in shape) or (numpy_dtype.itemsize == 0):\n # special case to avoid warning from dask\n suggested_chunks = shape\n elif len(shape) == 4:\n # TEMP: Special-case 4D data in a way that optimzes single-frame\n # access of area detector data.\n # If we choose 1 that would make single-frame access fast\n # but many-frame access too slow.\n suggested_chunks = (\n min(MAX_AD_FRAMES_PER_CHUNK, shape[0]),\n min(MAX_AD_FRAMES_PER_CHUNK, shape[1]),\n \"auto\",\n \"auto\",\n )\n else:\n suggested_chunks = (\"auto\",) * len(shape)\n\n try:\n chunks = normalize_chunks(\n suggested_chunks,\n shape=shape,\n limit=CHUNK_SIZE_LIMIT,\n dtype=numpy_dtype,\n )\n except Exception as err:\n raise ValueError(\n \"Failed to normalize chunks with suggested_chunks. Params: \"\n f\"suggested_chunks={suggested_chunks} \"\n f\"shape={shape} \"\n f\"limit={CHUNK_SIZE_LIMIT} \"\n f\"dtype={numpy_dtype}\"\n ) from err\n\n variable = ArrayStructure(\n macro=ArrayMacroStructure(shape=shape, chunks=chunks, dims=dims),\n micro=dtype,\n )\n data_array = DataArrayStructure(\n macro=DataArrayMacroStructure(\n variable, coords={}, coord_names=[\"time\"], name=key\n ),\n micro=None,\n )\n data_vars[key] = data_array\n metadata[\"data_vars\"][key] = {\"attrs\": attrs}\n\n return (\n DatasetMacroStructure(data_vars=data_vars, coords={\"time\": time_data_array}),\n metadata,\n )\n\n\nclass BlueskyRun(MapAdapter, BlueskyRunMixin):\n specs = [\"BlueskyRun\"]\n\n def __init__(\n self,\n *args,\n handler_registry,\n transforms,\n root_map,\n datum_collection,\n resource_collection,\n **kwargs,\n ):\n super().__init__(*args, **kwargs)\n self.transforms = transforms or {}\n self.root_map = root_map\n self._datum_collection = datum_collection\n self._resource_collection = resource_collection\n # This is used to create the Filler on first access.\n self._init_handler_registry = handler_registry\n self._filler = None\n self._filler_creation_lock = threading.RLock()\n\n def must_revalidate(self):\n return self._metadata[\"stop\"] is not None\n\n @property\n def metadata_stale_at(self):\n return datetime.utcnow() + timedelta(hours=1)\n\n @property\n def entries_stale_at(self):\n if self._metadata[\"stop\"] is not None:\n return datetime.utcnow() + timedelta(hours=1)\n\n @property\n def metadata(self):\n \"Metadata about this MongoAdapter.\"\n # If there are transforms configured, shadow the 'start' and 'stop' documents\n # with transfomed copies.\n transformed = {}\n if \"start\" in self.transforms:\n transformed[\"start\"] = self.transforms[\"start\"](self._metadata[\"start\"])\n if \"stop\" in self.transforms:\n transformed[\"stop\"] = self.transforms[\"stop\"](self._metadata[\"stop\"])\n metadata = dict(collections.ChainMap(transformed, self._metadata))\n return metadata\n\n @property\n def filler(self):\n # Often multiple requests prompt this to be created in parallel.\n # We need this to be threadsafe.\n with self._filler_creation_lock:\n if self._filler is None:\n filler = event_model.Filler(\n handler_registry=self._init_handler_registry,\n root_map=self.root_map,\n inplace=False,\n )\n for descriptor in itertools.chain(\n *(stream.metadata[\"descriptors\"] for stream in self.values())\n ):\n filler(\"descriptor\", descriptor)\n self._filler = filler\n return self._filler\n\n @property\n def register_handler(self):\n return self.filler.register_handler\n\n @property\n def deregister_handler(self):\n return self.filler.deregister_handler\n\n @property\n def handler_registry(self):\n return self.filler.handler_registry\n\n def new_variation(self, *args, **kwargs):\n return super().new_variation(\n *args,\n handler_registry=self.handler_registry,\n transforms=self.transforms,\n root_map=self.root_map,\n datum_collection=self._datum_collection,\n resource_collection=self._resource_collection,\n **kwargs,\n )\n\n def get_datum_for_resource(self, resource_uid):\n return self._datum_collection.find({\"resource\": resource_uid}, {\"_id\": False})\n\n def get_resource(self, uid):\n doc = self._resource_collection.find_one({\"uid\": uid}, {\"_id\": False})\n\n # Some old resource documents don't have a 'uid' and they are\n # referenced by '_id'.\n if doc is None:\n try:\n _id = ObjectId(uid)\n except InvalidId:\n pass\n else:\n doc = self._resource_collection.find_one({\"_id\": _id}, {\"_id\": False})\n doc[\"uid\"] = uid\n\n if doc is None:\n raise ValueError(f\"Could not find Resource with uid={uid}\")\n if \"resource\" in self.transforms:\n transformed_doc = self.transforms[\"resource\"](doc)\n else:\n transformed_doc = doc\n return transformed_doc\n\n def lookup_resource_for_datum(self, datum_id):\n doc = self._datum_collection.find_one({\"datum_id\": datum_id})\n if doc is None:\n raise ValueError(f\"Could not find Datum with datum_id={datum_id}\")\n return doc[\"resource\"]\n\n def single_documents(self, fill):\n if fill:\n raise NotImplementedError(\"Only fill=False is implemented.\")\n external_fields = {} # map descriptor uid to set of external fields\n datum_cache = {} # map datum_id to datum document\n # Track which Resource and Datum documents we have yielded so far.\n resource_uids = set()\n datum_ids = set()\n # Interleave the documents from the streams in time order.\n merged_iter = toolz.itertoolz.merge_sorted(\n *(stream.iter_descriptors_and_events() for stream in self.values()),\n key=lambda item: item[1][\"time\"],\n )\n yield (\"start\", self.metadata[\"start\"])\n for name, doc in merged_iter:\n # Insert Datum, Resource as needed, and then yield (name, doc).\n if name == \"event\":\n for field in external_fields[doc[\"descriptor\"]]:\n datum_id = doc[\"data\"][field]\n if datum_ids not in datum_ids:\n # We haven't yielded this Datum yet. Look it up, and yield it.\n try:\n # Check to see if it's been pre-fetched.\n datum = datum_cache.pop(datum_id)\n except KeyError:\n resource_uid = self.lookup_resource_for_datum(datum_id)\n if resource_uid not in resource_uids:\n # We haven't yielded this Resource yet. Look it up, and yield it.\n resource = self.get_resource(resource_uid)\n resource_uids.add(resource_uid)\n yield (\"resource\", resource)\n # Pre-fetch *all* the Datum documents for this resource in one query.\n datum_cache.update(\n {\n doc[\"datum_id\"]: doc\n for doc in self.get_datum_for_resource(\n resource_uid\n )\n }\n )\n # Now get the Datum we originally were looking for.\n datum = datum_cache.pop(datum_id)\n datum_ids.add(datum_id)\n yield (\"datum\", datum)\n elif name == \"descriptor\":\n # Track which fields (\"data keys\") hold references to external data.\n external_fields[doc[\"uid\"]] = {\n key\n for key, value in doc[\"data_keys\"].items()\n if value.get(\"external\")\n }\n yield name, doc\n stop_doc = self.metadata[\"stop\"]\n if stop_doc is not None:\n yield (\"stop\", stop_doc)\n\n def documents(self, fill, size=25):\n \"\"\"\n Yield ``(name, document)`` items from the run.\n\n Batch Event and Datum documents into pages of up to ``size`` rows,\n while preserving time-ordering.\n \"\"\"\n yield from batch_documents(self.single_documents(fill=fill), size)\n\n\nclass BlueskyEventStream(MapAdapter, BlueskyEventStreamMixin):\n specs = [\"BlueskyEventStream\"]\n\n def __init__(self, *args, event_collection, cutoff_seq_num, run, **kwargs):\n super().__init__(*args, **kwargs)\n self._event_collection = event_collection\n self._cutoff_seq_num = cutoff_seq_num\n self._run = run\n\n @property\n def must_revalidate(self):\n # The keys in this node are *always* stable.\n return False\n\n @property\n def metadata_stale_at(self):\n if self._run.metadata[\"stop\"] is not None:\n return datetime.utcnow() + timedelta(hours=1)\n return datetime.utcnow() + timedelta(hours=1)\n\n @property\n def entries_stale_at(self):\n if self._run.metadata[\"stop\"] is not None:\n return datetime.utcnow() + timedelta(hours=1)\n\n @property\n def metadata(self):\n # If there are transforms configured, shadow the 'descriptor' documents\n # with transfomed copies.\n transformed = {}\n transforms = self._run.transforms\n if \"descriptor\" in transforms:\n transformed[\"descriptors\"] = [\n transforms[\"descriptor\"](d) for d in self._metadata[\"descriptors\"]\n ]\n metadata = dict(collections.ChainMap(transformed, self._metadata))\n return metadata\n\n def new_variation(self, **kwargs):\n return super().new_variation(\n event_collection=self._event_collection,\n cutoff_seq_num=self._cutoff_seq_num,\n run=self._run,\n **kwargs,\n )\n\n def iter_descriptors_and_events(self):\n for descriptor in sorted(self.metadata[\"descriptors\"], key=lambda d: d[\"time\"]):\n yield (\"descriptor\", descriptor)\n # TODO Grab paginated chunks.\n events = list(\n self._event_collection.find(\n {\n \"descriptor\": descriptor[\"uid\"],\n \"seq_num\": {\"$lte\": self._cutoff_seq_num},\n },\n {\"_id\": False},\n sort=[(\"time\", pymongo.ASCENDING)],\n )\n )\n for event in events:\n yield (\"event\", event)\n\n\nclass ArrayFromDocuments:\n\n structure_family = \"array\"\n metadata = {}\n\n def __init__(self, data_array_adapter):\n self._data_array_adapter = data_array_adapter\n\n def read(self, slice):\n return self._data_array_adapter.read(slice)\n\n def read_block(self, block, slice=None):\n return self._data_array_adapter.read_block(block, slice=slice)\n\n def macrostructure(self):\n return self._data_array_adapter.macrostructure().variable.macro\n\n def microstructure(self):\n return self._data_array_adapter.macrostructure().variable.micro\n\n\nclass TimeArrayFromDocuments:\n\n structure_family = \"array\"\n metadata = {}\n\n def __init__(self, data_array_adapter):\n self._data_array_adapter = data_array_adapter\n\n def read(self, slice):\n return self._data_array_adapter.read(slice)\n\n def read_block(self, block, slice=None):\n return self._data_array_adapter.read_block(None, block, coord=\"time\", slice=slice)\n\n def macrostructure(self):\n return self._data_array_adapter.macrostructure().coords[\"time\"].macro\n\n def microstructure(self):\n return self._data_array_adapter.macrostructure().coords[\"time\"].micro\n\n\nclass DataArrayFromDocuments:\n \"\"\"\n Represents one column\n \"\"\"\n\n structure_family = \"xarray_data_array\"\n\n def __init__(self, dataset_adapter, field):\n self._dataset_adapter = dataset_adapter\n self._field = field\n self.metadata = dataset_adapter.metadata[\"data_vars\"].get(field, {})\n\n def read_block(self, block, slice=None):\n return self._dataset_adapter.read_block(self._field, block, slice=slice)\n\n def read(self, slice=None):\n da = self._dataset_adapter.read(fields=[self._field])[self._field]\n if slice:\n da = da[slice]\n return da\n\n def __getitem__(self, key):\n if key == \"variable\":\n return ArrayFromDocuments(self)\n elif key == \"coords\":\n return MapAdapter({\"time\": TimeArrayFromDocuments(self)})\n else:\n raise KeyError(key)\n\n def macrostructure(self):\n return self._dataset_adapter.macrostructure().data_vars[self._field].macro\n\n def microstructure(self):\n return self._dataset_adapter.macrostructure().data_vars[self._field].micro\n\n\nclass DatasetFromDocuments:\n \"\"\"\n An xarray.Dataset from a sub-dict of an Event stream\n \"\"\"\n\n structure_family = \"xarray_dataset\"\n\n def __init__(\n self,\n *,\n run,\n stream_name,\n cutoff_seq_num,\n event_descriptors,\n event_collection,\n root_map,\n sub_dict,\n metadata=None,\n ):\n self._run = run\n self._stream_name = stream_name\n self._cutoff_seq_num = cutoff_seq_num\n self._event_descriptors = event_descriptors\n self._event_collection = event_collection\n self._sub_dict = sub_dict\n self.root_map = root_map\n\n # metadata should look like\n # {\n # \"stream_name\": \"...\",\n # \"descriptors\": [...],\n # \"attrs\": {...},\n # \"data_vars\": {...},\n # \"coords\": {\"time\": {}},\n # }\n # We intentionally do not put the descriptors in attrs (ruins UI)\n # but we put the stream_name there.\n self.metadata = self._run[\n self._stream_name\n ].metadata.copy() # {\"descriptors\": [...], \"stream_name: \"...\"}\n # Put the stream_name in attrs so it shows up in the xarray repr.\n self.metadata[\"attrs\"] = {\"stream_name\": self.metadata[\"stream_name\"]}\n\n # The `data_keys` in a series of Event Descriptor documents with the same\n # `name` MUST be alike, so we can choose one arbitrarily.\n # IMPORTANT: Access via self.metadata so that the transforms are applied.\n descriptor, *_ = self.metadata[\"descriptors\"]\n unicode_columns = {}\n if self._sub_dict == \"data\":\n # Collect the keys (column names) that are of unicode data type.\n unicode_keys = []\n for key, field_metadata in descriptor[\"data_keys\"].items():\n if field_metadata[\"dtype\"] == \"string\":\n # Skip this if it has a dtype_str with an itemsize.\n dtype_str = field_metadata.get(\"dtype_str\")\n if dtype_str is not None:\n if numpy.dtype(dtype_str).itemsize != 0:\n continue\n unicode_keys.append(key)\n # Load the all the data for unicode columns to figure out the itemsize.\n # We have no other choice, except to *guess* but we'd be in\n # trouble if our guess were too small, and we'll waste space\n # if our guess is too large.\n if unicode_keys:\n unicode_columns.update(self._get_columns(unicode_keys, slices=None))\n\n self._macrostructure, metadata = structure_from_descriptor(\n descriptor, self._sub_dict, self._cutoff_seq_num, unicode_columns\n )\n self.metadata.update(metadata) # adds \"data_vars\" and \"coords\"\n self._data_vars = MapAdapter(\n {\n field: DataArrayFromDocuments(self, field)\n for field in self._macrostructure.data_vars\n }\n )\n self._coords = MapAdapter(\n {\"time\": MapAdapter({\"variable\": TimeArrayFromDocuments(self)})}\n )\n\n def __repr__(self):\n return f\"<{type(self).__name__}>\"\n\n @property\n def metadata_stale_at(self):\n if self._run.metadata[\"stop\"] is not None:\n return datetime.utcnow() + timedelta(hours=1)\n return datetime.utcnow() + timedelta(hours=1)\n\n @property\n def content_stale_at(self):\n if self._run.metadata[\"stop\"] is not None:\n return datetime.utcnow() + timedelta(hours=1)\n\n def macrostructure(self):\n return self._macrostructure\n\n def microstructure(self):\n return None\n\n def read(self, fields=None):\n # num_blocks = (range(len(n)) for n in chunks)\n # for block in itertools.product(*num_blocks):\n structure = self.macrostructure()\n data_arrays = {}\n if fields is None:\n keys = list(structure.data_vars)\n else:\n keys = fields\n columns = self._get_columns(keys, slices=None)\n # Build the time coordinate.\n time_coord = self._get_time_coord(slice_params=None)\n for key, data_array in structure.data_vars.items():\n if (fields is not None) and (key not in fields):\n continue\n variable = structure.data_vars[key].macro.variable\n dtype = variable.micro.to_numpy_dtype()\n raw_array = columns[key]\n if raw_array.dtype != dtype:\n logger.warning(\n f\"{key!r} actually has dtype {raw_array.dtype.str!r} \"\n f\"but was reported as having dtype {dtype.str!r}. \"\n \"It will be converted to the reported type, \"\n \"but this should be fixed by setting 'dtype_str' \"\n \"in the data_key of the EventDescriptor. \"\n f\"RunStart UID: {self._run.metadata['start']['uid']!r}\"\n )\n array = raw_array.astype(dtype)\n else:\n array = raw_array\n data_array = xarray.DataArray(\n array,\n attrs=self.metadata[\"data_vars\"][key][\"attrs\"],\n dims=variable.macro.dims,\n coords={\"time\": time_coord},\n )\n data_arrays[key] = data_array\n return xarray.Dataset(data_arrays, coords={\"time\": time_coord})\n\n def __getitem__(self, key):\n if key == \"data_vars\":\n return self._data_vars\n elif key == \"coords\":\n return self._coords\n else:\n raise KeyError(key)\n\n def read_block(self, variable, block, coord=None, slice=None):\n structure = self.macrostructure()\n if coord == \"time\":\n data_structure = structure.coords[\"time\"].macro.variable\n chunks = data_structure.macro.chunks\n cumdims = [cached_cumsum(bds, initial_zero=True) for bds in chunks]\n slices_for_chunks = [\n [builtins.slice(s, s + dim) for s, dim in zip(starts, shapes)]\n for starts, shapes in zip(cumdims, chunks)\n ]\n (slice_,) = [s[index] for s, index in zip(slices_for_chunks, block)]\n return self._get_time_coord(slice_params=(slice_.start, slice_.stop))\n elif coord is not None:\n # We only have a \"time\" coordinate. Any other coordinate is invalid.\n raise KeyError(coord)\n dtype = structure.data_vars[variable].macro.variable.micro.to_numpy_dtype()\n data_structure = structure.data_vars[variable].macro.variable\n dtype = data_structure.micro.to_numpy_dtype()\n chunks = data_structure.macro.chunks\n cumdims = [cached_cumsum(bds, initial_zero=True) for bds in chunks]\n slices_for_chunks = [\n [builtins.slice(s, s + dim) for s, dim in zip(starts, shapes)]\n for starts, shapes in zip(cumdims, chunks)\n ]\n slices = [s[index] for s, index in zip(slices_for_chunks, block)]\n raw_array = self._get_columns([variable], slices=slices)[variable]\n if raw_array.dtype != dtype:\n logger.warning(\n f\"{variable!r} actually has dtype {raw_array.dtype.str!r} \"\n f\"but was reported as having dtype {dtype.str!r}. \"\n \"It will be converted to the reported type, \"\n \"but this should be fixed by setting 'dtype_str' \"\n \"in the data_key of the EventDescriptor. \"\n f\"RunStart UID: {self._run.metadata['start']['uid']!r}\"\n )\n array = raw_array.astype(dtype)\n else:\n array = raw_array\n if slice is not None:\n array = array[slice]\n return array\n\n @functools.lru_cache(maxsize=1024)\n def _get_time_coord(self, slice_params):\n if slice_params is None:\n min_seq_num = 1\n max_seq_num = self._cutoff_seq_num\n else:\n min_seq_num = 1 + slice_params[0]\n max_seq_num = 1 + slice_params[1]\n column = []\n descriptor_uids = [doc[\"uid\"] for doc in self.metadata[\"descriptors\"]]\n\n def populate_column(min_seq_num, max_seq_num):\n cursor = self._event_collection.aggregate(\n [\n # Select Events for this Descriptor with the appropriate seq_num range.\n {\n \"$match\": {\n \"descriptor\": {\"$in\": descriptor_uids},\n # It's important to use a half-open interval here\n # so that the boundaries work.\n \"seq_num\": {\"$gte\": min_seq_num, \"$lt\": max_seq_num},\n },\n },\n # Include only the fields of interest.\n {\n \"$project\": {\"descriptor\": 1, \"seq_num\": 1, \"time\": 1},\n },\n # Sort by time.\n {\"$sort\": {\"time\": 1}},\n # If seq_num is repeated, take the latest one.\n {\n \"$group\": {\n \"_id\": \"$seq_num\",\n \"doc\": {\"$last\": \"$$ROOT\"},\n },\n },\n # Re-sort, now by seq_num which *should* be equivalent to\n # sorting by time but could not be in weird cases\n # (which I'm not aware have ever occurred) where an NTP sync\n # moves system time backward mid-run.\n {\"$sort\": {\"doc.seq_num\": 1}},\n # Extract the column of interest as an array.\n {\n \"$group\": {\n \"_id\": \"$descriptor\",\n \"column\": {\"$push\": \"$doc.time\"},\n },\n },\n ]\n )\n (result,) = cursor\n column.extend(result[\"column\"])\n\n # Aim for 10 MB pages to stay safely clear the MongoDB's hard limit\n # of 16 MB.\n TARGET_PAGE_BYTESIZE = 10_000_000\n\n page_size = TARGET_PAGE_BYTESIZE // 8 # estimated row byte size is 8\n boundaries = list(range(min_seq_num, 1 + max_seq_num, page_size))\n if boundaries[-1] != max_seq_num:\n boundaries.append(max_seq_num)\n for min_, max_ in zip(boundaries[:-1], boundaries[1:]):\n populate_column(min_, max_)\n\n return numpy.array(column)\n\n def _get_columns(self, keys, slices):\n if slices is None:\n min_seq_num = 1\n max_seq_num = self._cutoff_seq_num\n else:\n slice_ = slices[0]\n min_seq_num = 1 + slice_.start\n max_seq_num = 1 + slice_.stop\n\n to_stack = self._inner_get_columns(tuple(keys), min_seq_num, max_seq_num)\n\n result = {}\n for key, value in to_stack.items():\n array = numpy.stack(value)\n if slices:\n sliced_array = array[(..., *slices[1:])]\n else:\n sliced_array = array\n result[key] = sliced_array\n\n return result\n\n @functools.lru_cache(maxsize=1024)\n def _inner_get_columns(self, keys, min_seq_num, max_seq_num):\n columns = {key: [] for key in keys}\n # IMPORTANT: Access via self.metadata so that transforms are applied.\n descriptors = self.metadata[\"descriptors\"]\n descriptor_uids = [doc[\"uid\"] for doc in descriptors]\n # The `data_keys` in a series of Event Descriptor documents with the\n # same `name` MUST be alike, so we can just use the first one.\n data_keys = [descriptors[0][\"data_keys\"][key] for key in keys]\n is_externals = [\"external\" in data_key for data_key in data_keys]\n expected_shapes = [tuple(data_key[\"shape\"] or []) for data_key in data_keys]\n\n def populate_columns(keys, min_seq_num, max_seq_num):\n # This closes over the local variable columns and appends to its\n # contents.\n cursor = self._event_collection.aggregate(\n [\n # Select Events for this Descriptor with the appropriate seq_num range.\n {\n \"$match\": {\n \"descriptor\": {\"$in\": descriptor_uids},\n # It's important to use a half-open interval here\n # so that the boundaries work.\n \"seq_num\": {\"$gte\": min_seq_num, \"$lt\": max_seq_num},\n },\n },\n # Include only the fields of interest.\n {\n \"$project\": {\n \"descriptor\": 1,\n \"seq_num\": 1,\n **{f\"{self._sub_dict}.{key}\": 1 for key in keys},\n },\n },\n # Sort by time.\n {\"$sort\": {\"time\": 1}},\n # If seq_num is repeated, take the latest one.\n {\n \"$group\": {\n \"_id\": \"$seq_num\",\n \"doc\": {\"$last\": \"$$ROOT\"},\n },\n },\n # Re-sort, now by seq_num which *should* be equivalent to\n # sorting by time but could not be in weird cases\n # (which I'm not aware have ever occurred) where an NTP sync\n # moves system time backward mid-run.\n {\"$sort\": {\"doc.seq_num\": 1}},\n # Extract the column of interest as an array.\n {\n \"$group\": {\n \"_id\": \"$descriptor\",\n **{\n key: {\"$push\": f\"$doc.{self._sub_dict}.{key}\"}\n for key in keys\n },\n },\n },\n ]\n )\n (result,) = cursor\n for key, expected_shape, is_external in zip(\n keys, expected_shapes, is_externals\n ):\n if expected_shape and (not is_external):\n validated_column = list(\n map(\n lambda item: _validate_shape(\n key, numpy.asarray(item), expected_shape\n ),\n result[key],\n )\n )\n else:\n validated_column = result[key]\n columns[key].extend(validated_column)\n\n scalars = []\n nonscalars = []\n estimated_nonscalar_row_bytesizes = []\n estimated_scalar_row_bytesize = 0\n for key, data_key, is_external in zip(keys, data_keys, is_externals):\n if (not data_key[\"shape\"]) or is_external:\n # This is either a literal scalar value of a datum_id.\n scalars.append(key)\n if data_key[\"dtype\"] == \"string\":\n # Give a generous amount of headroom here.\n estimated_scalar_row_bytesize += 10_000 # 10 kB\n else:\n # 64-bit integer or float\n estimated_scalar_row_bytesize += 8\n else:\n nonscalars.append(key)\n estimated_nonscalar_row_bytesizes.append(\n numpy.product(data_key[\"shape\"]) * 8\n )\n\n # Aim for 10 MB pages to stay safely clear the MongoDB's hard limit\n # of 16 MB.\n TARGET_PAGE_BYTESIZE = 10_000_000\n\n # Fetch scalars all together.\n if scalars:\n page_size = TARGET_PAGE_BYTESIZE // estimated_scalar_row_bytesize\n boundaries = list(range(min_seq_num, 1 + max_seq_num, page_size))\n if boundaries[-1] != max_seq_num:\n boundaries.append(max_seq_num)\n for min_, max_ in zip(boundaries[:-1], boundaries[1:]):\n populate_columns(tuple(scalars), min_, max_)\n\n # Fetch each nonscalar column individually.\n # TODO We could batch a couple nonscalar columns at at ime based on\n # their size if we need to squeeze more performance out here. But maybe\n # we can get away with never adding that complexity.\n for key, est_row_bytesize in zip(nonscalars, estimated_nonscalar_row_bytesizes):\n page_size = TARGET_PAGE_BYTESIZE // est_row_bytesize\n boundaries = list(range(min_seq_num, 1 + max_seq_num, page_size))\n if boundaries[-1] != max_seq_num:\n boundaries.append(max_seq_num)\n for min_, max_ in zip(boundaries[:-1], boundaries[1:]):\n populate_columns((key,), min_, max_)\n\n # If data is external, we now have a column of datum_ids, and we need\n # to look up the data that they reference.\n to_stack = collections.defaultdict(list)\n # Any arbitrary valid descriptor uid will work; we just need to satisfy\n # the Filler with our mocked Event below. So we pick the first one.\n descriptor_uid = descriptor_uids[0]\n for key, expected_shape, is_external in zip(\n keys, expected_shapes, is_externals\n ):\n column = columns[key]\n if is_external:\n filled_column = []\n for datum_id in column:\n # HACK to adapt Filler which is designed to consume whole,\n # streamed documents, to this column-based access mode.\n mock_event = {\n \"data\": {key: datum_id},\n \"descriptor\": descriptor_uid,\n \"uid\": \"PLACEHOLDER\",\n \"filled\": {key: False},\n }\n filled_mock_event = _fill(\n self._run.filler,\n mock_event,\n self._run.lookup_resource_for_datum,\n self._run.get_resource,\n self._run.get_datum_for_resource,\n last_datum_id=None,\n )\n filled_data = filled_mock_event[\"data\"][key]\n validated_filled_data = _validate_shape(\n key, filled_data, expected_shape\n )\n filled_column.append(validated_filled_data)\n to_stack[key].extend(filled_column)\n else:\n to_stack[key].extend(column)\n\n return to_stack\n\n\nclass Config(MapAdapter):\n \"\"\"\n MongoAdapter of configuration datasets, keyed on 'object' (e.g. device)\n \"\"\"\n\n ...\n\n\ndef build_config_xarray(\n *,\n event_descriptors,\n sub_dict,\n object_name,\n):\n first_descriptor, *_ = event_descriptors\n data_keys = first_descriptor[\"configuration\"][object_name][\"data_keys\"]\n # All the data is stored in-line in the Event Descriptor documents.\n # The overwhelming majority of Runs have just one Event Descriptor,\n # and those that have more than one have only a couple, so we do\n # slow appending loop here knowing that we won't pay for too\n # many iterations except in vanishingly rare pathological cases.\n raw_columns = {key: [] for key in data_keys}\n for descriptor in event_descriptors:\n for key in data_keys:\n raw_columns[key].append(\n descriptor[\"configuration\"][object_name][sub_dict][key]\n )\n # Enforce dtype.\n columns = {}\n for key, column in raw_columns.items():\n field_metadata = data_keys[key]\n dtype = _try_descr(field_metadata)\n dt_str = field_metadata.get(\"dtype_str\")\n if dtype is not None:\n if len(getattr(column[0], \"shape\", ())) > 2:\n raise RuntimeError(\n \"We do not yet support general structured arrays, only 1D ones.\"\n )\n numpy_dtype = dtype.to_numpy_dtype()\n # if we have a detailed string, trust that\n elif dt_str is not None:\n numpy_dtype = numpy.dtype(dt_str)\n # otherwise guess!\n else:\n numpy_dtype = JSON_DTYPE_TO_MACHINE_DATA_TYPE[\n field_metadata[\"dtype\"]\n ].to_numpy_dtype()\n columns[key] = numpy.array(column, dtype=numpy_dtype)\n data_arrays = {}\n dim_counter = itertools.count()\n for key, field_metadata in data_keys.items():\n attrs = {}\n if sub_dict == \"data\":\n # if the EventDescriptor doesn't provide names for the\n # dimensions (it's optional) use the same default dimension\n # names that xarray would.\n try:\n dims = [\"time\"] + field_metadata[\"dims\"]\n except KeyError:\n ndim = len(field_metadata[\"shape\"])\n dims = [\"time\"] + [f\"dim_{next(dim_counter)}\" for _ in range(ndim)]\n units = field_metadata.get(\"units\")\n if units:\n if isinstance(units, str):\n attrs[\"units_string\"] = units\n # TODO We may soon add a more structured units type, which\n # would likely be a dict here.\n else:\n dims = [\"time\"]\n data_array = xarray.DataArray(columns[key], dims=dims, attrs=attrs)\n data_arrays[key] = data_array\n ds = xarray.Dataset(data_arrays)\n return DatasetAdapter(ds)\n\n\nclass MongoAdapter(collections.abc.Mapping, CatalogOfBlueskyRunsMixin, IndexersMixin):\n structure_family = \"node\"\n specs = [\"CatalogOfBlueskyRuns\"]\n\n # Define classmethods for managing what queries this MongoAdapter knows.\n query_registry = QueryTranslationRegistry()\n register_query = query_registry.register\n register_query_lazy = query_registry.register_lazy\n\n # Add a /documents route to the server.\n include_routers = [router]\n\n @classmethod\n def from_uri(\n cls,\n uri,\n *,\n asset_registry_uri=None,\n handler_registry=None,\n root_map=None,\n transforms=None,\n metadata=None,\n access_policy=None,\n principal=None,\n cache_ttl_complete=60, # seconds\n cache_ttl_partial=2, # seconds\n ):\n \"\"\"\n Create a MongoAdapter from MongoDB with the \"normalized\" (original) layout.\n\n Parameters\n ----------\n uri: str\n MongoDB URI with database name, formed like \"mongodb://HOSTNAME:27017/DATABASE_NAME\"\n or \"mongodb://USER:PASSWORD@HOSTNAME:27017/DATABASE_NAME?authSource=admin\".\n asset_registry_uri: str\n A separate URI for legacy deployments that place Resource and Datum documents\n in a different database from the rest of the documents. (This is believed to\n only be needed for old deployments at BNL NSLS-II.)\n handler_registry: dict, optional\n Maps each 'spec' (a string identifying a given type or external\n resource) to a handler class.\n\n A 'handler class' may be any callable with the signature::\n\n handler_class(resource_path, root, **resource_kwargs)\n\n It is expected to return an object, a 'handler instance', which is also\n callable and has the following signature::\n\n handler_instance(**datum_kwargs)\n\n As the names 'handler class' and 'handler instance' suggest, this is\n typically implemented using a class that implements ``__init__`` and\n ``__call__``, with the respective signatures. But in general it may be\n any callable-that-returns-a-callable.\n root_map: dict, optional\n str -> str mapping to account for temporarily moved/copied/remounted\n files. Any resources which have a ``root`` in ``root_map`` will be\n loaded using the mapped ``root``.\n transforms: dict\n A dict that maps any subset of the keys {start, stop, resource, descriptor}\n to a function that accepts a document of the corresponding type and\n returns it, potentially modified. This feature is for patching up\n erroneous metadata. It is intended for quick, temporary fixes that\n may later be applied permanently to the data at rest\n (e.g., via a database migration).\n cache_ttl_partial : float\n Time (in seconds) to cache a *partial* (i.e. incomplete, ongoing)\n BlueskyRun before checking the database for updates. Default 2.\n cache_ttl_complete : float\n Time (in seconds) to cache a *complete* BlueskyRun before checking\n the database for updates. Default 60.\n \"\"\"\n metadatastore_db = _get_database(uri)\n if asset_registry_uri is None:\n asset_registry_db = metadatastore_db\n else:\n asset_registry_db = _get_database(asset_registry_uri)\n root_map = root_map or {}\n transforms = parse_transforms(transforms)\n if handler_registry is None:\n handler_registry = discover_handlers()\n handler_registry = parse_handler_registry(handler_registry)\n # Two different caches with different eviction rules.\n cache_of_complete_bluesky_runs = cachetools.TTLCache(\n ttl=cache_ttl_complete, maxsize=100\n )\n cache_of_partial_bluesky_runs = cachetools.TTLCache(\n ttl=cache_ttl_partial, maxsize=100\n )\n return cls(\n metadatastore_db=metadatastore_db,\n asset_registry_db=asset_registry_db,\n handler_registry=handler_registry,\n root_map=root_map,\n transforms=transforms,\n cache_of_complete_bluesky_runs=cache_of_complete_bluesky_runs,\n cache_of_partial_bluesky_runs=cache_of_partial_bluesky_runs,\n metadata=metadata,\n access_policy=access_policy,\n principal=principal,\n )\n\n @classmethod\n def from_mongomock(\n cls,\n *,\n handler_registry=None,\n root_map=None,\n transforms=None,\n metadata=None,\n access_policy=None,\n principal=None,\n cache_ttl_complete=60, # seconds\n cache_ttl_partial=2, # seconds\n ):\n \"\"\"\n Create a transient MongoAdapter from backed by \"mongomock\".\n\n This is intended for testing, teaching, an demos. The data does not\n persistent. Do not use this for anything important.\n\n Parameters\n ----------\n handler_registry: dict, optional\n Maps each 'spec' (a string identifying a given type or external\n resource) to a handler class.\n\n A 'handler class' may be any callable with the signature::\n\n handler_class(resource_path, root, **resource_kwargs)\n\n It is expected to return an object, a 'handler instance', which is also\n callable and has the following signature::\n\n handler_instance(**datum_kwargs)\n\n As the names 'handler class' and 'handler instance' suggest, this is\n typically implemented using a class that implements ``__init__`` and\n ``__call__``, with the respective signatures. But in general it may be\n any callable-that-returns-a-callable.\n root_map: dict, optional\n str -> str mapping to account for temporarily moved/copied/remounted\n files. Any resources which have a ``root`` in ``root_map`` will be\n loaded using the mapped ``root``.\n transforms: dict\n A dict that maps any subset of the keys {start, stop, resource, descriptor}\n to a function that accepts a document of the corresponding type and\n returns it, potentially modified. This feature is for patching up\n erroneous metadata. It is intended for quick, temporary fixes that\n may later be applied permanently to the data at rest\n (e.g., via a database migration).\n cache_ttl_partial : float\n Time (in seconds) to cache a *partial* (i.e. incomplete, ongoing)\n BlueskyRun before checking the database for updates. Default 2.\n cache_ttl_complete : float\n Time (in seconds) to cache a *complete* BlueskyRun before checking\n the database for updates. Default 60.\n \"\"\"\n import mongomock\n\n client = mongomock.MongoClient()\n metadatastore_db = asset_registry_db = client[\"mock_database\"]\n root_map = root_map or {}\n transforms = parse_transforms(transforms)\n if handler_registry is None:\n handler_registry = discover_handlers()\n handler_registry = parse_handler_registry(handler_registry)\n # Two different caches with different eviction rules.\n cache_of_complete_bluesky_runs = cachetools.TTLCache(\n ttl=cache_ttl_complete, maxsize=100\n )\n cache_of_partial_bluesky_runs = cachetools.TTLCache(\n ttl=cache_ttl_partial, maxsize=100\n )\n return cls(\n metadatastore_db=metadatastore_db,\n asset_registry_db=asset_registry_db,\n handler_registry=handler_registry,\n root_map=root_map,\n transforms=transforms,\n cache_of_complete_bluesky_runs=cache_of_complete_bluesky_runs,\n cache_of_partial_bluesky_runs=cache_of_partial_bluesky_runs,\n metadata=metadata,\n access_policy=access_policy,\n principal=principal,\n )\n\n def __init__(\n self,\n metadatastore_db,\n asset_registry_db,\n handler_registry,\n root_map,\n transforms,\n cache_of_complete_bluesky_runs,\n cache_of_partial_bluesky_runs,\n metadata=None,\n queries=None,\n sorting=None,\n access_policy=None,\n principal=None,\n ):\n \"This is not user-facing. Use MongoAdapter.from_uri.\"\n self._run_start_collection = metadatastore_db.get_collection(\"run_start\")\n self._run_stop_collection = metadatastore_db.get_collection(\"run_stop\")\n self._event_descriptor_collection = metadatastore_db.get_collection(\n \"event_descriptor\"\n )\n self._event_collection = metadatastore_db.get_collection(\"event\")\n self._resource_collection = asset_registry_db.get_collection(\"resource\")\n self._datum_collection = asset_registry_db.get_collection(\"datum\")\n self._metadatastore_db = metadatastore_db\n self._asset_registry_db = asset_registry_db\n\n self._handler_registry = handler_registry\n self.handler_registry = event_model.HandlerRegistryView(self._handler_registry)\n self.root_map = root_map\n self.transforms = transforms or {}\n self._cache_of_complete_bluesky_runs = cache_of_complete_bluesky_runs\n self._cache_of_partial_bluesky_runs = cache_of_partial_bluesky_runs\n self._cache_of_bluesky_runs = collections.ChainMap(\n cache_of_complete_bluesky_runs, cache_of_partial_bluesky_runs\n )\n self._metadata = metadata or {}\n self.queries = list(queries or [])\n if sorting is None:\n sorting = [(\"time\", 1)]\n self._sorting = sorting\n if isinstance(access_policy, str):\n access_policy = import_object(access_policy)\n if (access_policy is not None) and (\n not access_policy.check_compatibility(self)\n ):\n raise ValueError(\n f\"Access policy {access_policy} is not compatible with this MongoAdapter.\"\n )\n self._access_policy = access_policy\n self._principal = principal\n self._serializer = None\n super().__init__()\n\n @property\n def database(self):\n \"\"\"\n The underlying MongoDB database object\n\n Note: Very old deployments use two separate databases. We believe these\n are rare \"in the wild\", mostly or entirely restricted to the earliest\n facility to use databroker, BNL NSLS-II.\n\n In the event that two databases are used, this raises\n NotImplementedError and instructs the callers to use two semi-internal\n attributes instead.\n \"\"\"\n if self._metadatastore_db != self._asset_registry_db:\n raise NotImplementedError(\n \"This MongoAdapter is backed by two databases. This is no longer \"\n \"necessary or recommended. As a result, the `database` property \"\n \"is undefined. Use the attributes _metadatastore_db and \"\n \"_asset_registry_db directly.\"\n )\n return self._metadatastore_db\n\n def get_serializer(self):\n from suitcase.mongo_normalized import Serializer\n\n if self._serializer is None:\n self._serializer = Serializer(\n self._metadatastore_db, self._asset_registry_db\n )\n\n return self._serializer\n\n def register_handler(self, spec, handler, overwrite=False):\n if (not overwrite) and (spec in self._handler_registry):\n original = self._handler_registry[spec]\n if original is handler:\n return\n raise event_model.DuplicateHandler(\n f\"There is already a handler registered for the spec {spec!r}. \"\n f\"Use overwrite=True to deregister the original.\\n\"\n f\"Original: {original}\\n\"\n f\"New: {handler}\"\n )\n self._handler_registry[spec] = handler\n\n def deregister_handler(self, spec):\n self._handler_registry.pop(spec, None)\n\n def new_variation(\n self,\n *args,\n metadata=UNCHANGED,\n queries=UNCHANGED,\n sorting=UNCHANGED,\n principal=UNCHANGED,\n **kwargs,\n ):\n if metadata is UNCHANGED:\n metadata = self._metadata\n if queries is UNCHANGED:\n queries = self.queries\n if sorting is UNCHANGED:\n sorting = self._sorting\n if principal is UNCHANGED:\n principal = self._principal\n return type(self)(\n *args,\n metadatastore_db=self._metadatastore_db,\n asset_registry_db=self._asset_registry_db,\n handler_registry=self.handler_registry,\n root_map=self.root_map,\n transforms=self.transforms,\n cache_of_complete_bluesky_runs=self._cache_of_complete_bluesky_runs,\n cache_of_partial_bluesky_runs=self._cache_of_partial_bluesky_runs,\n queries=queries,\n sorting=sorting,\n access_policy=self.access_policy,\n principal=principal,\n **kwargs,\n )\n\n @property\n def access_policy(self):\n return self._access_policy\n\n @property\n def principal(self):\n return self._principal\n\n @property\n def metadata_stale_at(self):\n return datetime.utcnow() + timedelta(seconds=600)\n\n @property\n def entries_stale_at(self):\n return None\n\n @property\n def metadata(self):\n \"Metadata about this MongoAdapter.\"\n return self._metadata\n\n @property\n def sorting(self):\n return list(self._sorting)\n\n def __repr__(self):\n # Display up to the first N keys to avoid making a giant service\n # request. Use _keys_slicer because it is unauthenticated.\n N = 10\n return tree_repr(self, self._keys_slice(0, N, direction=1))\n\n def _get_run(self, run_start_doc):\n \"Get a BlueskyRun, either from a cache or by making one if needed.\"\n uid = run_start_doc[\"uid\"]\n try:\n return self._cache_of_bluesky_runs[uid]\n except KeyError:\n run = self._build_run(run_start_doc)\n # Choose a cache depending on whethter the run is complete (in\n # which case updates are rare) or incomplete/partial (in which case\n # more data is likely incoming soon).\n if run.metadata.get(\"stop\") is None:\n self._cache_of_partial_bluesky_runs[uid] = run\n else:\n self._cache_of_complete_bluesky_runs[uid] = run\n return run\n\n def _build_run(self, run_start_doc):\n \"This should not be called directly, even internally. Use _get_run.\"\n # Instantiate a BlueskyRun for this run_start_doc.\n uid = run_start_doc[\"uid\"]\n # This may be None; that's fine.\n run_stop_doc = self._get_stop_doc(uid)\n stream_names = self._event_descriptor_collection.distinct(\n \"name\",\n {\"run_start\": uid},\n )\n mapping = {}\n for stream_name in stream_names:\n mapping[stream_name] = functools.partial(\n self._build_event_stream,\n run_start_uid=uid,\n stream_name=stream_name,\n is_complete=(run_stop_doc is not None),\n )\n return BlueskyRun(\n OneShotCachedMap(mapping),\n metadata={\n \"start\": run_start_doc,\n \"stop\": run_stop_doc,\n \"summary\": build_summary(run_start_doc, run_stop_doc, stream_names),\n },\n handler_registry=self.handler_registry,\n transforms=copy.copy(self.transforms),\n root_map=copy.copy(self.root_map),\n datum_collection=self._datum_collection,\n resource_collection=self._resource_collection,\n )\n\n def _build_event_stream(self, *, run_start_uid, stream_name, is_complete):\n event_descriptors = list(\n self._event_descriptor_collection.find(\n {\"run_start\": run_start_uid, \"name\": stream_name}, {\"_id\": False}\n )\n )\n event_descriptor_uids = [doc[\"uid\"] for doc in event_descriptors]\n # We need each of the sub-dicts to have a consistent length. If\n # Events are still being added, we need to choose a consistent\n # cutoff. If not, we need to know the length anyway. Note that this\n # is not the same thing as the number of Event documents in the\n # stream because seq_num may be repeated, nonunique.\n cursor = self._event_collection.aggregate(\n [\n {\"$match\": {\"descriptor\": {\"$in\": event_descriptor_uids}}},\n {\n \"$group\": {\n \"_id\": \"descriptor\",\n \"highest_seq_num\": {\"$max\": \"$seq_num\"},\n },\n },\n ]\n )\n (result,) = cursor\n cutoff_seq_num = (\n 1 + result[\"highest_seq_num\"]\n ) # `1 +` because we use a half-open interval\n object_names = event_descriptors[0][\"object_keys\"]\n run = self[run_start_uid]\n mapping = OneShotCachedMap(\n {\n \"data\": lambda: DatasetFromDocuments(\n run=run,\n stream_name=stream_name,\n cutoff_seq_num=cutoff_seq_num,\n event_descriptors=event_descriptors,\n event_collection=self._event_collection,\n root_map=self.root_map,\n sub_dict=\"data\",\n ),\n \"timestamps\": lambda: DatasetFromDocuments(\n run=run,\n stream_name=stream_name,\n cutoff_seq_num=cutoff_seq_num,\n event_descriptors=event_descriptors,\n event_collection=self._event_collection,\n root_map=self.root_map,\n sub_dict=\"timestamps\",\n ),\n \"config\": lambda: Config(\n OneShotCachedMap(\n {\n object_name: lambda object_name=object_name: build_config_xarray(\n event_descriptors=event_descriptors,\n object_name=object_name,\n sub_dict=\"data\",\n )\n for object_name in object_names\n }\n )\n ),\n \"config_timestamps\": lambda: Config(\n OneShotCachedMap(\n {\n object_name: lambda object_name=object_name: build_config_xarray(\n event_descriptors=event_descriptors,\n object_name=object_name,\n sub_dict=\"timestamps\",\n )\n for object_name in object_names\n }\n )\n ),\n }\n )\n\n metadata = {\"descriptors\": event_descriptors, \"stream_name\": stream_name}\n return BlueskyEventStream(\n mapping,\n metadata=metadata,\n event_collection=self._event_collection,\n cutoff_seq_num=cutoff_seq_num,\n run=run,\n )\n\n def __getitem__(self, key):\n # Lookup this key *within the search results* of this MongoAdapter.\n query = self._build_mongo_query({\"uid\": key})\n run_start_doc = self._run_start_collection.find_one(query, {\"_id\": False})\n if run_start_doc is None:\n raise KeyError(key)\n return self._get_run(run_start_doc)\n\n def _chunked_find(self, collection, query, *args, skip=0, limit=None, **kwargs):\n # This is an internal chunking that affects how much we pull from\n # MongoDB at a time.\n CURSOR_LIMIT = 100 # TODO Tune this for performance.\n if limit is not None and limit < CURSOR_LIMIT:\n initial_limit = limit\n else:\n initial_limit = CURSOR_LIMIT\n cursor = (\n collection.find(query, *args, **kwargs)\n .sort(self._sorting + [(\"_id\", 1)])\n .skip(skip)\n .limit(initial_limit)\n )\n # Fetch in batches, starting each batch from where we left off.\n # https://medium.com/swlh/mongodb-pagination-fast-consistent-ece2a97070f3\n tally = 0\n items = []\n last_sorted_values = {}\n while True:\n # Greedily exhaust the cursor. The user may loop over this iterator\n # slowly and, if we don't pull it all into memory now, we'll be\n # holding a long-lived cursor that might get timed out by the\n # MongoDB server.\n items.extend(cursor) # Exhaust cursor.\n if not items:\n break\n # Next time through the loop, we'll pick up where we left off.\n last_object_id = items[-1][\"_id\"]\n last_item = items[-1]\n for name, _ in self._sorting:\n # This supports sorting by sub-items like, for example,\n # \"XDI.Element.edge\".\n first_token, *tokens = name.split(\".\")\n value = last_item[first_token]\n for token in tokens:\n value = value[token]\n last_sorted_values[name] = value\n page_cutoff_query = [\n {\n \"$or\": [\n {\n name: {\n (\n \"$gt\" if direction > 0 else \"$lt\"\n ): last_sorted_values[name]\n }\n },\n {\n name: last_sorted_values[name],\n \"_id\": {\"$gt\": last_object_id},\n },\n ]\n }\n for name, direction in self._sorting\n ]\n if \"$and\" in query:\n query[\"$and\"].extend(page_cutoff_query)\n else:\n query[\"$and\"] = page_cutoff_query\n for item in items:\n item.pop(\"_id\")\n yield item\n tally += len(items)\n if limit is not None:\n if tally == limit:\n break\n if limit - tally < CURSOR_LIMIT:\n this_limit = limit - tally\n else:\n this_limit = CURSOR_LIMIT\n else:\n this_limit = CURSOR_LIMIT\n # Get another batch and go round again.\n cursor = (\n collection.find(query, *args, **kwargs)\n .sort(self._sorting + [(\"_id\", 1)])\n .limit(this_limit)\n )\n items.clear()\n\n def _build_mongo_query(self, *queries):\n combined = self.queries + list(queries)\n if combined:\n return {\"$and\": combined}\n else:\n return {}\n\n def _get_stop_doc(self, run_start_uid):\n \"This may return None.\"\n return self._run_stop_collection.find_one(\n {\"run_start\": run_start_uid}, {\"_id\": False}\n )\n\n def __iter__(self):\n for run_start_doc in self._chunked_find(\n self._run_start_collection, self._build_mongo_query()\n ):\n yield run_start_doc[\"uid\"]\n\n def __len__(self):\n return self._run_start_collection.count_documents(self._build_mongo_query())\n\n def __length_hint__(self):\n # https://www.python.org/dev/peps/pep-0424/\n return self._run_start_collection.estimated_document_count(\n self._build_mongo_query(),\n )\n\n def authenticated_as(self, identity):\n if self._principal is not None:\n raise RuntimeError(\n f\"Already authenticated as {self.principal}\"\n )\n if self._access_policy is not None:\n queries = self._access_policy.modify_queries(\n self.queries,\n identity,\n )\n tree = self.new_variation(principal=identity, queries=queries)\n else:\n tree = self.new_variation(principal=identity)\n return tree\n\n def search(self, query):\n \"\"\"\n Return a MongoAdapter with a subset of the mapping.\n \"\"\"\n return self.query_registry(query, self)\n\n def sort(self, sorting):\n return self.new_variation(sorting=sorting)\n\n def _keys_slice(self, start, stop, direction):\n assert direction == 1, \"direction=-1 should be handled by the client\"\n skip = start or 0\n if stop is not None:\n limit = stop - skip\n else:\n limit = None\n for run_start_doc in self._chunked_find(\n self._run_start_collection,\n self._build_mongo_query(),\n skip=skip,\n limit=limit,\n ):\n # TODO Fetch just the uid.\n yield run_start_doc[\"uid\"]\n\n def _items_slice(self, start, stop, direction):\n assert direction == 1, \"direction=-1 should be handled by the client\"\n skip = start or 0\n if stop is not None:\n limit = stop - skip\n else:\n limit = None\n for run_start_doc in self._chunked_find(\n self._run_start_collection,\n self._build_mongo_query(),\n skip=skip,\n limit=limit,\n ):\n uid = run_start_doc[\"uid\"]\n run = self._get_run(run_start_doc)\n yield (uid, run)\n\n def _item_by_index(self, index, direction):\n assert direction == 1, \"direction=-1 should be handled by the client\"\n run_start_doc = next(\n self._chunked_find(\n self._run_start_collection,\n self._build_mongo_query(),\n skip=index,\n limit=1,\n )\n )\n uid = run_start_doc[\"uid\"]\n run = self._get_run(run_start_doc)\n return (uid, run)\n\n\ndef full_text_search(query, catalog):\n # First if this catalog is backed by mongomock, which does not support $text queries.\n # Avoid importing mongomock if it is not already imported.\n if \"mongomock\" in sys.modules:\n import mongomock\n\n if isinstance(catalog.database.client, mongomock.MongoClient):\n # Do the query in memory.\n # For huge MongoAdapters this will be slow, but if you are attempting\n # full text search on a large mongomock-backed MongoAdapter,\n # you have made your choices! :-)\n return BlueskyMapAdapter(dict(catalog)).search(query)\n\n return MongoAdapter.query_registry(\n RawMongo(\n start={\n \"$text\": {\"$search\": query.text, \"$caseSensitive\": query.case_sensitive}\n }\n ),\n catalog,\n )\n\n\ndef raw_mongo(query, catalog):\n # For now, only handle search on the 'run_start' collection.\n return catalog.new_variation(\n queries=catalog.queries + [json.loads(query.start)],\n )\n\n\n# These are implementation-specific definitions.\nMongoAdapter.register_query(FullText, full_text_search)\nMongoAdapter.register_query(RawMongo, raw_mongo)\n# These are generic definitions that use RawMongo internally.\nMongoAdapter.register_query(_PartialUID, partial_uid)\nMongoAdapter.register_query(_ScanID, scan_id)\nMongoAdapter.register_query(TimeRange, time_range)\n\n\nclass SimpleAccessPolicy:\n \"\"\"\n Refer to a mapping of user names to lists of entries they can access.\n\n By Run Start UID\n >>> SimpleAccessPolicy({\"alice\": [<uuid>, <uuid>], \"bob\": [<uuid>]}, key=\"uid\")\n\n By Data Session\n >>> SimpleAccessPolicy({\"alice\": [<data_session>, key=\"data_session\")\n \"\"\"\n\n ALL = object() # sentinel\n\n def __init__(self, access_lists, key, provider):\n self.access_lists = {}\n self.key = key\n self.provider = provider\n for identity, entries in (access_lists or {}).items():\n if isinstance(entries, str):\n entries = import_object(entries)\n self.access_lists[identity] = entries\n\n def check_compatibility(self, catalog):\n return isinstance(catalog, MongoAdapter)\n\n def modify_queries(self, queries, principal):\n # Get the id (i.e. username) of this Principal for the\n # associated authentication provider.\n for identity in principal.identities:\n if identity.provider == self.provider:\n id = identity.id\n break\n else:\n raise ValueError(\n f\"Principcal {principal} has no identity from provider {self.provider}. \"\n f\"Its identities are: {principal.identities}\"\n )\n allowed = self.access_lists.get(id, [])\n if (id is SpecialUsers.admin) or (allowed is self.ALL):\n modified_queries = queries\n else:\n modified_queries = list(queries)\n modified_queries.append({self.key: {\"$in\": allowed}})\n return modified_queries\n\n\ndef _get_database(uri):\n if not pymongo.uri_parser.parse_uri(uri)[\"database\"]:\n raise ValueError(\n f\"Invalid URI: {uri!r} \" f\"Did you forget to include a database?\"\n )\n else:\n client = pymongo.MongoClient(uri)\n return client.get_database()\n\n\ndef discover_handlers(entrypoint_group_name=\"databroker.handlers\", skip_failures=True):\n \"\"\"\n Discover handlers via entrypoints.\n\n Parameters\n ----------\n entrypoint_group_name: str\n Default is 'databroker.handlers', the \"official\" databroker entrypoint\n for handlers.\n skip_failures: boolean\n True by default. Errors loading a handler class are converted to\n warnings if this is True.\n\n Returns\n -------\n handler_registry: dict\n A suitable default handler registry\n \"\"\"\n group = entrypoints.get_group_named(entrypoint_group_name)\n group_all = entrypoints.get_group_all(entrypoint_group_name)\n if len(group_all) != len(group):\n # There are some name collisions. Let's go digging for them.\n for name, matches in itertools.groupby(group_all, lambda ep: ep.name):\n matches = list(matches)\n if len(matches) != 1:\n winner = group[name]\n logger.warning(\n f\"There are {len(matches)} entrypoints for the \"\n f\"databroker handler spec {name!r}. \"\n f\"They are {matches}. The match {winner} has won the race.\"\n )\n handler_registry = {}\n for name, entrypoint in group.items():\n try:\n handler_class = entrypoint.load()\n except Exception as exc:\n if skip_failures:\n logger.warning(\n f\"Skipping {entrypoint!r} which failed to load. \"\n f\"Exception: {exc!r}\"\n )\n continue\n else:\n raise\n handler_registry[name] = handler_class\n\n return handler_registry\n\n\ndef parse_handler_registry(handler_registry):\n \"\"\"\n Parse mapping of spec name to 'import path' into mapping to class itself.\n\n Parameters\n ----------\n handler_registry : dict\n Values may be string 'import paths' to classes or actual classes.\n\n Examples\n --------\n Pass in name; get back actual class.\n\n >>> parse_handler_registry({'my_spec': 'package.module.ClassName'})\n {'my_spec': <package.module.ClassName>}\n\n \"\"\"\n return _parse_dict_of_objs_or_importable_strings(handler_registry)\n\n\ndef _parse_dict_of_objs_or_importable_strings(d):\n result = {}\n for key, value in d.items():\n if isinstance(value, str):\n try:\n class_ = import_object(value)\n except Exception:\n # For back-compat, trying transforming 'a.b.c' into 'a.b:c'.\n edited_value = \":\".join(value.rsplit(\".\", 1))\n class_ = import_object(edited_value)\n # TODO Warn.\n else:\n class_ = value\n result[key] = class_\n return result\n\n\ndef parse_transforms(transforms):\n \"\"\"\n Parse mapping of spec name to 'import path' into mapping to class itself.\n\n Parameters\n ----------\n transforms : collections.abc.Mapping or None\n A collections.abc.Mapping or subclass, that maps any subset of the\n keys {start, stop, resource, descriptor} to a function (or a string\n import path) that accepts a document of the corresponding type and\n returns it, potentially modified. This feature is for patching up\n erroneous metadata. It is intended for quick, temporary fixes that\n may later be applied permanently to the data at rest (e.g via a\n database migration).\n\n Examples\n --------\n Pass in name; get back actual class.\n\n >>> parse_transforms({'descriptor': 'package.module.function_name'})\n {'descriptor': <package.module.function_name>}\n\n \"\"\"\n if transforms is None:\n return\n elif isinstance(transforms, collections.abc.Mapping):\n allowed_keys = {\"start\", \"stop\", \"resource\", \"descriptor\"}\n if transforms.keys() - allowed_keys:\n raise NotImplementedError(\n f\"Transforms for {transforms.keys() - allowed_keys} \"\n f\"are not supported.\"\n )\n else:\n raise ValueError(\n f\"Invalid transforms argument {transforms}. \"\n f\"transforms must be None or a dictionary.\"\n )\n return _parse_dict_of_objs_or_importable_strings(transforms)\n\n\n# These are fallback guesses when all we have is a general jsonschema \"dtype\"\n# like \"array\" no specific \"dtype_str\" like \"<u2\".\nBOOLEAN_DTYPE = BuiltinDtype.from_numpy_dtype(numpy.dtype(\"bool\"))\nFLOAT_DTYPE = BuiltinDtype.from_numpy_dtype(numpy.dtype(\"float64\"))\nINT_DTYPE = BuiltinDtype.from_numpy_dtype(numpy.dtype(\"int64\"))\nSTRING_DTYPE = BuiltinDtype.from_numpy_dtype(numpy.dtype(\"<U\"))\nJSON_DTYPE_TO_MACHINE_DATA_TYPE = {\n \"boolean\": BOOLEAN_DTYPE,\n \"number\": FLOAT_DTYPE,\n \"integer\": INT_DTYPE,\n \"string\": STRING_DTYPE,\n \"array\": FLOAT_DTYPE, # If this is wrong, set 'dtype_str' in data_key to override.\n}\n\n\ndef _fill(\n filler,\n event,\n lookup_resource_for_datum,\n get_resource,\n get_datum_for_resource,\n last_datum_id=None,\n):\n try:\n _, filled_event = filler(\"event\", event)\n return filled_event\n except event_model.UnresolvableForeignKeyError as err:\n datum_id = err.key\n if datum_id == last_datum_id:\n # We tried to fetch this Datum on the last trip\n # trip through this method, and apparently it did not\n # work. We are in an infinite loop. Bail!\n raise\n\n # try to fast-path looking up the resource uid if this works\n # it saves us a a database hit (to get the datum document)\n if \"/\" in datum_id:\n resource_uid, _ = datum_id.split(\"/\", 1)\n # otherwise do it the standard way\n else:\n resource_uid = lookup_resource_for_datum(datum_id)\n\n # but, it might be the case that the key just happens to have\n # a '/' in it and it does not have any semantic meaning so we\n # optimistically try\n try:\n resource = get_resource(uid=resource_uid)\n # and then fall back to the standard way to be safe\n except ValueError:\n resource = get_resource(lookup_resource_for_datum(datum_id))\n\n filler(\"resource\", resource)\n # Pre-fetch all datum for this resource.\n for datum in get_datum_for_resource(resource_uid=resource_uid):\n filler(\"datum\", datum)\n # TODO -- When to clear the datum cache in filler?\n\n # Re-enter and try again now that the Filler has consumed the\n # missing Datum. There might be another missing Datum in this same\n # Event document (hence this re-entrant structure) or might be good\n # to go.\n return _fill(\n filler,\n event,\n lookup_resource_for_datum,\n get_resource,\n get_datum_for_resource,\n last_datum_id=datum_id,\n )\n\n\ndef batch_documents(singles, size):\n # Acculuate rows for Event Pages or Datum Pages in a cache.\n # Drain the cache and emit the page when any of the following conditions\n # are met:\n # (1) We reach a document of a different type.\n # (2) The associated Event Descriptor or Resource changes.\n # (3) The number of rows in the cache reaches `size`.\n cache = collections.deque()\n current_uid = None\n current_type = None\n\n def handle_item(name, doc):\n nonlocal current_uid\n nonlocal current_type\n if name == \"event\":\n if (\n (current_type == \"event_page\")\n and (current_uid == doc[\"descriptor\"])\n and len(cache) < size\n ):\n cache.append(doc)\n elif current_type is None:\n current_type = \"event_page\"\n current_uid = doc[\"descriptor\"]\n cache.append(doc)\n else:\n # Emit the cache and recurse.\n if current_type == \"event_page\":\n yield (current_type, event_model.pack_event_page(*cache))\n if current_type == \"datum_page\":\n yield (current_type, event_model.pack_datum_page(*cache))\n cache.clear()\n current_uid = None\n current_type = None\n yield from handle_item(name, doc)\n elif name == \"datum\":\n if (\n (current_type == \"datum_page\")\n and (current_uid == doc[\"resource\"])\n and len(cache) < size\n ):\n cache.append(doc)\n elif current_type is None:\n current_type = \"datum_page\"\n current_uid = doc[\"resource\"]\n cache.append(doc)\n else:\n # Emit the cache and recurse\n if current_type == \"event_page\":\n yield (current_type, event_model.pack_event_page(*cache))\n if current_type == \"datum_page\":\n yield (current_type, event_model.pack_datum_page(*cache))\n cache.clear()\n current_uid = None\n current_type = None\n yield from handle_item(name, doc)\n else:\n # Emit the cached page (if nonempty) and then this item.\n if cache:\n if current_type == \"event_page\":\n yield (current_type, event_model.pack_event_page(*cache))\n elif current_type == \"datum_page\":\n yield (current_type, event_model.pack_datum_page(*cache))\n else:\n assert False\n cache.clear()\n current_uid = None\n current_type = None\n yield (name, doc)\n\n for name, doc in singles:\n yield from handle_item(name, doc)\n\n\nclass BadShapeMetadata(Exception):\n pass\n\n\ndef _validate_shape(key, data, expected_shape):\n \"\"\"\n Check that data.shape == expected.shape.\n\n * If number of dimensions differ, raise BadShapeMetadata\n * If any dimension is larger than expected, raise BadShapeMetadata.\n * If some dimensions are smaller than expected,, pad \"right\" edge of each\n dimension that falls short with NaN.\n \"\"\"\n if data.shape == expected_shape:\n return data\n if len(data.shape) != len(expected_shape):\n # The number of dimensions are different; padding can't fix this.\n raise BadShapeMetadata(\n f\"For data key {key} \"\n f\"shape {data.shape} does not \"\n f\"match expected shape {expected_shape}.\"\n )\n # Pad at the \"end\" along any dimension that is too short.\n padding = []\n trimming = []\n for actual, expected in zip(data.shape, expected_shape):\n margin = expected - actual\n # Limit how much padding or trimming we are willing to do.\n SOMEWHAT_ARBITRARY_LIMIT_OF_WHAT_IS_REASONABLE = 2\n if abs(margin) > SOMEWHAT_ARBITRARY_LIMIT_OF_WHAT_IS_REASONABLE:\n raise BadShapeMetadata(\n f\"For data key {key} \"\n f\"shape {data.shape} does not \"\n f\"match expected shape {expected_shape}.\"\n )\n if margin > 0:\n padding.append((0, margin))\n trimming.append(slice(None, None))\n elif margin < 0:\n padding.append((0, 0))\n trimming.append(slice(None))\n else: # margin == 0\n padding.append((0, 0))\n trimming.append(slice(None, None))\n # TODO Rethink this!\n # We cannot do NaN because that does not work for integers\n # and it is too late to change our mind about the data type.\n padded = numpy.pad(data, padding, \"edge\")\n padded_and_trimmed = padded[tuple(trimming)]\n return padded_and_trimmed\n\n\ndef build_summary(run_start_doc, run_stop_doc, stream_names):\n summary = {\n \"uid\": run_start_doc[\"uid\"],\n \"scan_id\": run_start_doc.get(\"scan_id\"),\n \"timestamp\": run_start_doc[\"time\"],\n \"datetime\": datetime.fromtimestamp(run_start_doc[\"time\"]),\n \"plan_name\": run_start_doc.get(\"plan_name\"),\n \"stream_names\": stream_names,\n }\n if run_stop_doc is None:\n summary[\"duration\"] = None\n else:\n summary[\"duration\"] = run_stop_doc[\"time\"] - run_start_doc[\"time\"]\n return summary\n\n\n# for back-compat with old config file\nTree = MongoAdapter\n"
] |
[
[
"numpy.product",
"numpy.pad",
"numpy.asarray",
"numpy.stack",
"numpy.dtype",
"numpy.array"
]
] |
BayesianSCA/k-trace-CCA
|
[
"8dbf10ff28712848dcb8874e370c3fe40a0566a0"
] |
[
"python/full_attack.py"
] |
[
"#!/usr/bin/env python3\nimport sys\nimport os\nimport math\nimport random\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport itertools\nimport traceback\nfrom multiprocessing import cpu_count\n\nsys.path.append('lib/')\n\nfrom helpers.experiment import Experiment\nfrom helpers.params import get_argument_parser, get_params, print_params\nfrom helpers.intt_builder import build_masked_graphs, build_unmasked_graph\nfrom simulation.gen_input import INTTInputMasked, INTTInputUnmasked, BHatInfo, gen_skpv\nfrom simulation.leak_data import LeakDataMasked, LeakDataUnmasked\nfrom test import create_experiment_masked, create_experiment_unmasked\nfrom simulation.kyber.reference.params import KYBER_N\nfrom simulation.kyber.reference.reduce import barrett_reduce\nfrom simulation.kyber.reference.poly import poly\nfrom simulation.recover_sk_sparse import RecoverSk\n\n\ndef main():\n params = {\n 'seed': 42,\n 'runs': 1,\n 'sigmas': [\n 0.2,\n ],\n 'attack_strategies': [1, 2],\n 'unmasked': True,\n 'total_steps': 100,\n 'height': KYBER_N,\n 'layers': 7,\n 'kyber_k': 3,\n 'abort_entropy': 0.1,\n 'abort_entropy_diff': 0.5,\n 'thread_count': cpu_count() - 1,\n 'step_size': 10,\n 'do_not_draw': False,\n 'draw_labels': True,\n 'no_bp': True,\n 'result_file': 'res_full_attack',\n }\n\n results = {}\n for attack_strategy in params['attack_strategies']:\n attack_strategy = AttackStrategy.generate(attack_strategy)\n results[attack_strategy] = {}\n for sigma in params['sigmas']:\n results[attack_strategy][sigma] = {}\n results[attack_strategy][sigma]['nbr_success'] = 0\n print(\"Sigma: \", sigma)\n print(\"==============\")\n # Terrible..\n params['sigma'] = sigma\n for i_run in range(params['runs']):\n results[attack_strategy][sigma][i_run] = {}\n seed = (\n params['seed'] + i_run\n ) # This should be statistically independent with a decent PRNG\n results[attack_strategy][sigma][i_run]['seed'] = seed\n random.seed(seed)\n rng = np.random.default_rng(seed)\n\n try:\n skpv_orig, skpv = gen_skpv(rng, params['height'], params['kyber_k'])\n print(\"skpv (in reg domain): \", skpv_orig)\n print(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\")\n rec_sk = RecoverSk(height=params['height'], vec_k=params['kyber_k'])\n for i_trace in range(attack_strategy.nbr_traces):\n bhat_info = attack_strategy.bhat_info(i_trace)\n bhat, len_zero_indices = bhat_info.generate_bhat(\n rng, params['height'], params['kyber_k']\n )\n print(\"Bhat: \", bhat)\n print(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\")\n print(\n \"Experiment {} with seed {} and {} zeros:\".format(\n i_run, seed, len_zero_indices\n )\n )\n if params['no_bp']:\n if params['unmasked']:\n inttinput = INTTInputUnmasked.generate(\n rng, params['height'], 3, skpv, bhat\n )\n c_hat = inttinput.get_intt_input()\n else:\n inttinput = INTTInputMasked.generate(\n rng, params['height'], 3, skpv, bhat\n )\n maskshare, skm = inttinput.get_intt_inputs()\n c_hat = barrett_reduce(maskshare + skm)\n else:\n if params['unmasked']:\n r = create_experiment_unmasked(params, rng, skpv, bhat)\n else:\n r = create_experiment_masked(params, rng, skpv, bhat)\n r.run(params['total_steps'])\n _, stats, _ = r.print_results(not params['unmasked'])\n print(\"\")\n assert stats[\n 'success'\n ], \"Key part not successfully recovered\"\n c_hat = poly()\n if params['unmasked']:\n c_hat.coeffs = r.key\n else:\n key_len = len(r.key) // 2\n maskshare = r.key[:key_len]\n skm = r.key[key_len:]\n c_hat.coeffs = list(\n map(\n lambda a, b: barrett_reduce(a + b),\n maskshare,\n skm,\n )\n )\n\n rec_sk.recover_sk_hat(bhat, c_hat)\n print(\">\" * 80)\n assert rec_sk.is_complete, \"Key not completely recovered\"\n # print(\"skpv (in reg domain): \", skpv_orig)\n # print(\"rec_sk (in reg domain): \", rec_sk.sk)\n assert (\n skpv_orig == rec_sk.sk\n ).all(), \"Key not successfully recovered (in ntt domain)\"\n assert (\n skpv == rec_sk.sk_hat_mont\n ).all(), \"Key not successfully recovered (in reg domain)\"\n except:\n print(\"ERROR in run {} with sigma {}\".format(i_run, sigma))\n traceback.print_exc()\n print(\"This is run will be counted as unsuccessful attack.\")\n results[attack_strategy][sigma][i_run]['success'] = False\n else:\n results[attack_strategy][sigma][i_run]['success'] = True\n results[attack_strategy][sigma]['nbr_success'] += 1\n print(\">\" * 80)\n print(\"Params :\\n\", params)\n print(\">\" * 80)\n print(\"Final Results :\\n\", results)\n\n np.savez_compressed(\n \"{}\".format(params['result_file']), results=results, params=params\n )\n\n\nclass AttackStrategy:\n def __init__(self, attack_strategy):\n self.attack_strategy = attack_strategy\n\n @staticmethod\n def generate(attack_strategy):\n return AttackStrategy(attack_strategy)\n\n def __hash__(self):\n return hash(self.attack_strategy)\n\n def __eq__(self, other):\n return (\n hasattr(other, 'attack_strategy')\n and self.attack_strategy == other.attack_strategy\n )\n\n def __repr__(self):\n return str(self.attack_strategy)\n\n @property\n def nbr_traces(self):\n if self.attack_strategy == 1:\n return 6\n elif self.attack_strategy == 2:\n return 12\n else:\n raise NotImplementedError(\"Attack strategy not implemented.\")\n\n def bhat_info(self, i_trace):\n if self.attack_strategy == 1:\n blocks = [0, 1] if not i_trace & 1 else [2, 3]\n set_bhat = i_trace >> 1\n return BHatInfo.from_generated_bhat(blocks, set_bhat)\n elif self.attack_strategy == 2:\n blocks = [i_trace & 0b11]\n set_bhat = i_trace >> 2\n return BHatInfo.from_generated_bhat(blocks, set_bhat)\n else:\n raise NotImplementedError(\"Attack strategy not implemented.\")\n\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"numpy.random.default_rng"
]
] |
pmla/hyperspherical-coverings
|
[
"5c9130c5dd0043d0a658712c5256c8588a384f02"
] |
[
"regular_simplex.py"
] |
[
"import numpy as np\nimport scipy.special\n\n\ndef ei(t):\n return np.exp(1j * t)\n\n\ndef verify_solution(t, z0):\n\n sol = (ei(3*t) + z0)**4 / ((1 - z0) * (ei(4*t) - z0)**3)\n\n if abs(np.real(sol) - 1.0) > 1E-3:\n raise Exception(\"real part not 1\")\n if abs(np.imag(sol)) > 1E-3:\n raise Exception(\"imaginary part not 0\")\n\n\ndef Li2(x):\n return scipy.special.spence(1 - x)\n\n\ndef calculate_volume(l):\n\n t = np.arccos(np.cos(l) / (2*np.cos(l) + 1))\n sint = np.sin(t)\n cost = np.cos(t)\n\n q2 = 3*ei(-2*t) + 4*ei(-3*t) + ei(-6*t)\n z0 = (-6*sint**2 + 2 * np.sqrt((cost+1)**3 * (1 - 3*cost))) / q2\n\n verify_solution(t, z0)\n\n L = 0.5 * (Li2(z0) + 3*Li2(z0 * ei(-4*t)) - 4*Li2(-z0 * ei(-3*t)) - 3*t**2)\n vol = -np.real(L) + np.pi * (np.angle(-q2) + 3 * t) - 1.5*np.pi**2\n vol = vol % (2 * np.pi**2)\n return vol\n\n"
] |
[
[
"numpy.imag",
"numpy.sqrt",
"numpy.cos",
"numpy.sin",
"numpy.real",
"numpy.angle",
"numpy.exp"
]
] |
jayanthchandra/nilearn
|
[
"d8b6f3121f4663914c65c10ae8d2c2bc513a89ba"
] |
[
"examples/plot_decoding_tutorial.py"
] |
[
"\"\"\"\nA introduction tutorial to fMRI decoding\n==========================================\n\nHere is a simple tutorial on decoding with nilearn. It reproduces the\nHaxby 2001 study on a face vs cat discrimination task in a mask of the\nventral stream.\n\nThis tutorial is meant as an introduction to the various steps of a\ndecoding analysis.\n\nIt is not a minimalistic example, as it strives to be didactic. It is not\nmeant to be copied to analyze new data: many of the steps are unnecessary.\n\n.. contents:: **Contents**\n :local:\n :depth: 1\n\n\n\"\"\"\n\n###########################################################################\n# Retrieve and load the fMRI data from the Haxby study\n# ------------------------------------------------------\n#\n# First download the data\n# ........................\n#\n# The :func:`nilearn.datasets.fetch_haxby` function will download the\n# Haxby dataset if not present on the disk, in the nilearn data directory.\n# It can take a while to download about 310 Mo of data from the Internet.\nfrom nilearn import datasets\n# By default 2nd subject will be fetched\nhaxby_dataset = datasets.fetch_haxby()\n# 'func' is a list of filenames: one for each subject\nfmri_filename = haxby_dataset.func[0]\n\n# print basic information on the dataset\nprint('First subject functional nifti images (4D) are at: %s' %\n fmri_filename) # 4D data\n\n###########################################################################\n# Visualizing the fmri volume\n# ............................\n#\n# One way to visualize a fmri volume is\n# using :func:`nilearn.plotting.plot_epi`.\n# We will visualize the previously fetched fmri data from Haxby dataset.\n#\n# Because fmri data is 4D (it consists of many 3D EPI images), we cannot \n# plot it directly using :func:`nilearn.plotting.plot_epi` (which accepts \n# just 3D input). Here we are using :func:`nilearn.image.mean_img` to \n# extract a single 3D EPI image from the fmri data.\n#\nfrom nilearn import plotting\nfrom nilearn.image import mean_img\nplotting.view_img(mean_img(fmri_filename), threshold=None)\n\n###########################################################################\n# Feature extraction: from fMRI volumes to a data matrix\n# .......................................................\n#\n# These are some really lovely images, but for machine learning\n# we need matrices to work with the actual data. Fortunately, the\n# :class:`nilearn.decoding.Decoder` object we will use later on can\n# automatically transform Nifti images into matrices.\n# All we have to do for now is define a mask filename.\n#\n# A mask of the Ventral Temporal (VT) cortex coming from the\n# Haxby study is available:\nmask_filename = haxby_dataset.mask_vt[0]\n\n# Let's visualize it, using the subject's anatomical image as a\n# background\nplotting.plot_roi(mask_filename, bg_img=haxby_dataset.anat[0],\n cmap='Paired')\n\n###########################################################################\n# Load the behavioral labels\n# ...........................\n#\n# Now that the brain images are converted to a data matrix, we can apply \n# machine-learning to them, for instance to predict the task that the subject \n# was doing. The behavioral labels are stored in a CSV file, separated by\n# spaces.\n#\n# We use pandas to load them in an array.\nimport pandas as pd\n# Load behavioral information\nbehavioral = pd.read_csv(haxby_dataset.session_target[0], delimiter=' ')\nprint(behavioral)\n\n###########################################################################\n# The task was a visual-recognition task, and the labels denote the \n# experimental condition: the type of object that was presented to the \n# subject. This is what we are going to try to predict.\nconditions = behavioral['labels']\nprint(conditions)\n\n###########################################################################\n# Restrict the analysis to cats and faces\n# ........................................\n#\n# As we can see from the targets above, the experiment contains many\n# conditions. As a consequence, the data is quite big. Not all of this data\n# has an interest to us for decoding, so we will keep only fmri signals\n# corresponding to faces or cats. We create a mask of the samples belonging to\n# the condition; this mask is then applied to the fmri data to restrict the\n# classification to the face vs cat discrimination.\n#\n# The input data will become much smaller (i.e. fmri signal is shorter):\ncondition_mask = conditions.isin(['face', 'cat'])\n\n###########################################################################\n# Because the data is in one single large 4D image, we need to use\n# index_img to do the split easily.\nfrom nilearn.image import index_img\nfmri_niimgs = index_img(fmri_filename, condition_mask)\n\n###########################################################################\n# We apply the same mask to the targets\nconditions = conditions[condition_mask]\n# Convert to numpy array\nconditions = conditions.values\nprint(conditions.shape)\n\n###########################################################################\n# Decoding with Support Vector Machine\n# ------------------------------------\n#\n# As a decoder, we use a Support Vector Classification, with a linear kernel.\n# We first create it using by using :class:`nilearn.decoding.Decoder`.\nfrom nilearn.decoding import Decoder\ndecoder = Decoder(estimator='svc', mask=mask_filename, standardize=True)\n\n###########################################################################\n# The svc object is an object that can be fit (or trained) on data with\n# labels, and then predict labels on data without.\n#\n# We first fit it on the data\ndecoder.fit(fmri_niimgs, conditions)\n\n###########################################################################\n# We can then predict the labels from the data\nprediction = decoder.predict(fmri_niimgs)\nprint(prediction)\n\n###########################################################################\n# Let's measure the prediction accuracy:\nprint((prediction == conditions).sum() / float(len(conditions)))\n\n###########################################################################\n# This prediction accuracy score is meaningless. Why?\n\n###########################################################################\n# Measuring prediction scores using cross-validation\n# ---------------------------------------------------\n#\n# The proper way to measure error rates or prediction accuracy is via\n# cross-validation: leaving out some data and testing on it.\n#\n# Manually leaving out data\n# ..........................\n#\n# Let's leave out the 30 last data points during training, and test the\n# prediction on these 30 last points:\nfmri_niimgs_train = index_img(fmri_niimgs, slice(0, -30))\nfmri_niimgs_test = index_img(fmri_niimgs, slice(-30, None))\nconditions_train = conditions[:-30]\nconditions_test = conditions[-30:]\n\ndecoder = Decoder(estimator='svc', mask=mask_filename, standardize=True)\ndecoder.fit(fmri_niimgs_train, conditions_train)\n\nprediction = decoder.predict(fmri_niimgs_test)\n\n# The prediction accuracy is calculated on the test data: this is the accuracy\n# of our model on examples it hasn't seen to examine how well the model perform\n# in general.\n\nprint(\"Prediction Accuracy: {:.3f}\".format(\n (prediction == conditions_test).sum() / float(len(conditions_test))))\n\n###########################################################################\n# Implementing a KFold loop\n# ..........................\n#\n# We can split the data in train and test set repetitively in a `KFold`\n# strategy:\nfrom sklearn.model_selection import KFold\ncv = KFold(n_splits=5)\n\n# The \"cv\" object's split method can now accept data and create a\n# generator which can yield the splits.\nfold = 0\nfor train, test in cv.split(conditions):\n fold += 1\n decoder = Decoder(estimator='svc', mask=mask_filename, standardize=True)\n decoder.fit(index_img(fmri_niimgs, train), conditions[train])\n prediction = decoder.predict(index_img(fmri_niimgs, test))\n print(\n \"CV Fold {:01d} | Prediction Accuracy: {:.3f}\".format(\n fold,\n (prediction == conditions[test]).sum() / float(len(\n conditions[test]))))\n\n###########################################################################\n# Cross-validation with the decoder\n# ...................................\n#\n# The decoder implements a cross-validation loop by default, it also returns\n# an array of shape (cross-validation parameters, n_folds)..\ndecoder = Decoder(estimator='svc', mask=mask_filename, standardize=True,\n cv=cv)\ndecoder.fit(fmri_niimgs, conditions)\n\nprint(decoder.cv_scores_['face'])\nprint(decoder.cv_scores_['cat'])\n\n# The decoder also gives the best performing parameters per fold.\nprint(decoder.cv_params_['face'])\n\n###########################################################################\n# .. note::\n# \tWe can speed things up to use all the CPUs of our computer with the\n# \tn_jobs parameter.\n# \n# The best way to do cross-validation is to respect the structure of\n# the experiment, for instance by leaving out full sessions of\n# acquisition.\n#\n# The number of the session is stored in the CSV file giving the\n# behavioral data. We have to apply our session mask, to select only cats\n# and faces.\nsession_label = behavioral['chunks'][condition_mask]\n\n###########################################################################\n# The fMRI data is acquired by sessions, and the noise is autocorrelated in a\n# given session. Hence, it is better to predict across sessions when doing\n# cross-validation. To leave a session out, pass the cross-validator object\n# to the cv parameter of decoder.\nfrom sklearn.model_selection import LeaveOneGroupOut\ncv = LeaveOneGroupOut()\n\ndecoder = Decoder(estimator='svc', mask=mask_filename, standardize=True,\n cv=cv)\ndecoder.fit(fmri_niimgs, conditions, groups=session_label)\n\nprint(decoder.cv_scores_)\n\n###########################################################################\n# Inspecting the model weights\n# -----------------------------\n#\n# Finally, it may be useful to inspect and display the model weights.\n#\n# Turning the weights into a nifti image\n# .......................................\n#\n# We retrieve the SVC discriminating weights\ncoef_ = decoder.coef_\nprint(coef_)\n\n###########################################################################\n# It's a numpy array with only one coefficient per voxel:\nprint(coef_.shape)\n\n###########################################################################\n# To get the Nifti image of these coefficients, we only need retrieve the\n# `coef_img_` in the decoder and select the class\n\ncoef_img = decoder.coef_img_['face']\n\n###########################################################################\n# coef_img is now a NiftiImage. We can save the coefficients as a nii.gz file:\ndecoder.coef_img_['face'].to_filename('haxby_svc_weights.nii.gz')\n\n###########################################################################\n# Plotting the SVM weights\n# .........................\n#\n# We can plot the weights, using the subject's anatomical as a background\nfrom nilearn.plotting import plot_stat_map, show\nplot_stat_map(decoder.coef_img_['face'], bg_img=haxby_dataset.anat[0],\n title=\"SVM weights\", display_mode=\"yx\")\n\nshow()\n\n###########################################################################\n# Further reading\n# ----------------\n#\n# * The :ref:`section of the documentation on decoding <decoding>`\n#\n# * :ref:`sphx_glr_auto_examples_02_decoding_plot_haxby_anova_svm.py`\n# For decoding without a precomputed mask\n#\n# * :ref:`space_net`\n#\n# ______________\n"
] |
[
[
"pandas.read_csv",
"sklearn.model_selection.KFold",
"sklearn.model_selection.LeaveOneGroupOut"
]
] |
qiang55/codes
|
[
"f50daf56fe67db0e5341436a828d37d05e1630e7"
] |
[
"mosfit/modules/seds/sed.py"
] |
[
"\"\"\"Definitions for the `SED` class.\"\"\"\nimport numpy as np\nfrom astropy import constants as c\nfrom astropy import units as u\n\nfrom mosfit.modules.module import Module\n\n\n# Important: Only define one ``Module`` class per file.\n\n\nclass SED(Module):\n \"\"\"Template class for SED Modules.\n\n Modules that inherit from the SED class should produce a `seds` key, which\n contains a spectral energy distribution for each time. The units of the SED\n should be in ergs/steradian/cm^2/Hz/Angstrom.\n \"\"\"\n\n C_OVER_ANG = (c.c / u.Angstrom).cgs.value\n\n def __init__(self, **kwargs):\n \"\"\"Initialize module.\"\"\"\n super(SED, self).__init__(**kwargs)\n self._N_PTS = 16 + 1\n self._sample_wavelengths = []\n\n def receive_requests(self, **requests):\n \"\"\"Receive requests from other ``Module`` objects.\"\"\"\n self._sample_wavelengths = requests.get('sample_wavelengths', [])\n if not self._sample_wavelengths:\n wave_ranges = requests.get('band_wave_ranges', [])\n if not wave_ranges:\n return\n max_len = 0\n for rng in wave_ranges:\n min_wav, max_wav = min(rng), max(rng)\n rngc = list(rng)\n rngc.remove(min_wav)\n rngc.remove(max_wav)\n self._sample_wavelengths.append(np.unique(np.concatenate(\n (np.linspace(min_wav, max_wav,\n self._N_PTS - len(rngc)), np.array(rngc)))))\n llen = len(self._sample_wavelengths[-1])\n if llen > max_len:\n max_len = llen\n for wi, wavs in enumerate(self._sample_wavelengths):\n if len(wavs) != max_len:\n self._sample_wavelengths[wi] = np.unique(np.concatenate(\n (wavs, (max(wavs) - min(wavs)) * 1.0 / np.exp(\n np.arange(1, 1 + max_len - len(\n wavs))) + min(wavs))))\n if len(self._sample_wavelengths[wi]) != max_len:\n raise RuntimeError(\n 'Could not construct wavelengths for bandpass.')\n\n # Note: Many of these will just be 0 - 1, but faster to have a\n # single type numpy array than a ragged list of lists.\n self._sample_wavelengths = np.array(self._sample_wavelengths,\n dtype=float)\n self._sample_frequencies = self.C_OVER_ANG / self._sample_wavelengths\n\n def add_to_existing_seds(self, new_seds, **kwargs):\n \"\"\"Add SED from module to existing ``seds`` key.\n\n Parameters\n ----------\n new_seds : array\n The new SEDs to add to the existing SEDs.\n\n Returns\n -------\n new_seds : array\n The result of summing the new and existing SEDs.\n\n \"\"\"\n old_seds = kwargs.get('seds', None)\n if old_seds is not None:\n for i, sed in enumerate(old_seds):\n new_seds[i] += sed\n return new_seds\n\n def send_request(self, request):\n \"\"\"Send a request.\"\"\"\n if request == 'sample_wavelengths':\n return self._sample_wavelengths\n return []\n\n def set_data(self, band_sampling_points):\n \"\"\"Set SED data.\"\"\"\n self._N_PTS = band_sampling_points\n return True\n"
] |
[
[
"numpy.array"
]
] |
S4NdeeP/sat-tensorflow
|
[
"cdc237b2bed24afc655af06b6e9570c557311af7"
] |
[
"core/model.py"
] |
[
"# =========================================================================================\n# Implementation of \"Show, Attend and Tell: Neural Caption Generator With Visual Attention\".\n# There are some notations.\n# N is batch size.\n# L is spacial size of feature vector (196).\n# D is dimension of image feature vector (512).\n# T is the number of time step which is equal to caption's length-1 (16).\n# V is vocabulary size (about 10000).\n# M is dimension of word vector which is embedding size (default is 512).\n# H is dimension of hidden state (default is 1024).\n# =========================================================================================\n\nfrom __future__ import division\n\nimport tensorflow as tf\n\n\nclass CaptionGenerator(object):\n def __init__(self, word_to_idx, dim_feature=[196, 512], dim_embed=512, dim_hidden=1024, n_time_step=16, \n prev2out=True, ctx2out=True, alpha_c=0.0, selector=True, dropout=True):\n \"\"\"\n Args:\n word_to_idx: word-to-index mapping dictionary.\n dim_feature: (optional) Dimension of vggnet19 conv5_3 feature vectors.\n dim_embed: (optional) Dimension of word embedding.\n dim_hidden: (optional) Dimension of all hidden state.\n n_time_step: (optional) Time step size of LSTM. \n prev2out: (optional) previously generated word to hidden state. (see Eq (7) for explanation)\n ctx2out: (optional) context to hidden state (see Eq (7) for explanation)\n alpha_c: (optional) Doubly stochastic regularization coefficient. (see Section (4.2.1) for explanation)\n selector: (optional) gating scalar for context vector. (see Section (4.2.1) for explanation)\n dropout: (optional) If true then dropout layer is added.\n \"\"\"\n \n self.word_to_idx = word_to_idx\n self.idx_to_word = {i: w for w, i in word_to_idx.iteritems()}\n self.prev2out = prev2out\n self.ctx2out = ctx2out\n self.alpha_c = alpha_c\n self.selector = selector\n self.dropout = dropout\n self.V = len(word_to_idx)\n self.L = dim_feature[0]\n self.D = dim_feature[1]\n self.M = dim_embed\n self.H = dim_hidden\n self.T = n_time_step\n self._start = word_to_idx['<START>']\n self._null = word_to_idx['<NULL>']\n\n self.weight_initializer = tf.contrib.layers.xavier_initializer()\n self.const_initializer = tf.constant_initializer(0.0)\n self.emb_initializer = tf.random_uniform_initializer(minval=-1.0, maxval=1.0)\n\n # Place holder for features and captions\n self.features = tf.placeholder(tf.float32, [None, self.L, self.D])\n self.captions = tf.placeholder(tf.int32, [None, self.T + 1])\n \n def _get_initial_lstm(self, features):\n with tf.variable_scope('initial_lstm'):\n features_mean = tf.reduce_mean(features, 1)\n\n w_h = tf.get_variable('w_h', [self.D, self.H], initializer=self.weight_initializer)\n b_h = tf.get_variable('b_h', [self.H], initializer=self.const_initializer)\n h = tf.nn.tanh(tf.matmul(features_mean, w_h) + b_h)\n\n w_c = tf.get_variable('w_c', [self.D, self.H], initializer=self.weight_initializer)\n b_c = tf.get_variable('b_c', [self.H], initializer=self.const_initializer)\n c = tf.nn.tanh(tf.matmul(features_mean, w_c) + b_c)\n return c, h\n\n def _word_embedding(self, inputs, reuse=False):\n with tf.variable_scope('word_embedding', reuse=reuse):\n w = tf.get_variable('w', [self.V, self.M], initializer=self.emb_initializer)\n x = tf.nn.embedding_lookup(w, inputs, name='word_vector') # (N, T, M) or (N, M)\n return x\n\n def _project_features(self, features):\n with tf.variable_scope('project_features'):\n w = tf.get_variable('w', [self.D, self.D], initializer=self.weight_initializer)\n features_flat = tf.reshape(features, [-1, self.D])\n features_proj = tf.matmul(features_flat, w) \n features_proj = tf.reshape(features_proj, [-1, self.L, self.D])\n return features_proj\n\n def _attention_layer(self, features, features_proj, h, reuse=False):\n with tf.variable_scope('attention_layer', reuse=reuse):\n w = tf.get_variable('w', [self.H, self.D], initializer=self.weight_initializer)\n b = tf.get_variable('b', [self.D], initializer=self.const_initializer)\n w_att = tf.get_variable('w_att', [self.D, 1], initializer=self.weight_initializer)\n\n h_att = tf.nn.relu(features_proj + tf.expand_dims(tf.matmul(h, w), 1) + b) # (N, L, D)\n out_att = tf.reshape(tf.matmul(tf.reshape(h_att, [-1, self.D]), w_att), [-1, self.L]) # (N, L)\n alpha = tf.nn.softmax(out_att) \n context = tf.reduce_sum(features * tf.expand_dims(alpha, 2), 1, name='context') #(N, D)\n return context, alpha\n \n def _selector(self, context, h, reuse=False):\n with tf.variable_scope('selector', reuse=reuse):\n w = tf.get_variable('w', [self.H, 1], initializer=self.weight_initializer)\n b = tf.get_variable('b', [1], initializer=self.const_initializer)\n beta = tf.nn.sigmoid(tf.matmul(h, w) + b, 'beta') # (N, 1)\n context = tf.multiply(beta, context, name='selected_context') \n return context, beta\n \n def _decode_lstm(self, x, h, context, dropout=False, reuse=False):\n with tf.variable_scope('logits', reuse=reuse):\n w_h = tf.get_variable('w_h', [self.H, self.M], initializer=self.weight_initializer)\n b_h = tf.get_variable('b_h', [self.M], initializer=self.const_initializer)\n w_out = tf.get_variable('w_out', [self.M, self.V], initializer=self.weight_initializer)\n b_out = tf.get_variable('b_out', [self.V], initializer=self.const_initializer)\n\n if dropout:\n h = tf.nn.dropout(h, 0.5)\n h_logits = tf.matmul(h, w_h) + b_h\n\n if self.ctx2out:\n w_ctx2out = tf.get_variable('w_ctx2out', [self.D, self.M], initializer=self.weight_initializer)\n h_logits += tf.matmul(context, w_ctx2out)\n\n if self.prev2out:\n h_logits += x\n h_logits = tf.nn.tanh(h_logits)\n\n if dropout:\n h_logits = tf.nn.dropout(h_logits, 0.5)\n out_logits = tf.matmul(h_logits, w_out) + b_out\n return out_logits\n \n def _batch_norm(self, x, mode='train', name=None):\n return tf.contrib.layers.batch_norm(inputs=x, \n decay=0.95,\n center=True,\n scale=True,\n is_training=(mode=='train'),\n updates_collections=None,\n scope=(name+'batch_norm'))\n\n def build_model(self):\n features = self.features\n captions = self.captions\n batch_size = tf.shape(features)[0]\n\n captions_in = captions[:, :self.T] \n captions_out = captions[:, 1:] \n mask = tf.to_float(tf.not_equal(captions_out, self._null))\n \n \n # batch normalize feature vectors\n features = self._batch_norm(features, mode='train', name='conv_features')\n \n c, h = self._get_initial_lstm(features=features)\n x = self._word_embedding(inputs=captions_in)\n features_proj = self._project_features(features=features)\n\n loss = 0.0\n alpha_list = []\n lstm_cell = tf.contrib.rnn.BasicLSTMCell(num_units=self.H)\n\n for t in range(self.T):\n context, alpha = self._attention_layer(features, features_proj, h, reuse=(t!=0))\n alpha_list.append(alpha)\n\n if self.selector:\n context, beta = self._selector(context, h, reuse=(t!=0)) \n\n with tf.variable_scope('lstm', reuse=(t!=0)):\n _, (c, h) = lstm_cell(inputs=tf.concat(axis=1, values=[x[:,t,:], context]), state=[c, h])\n\n logits = self._decode_lstm(x[:,t,:], h, context, dropout=self.dropout, reuse=(t!=0))\n loss += tf.reduce_sum(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=captions_out[:, t]) * mask[:, t])\n \n if self.alpha_c > 0:\n alphas = tf.transpose(tf.stack(alpha_list), (1, 0, 2)) # (N, T, L)\n alphas_all = tf.reduce_sum(alphas, 1) # (N, L)\n alpha_reg = self.alpha_c * tf.reduce_sum((16./196 - alphas_all) ** 2) \n loss += alpha_reg\n\n return loss / tf.to_float(batch_size)\n\n def build_sampler(self, max_len=20):\n features = self.features\n \n # batch normalize feature vectors\n features = self._batch_norm(features, mode='test', name='conv_features')\n \n c, h = self._get_initial_lstm(features=features)\n features_proj = self._project_features(features=features)\n\n sampled_word_list = []\n alpha_list = []\n beta_list = []\n lstm_cell = tf.contrib.rnn.BasicLSTMCell(num_units=self.H, reuse=tf.get_variable_scope().reuse)\n\n for t in range(max_len):\n if t == 0:\n x = self._word_embedding(inputs=tf.fill([tf.shape(features)[0]], self._start))\n else:\n x = self._word_embedding(inputs=sampled_word, reuse=True) \n \n context, alpha = self._attention_layer(features, features_proj, h, reuse=(t!=0))\n alpha_list.append(alpha)\n\n if self.selector:\n context, beta = self._selector(context, h, reuse=(t!=0)) \n beta_list.append(beta)\n\n with tf.variable_scope('lstm', reuse=(t!=0)):\n _, (c, h) = lstm_cell(inputs=tf.concat(axis=1, values=[x, context]), state=[c, h])\n\n logits = self._decode_lstm(x, h, context, reuse=(t!=0))\n sampled_word = tf.argmax(logits, 1) \n sampled_word_list.append(sampled_word) \n\n alphas = tf.transpose(tf.stack(alpha_list), (1, 0, 2)) # (N, T, L)\n betas = tf.transpose(tf.squeeze(beta_list), (1, 0)) # (N, T)\n sampled_captions = tf.transpose(tf.stack(sampled_word_list), (1, 0)) # (N, max_len)\n return alphas, betas, sampled_captions\n"
] |
[
[
"tensorflow.get_variable",
"tensorflow.concat",
"tensorflow.reduce_sum",
"tensorflow.stack",
"tensorflow.random_uniform_initializer",
"tensorflow.squeeze",
"tensorflow.contrib.layers.xavier_initializer",
"tensorflow.to_float",
"tensorflow.argmax",
"tensorflow.nn.dropout",
"tensorflow.matmul",
"tensorflow.shape",
"tensorflow.placeholder",
"tensorflow.nn.tanh",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits",
"tensorflow.contrib.layers.batch_norm",
"tensorflow.nn.embedding_lookup",
"tensorflow.not_equal",
"tensorflow.nn.softmax",
"tensorflow.multiply",
"tensorflow.reduce_mean",
"tensorflow.contrib.rnn.BasicLSTMCell",
"tensorflow.reshape",
"tensorflow.expand_dims",
"tensorflow.constant_initializer",
"tensorflow.variable_scope",
"tensorflow.get_variable_scope"
]
] |
fengliu90/DK-for-TST
|
[
"1c4065e81fb902e46e3316bfd98eadd0b7f22d74"
] |
[
"Ablation_Tests_MNIST.py"
] |
[
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Dec 21 14:57:02 2019\r\n@author: Learning Deep Kernels for Two-sample Test\r\n@Implementation of MMD-D and baselines in our paper on MNIST dataset\r\n\r\nBEFORE USING THIS CODE:\r\n1. This code requires PyTorch 1.1.0, which can be found in\r\nhttps://pytorch.org/get-started/previous-versions/ (CUDA version is 10.1).\r\n2. This code also requires freqopttest repo (interpretable nonparametric two-sample test)\r\nto implement ME and SCF tests, which can be installed by\r\n pip install git+https://github.com/wittawatj/interpretable-test\r\n3. Pickle is required to load fake MNIST datasets (generated by DCGAN), which can be installed by\r\n pip install pickle-mixin\r\n4. Numpy and Sklearn are also required. Users can install\r\nPython via Anaconda (Python 3.7.3) to obtain both packages. Anaconda\r\ncan be found in https://www.anaconda.com/distribution/#download-section .\r\n\"\"\"\r\nimport argparse\r\nimport os\r\nimport numpy as np\r\nimport torchvision.transforms as transforms\r\nfrom torch.utils.data import DataLoader\r\nfrom torchvision import datasets\r\nfrom torch.autograd import Variable\r\nimport torch.nn as nn\r\nimport torch\r\nimport pickle\r\nfrom utils_HD import MatConvert, Pdist2, MMDu, TST_MMD_adaptive_bandwidth, TST_MMD_u, MMDu_linear_kernel, TST_MMD_u_linear_kernel\r\n\r\n# Setup seeds\r\nos.makedirs(\"images\", exist_ok=True)\r\nnp.random.seed(819)\r\ntorch.manual_seed(819)\r\ntorch.cuda.manual_seed(819)\r\ntorch.backends.cudnn.deterministic = True\r\nis_cuda = True\r\n\r\n# parameters setting\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument(\"--n_epochs\", type=int, default=2000, help=\"number of epochs of training\")\r\nparser.add_argument(\"--batch_size\", type=int, default=100, help=\"size of the batches\")\r\nparser.add_argument(\"--lr\", type=float, default=0.0002, help=\"adam: learning rate\")\r\nparser.add_argument(\"--img_size\", type=int, default=32, help=\"size of each image dimension\")\r\nparser.add_argument(\"--channels\", type=int, default=1, help=\"number of image channels\")\r\nparser.add_argument(\"--n\", type=int, default=200, help=\"number of samples in one set\")\r\nopt = parser.parse_args()\r\nprint(opt)\r\ndtype = torch.float\r\ndevice = torch.device(\"cuda:0\")\r\ncuda = True if torch.cuda.is_available() else False\r\nN_per = 100 # permutation times\r\nalpha = 0.05 # test threshold\r\nN1 = opt.n # number of samples in one set\r\nK = 10 # number of trails\r\nN = 100 # number of test sets\r\nN_f = 100.0 # number of test sets (float)\r\n\r\n# Loss function\r\nadversarial_loss = torch.nn.CrossEntropyLoss()\r\n\r\n# Naming variables\r\nep_OPT = np.zeros([K])\r\ns_OPT = np.zeros([K])\r\ns0_OPT = np.zeros([K])\r\nResults = np.zeros([4,K])\r\n\r\n# Define the deep network for G+c and D+C\r\nclass Discriminator(nn.Module):\r\n def __init__(self):\r\n super(Discriminator, self).__init__()\r\n\r\n def discriminator_block(in_filters, out_filters, bn=True):\r\n block = [nn.Conv2d(in_filters, out_filters, 3, 2, 1), nn.LeakyReLU(0.2, inplace=True), nn.Dropout2d(0)] #0.25\r\n if bn:\r\n block.append(nn.BatchNorm2d(out_filters, 0.8))\r\n return block\r\n self.model = nn.Sequential(\r\n *discriminator_block(opt.channels, 16, bn=False),\r\n *discriminator_block(16, 32),\r\n *discriminator_block(32, 64),\r\n *discriminator_block(64, 128),\r\n )\r\n # The height and width of downsampled image\r\n ds_size = opt.img_size // 2 ** 4\r\n self.adv_layer = nn.Sequential(\r\n nn.Linear(128 * ds_size ** 2, 100),\r\n nn.ReLU())\r\n self.output_layer = nn.Sequential(\r\n nn.Linear(100, 2),\r\n nn.Softmax())\r\n def forward(self, img):\r\n out = self.model(img)\r\n out = out.view(out.shape[0], -1)\r\n fea = self.adv_layer(out)\r\n validity = self.output_layer(fea)\r\n\r\n return validity, fea # It is different with Discriminator defined in \"Deep_Baselines_MNIST.py\"\r\n\r\n# Define the deep network for L+J and G+J\r\nclass Featurizer(nn.Module):\r\n def __init__(self):\r\n super(Featurizer, self).__init__()\r\n\r\n def discriminator_block(in_filters, out_filters, bn=True):\r\n block = [nn.Conv2d(in_filters, out_filters, 3, 2, 1), nn.LeakyReLU(0.2, inplace=True), nn.Dropout2d(0)] #0.25\r\n if bn:\r\n block.append(nn.BatchNorm2d(out_filters, 0.8))\r\n return block\r\n\r\n self.model = nn.Sequential(\r\n *discriminator_block(opt.channels, 16, bn=False),\r\n *discriminator_block(16, 32),\r\n *discriminator_block(32, 64),\r\n *discriminator_block(64, 128),\r\n )\r\n\r\n # The height and width of downsampled image\r\n ds_size = opt.img_size // 2 ** 4\r\n self.adv_layer = nn.Sequential(\r\n nn.Linear(128 * ds_size ** 2, 100))\r\n\r\n def forward(self, img):\r\n out = self.model(img)\r\n out = out.view(out.shape[0], -1)\r\n feature = self.adv_layer(out)\r\n\r\n return feature\r\n\r\n# Configure data loader\r\nos.makedirs(\"./data/mnist\", exist_ok=True)\r\ndataloader_FULL = torch.utils.data.DataLoader(\r\n datasets.MNIST(\r\n \"./data/mnist\",\r\n train=True,\r\n download=True,\r\n transform=transforms.Compose(\r\n [transforms.Resize(opt.img_size), transforms.ToTensor(), transforms.Normalize([0.5], [0.5])]\r\n ),\r\n ),\r\n batch_size=60000,\r\n shuffle=True,\r\n)\r\n# Obtain real MNIST images\r\nfor i, (imgs, Labels) in enumerate(dataloader_FULL):\r\n data_all = imgs\r\n label_all = Labels\r\ndataloader_FULL_te = torch.utils.data.DataLoader(\r\n datasets.MNIST(\r\n \"./data/mnist\",\r\n train=False,\r\n download=True,\r\n transform=transforms.Compose(\r\n [transforms.Resize(opt.img_size), transforms.ToTensor(), transforms.Normalize([0.5], [0.5])]\r\n ),\r\n ),\r\n batch_size=10000,\r\n shuffle=True,\r\n)\r\nfor i, (imgs, Labels) in enumerate(dataloader_FULL_te):\r\n data_all_te = imgs\r\n label_all_te = Labels\r\n\r\n# Repeat experiments K times (K = 10) and report average test power (rejection rate)\r\nfor kk in range(K):\r\n torch.manual_seed(kk * 19 + N1)\r\n torch.cuda.manual_seed(kk * 19 + N1)\r\n np.random.seed(seed=1102 * (kk + 10) + N1)\r\n # Initialize deep networks for L+J and G+J (called featurizer), G+C and D+C (called discriminator)\r\n featurizer = Featurizer()\r\n discriminator = Discriminator()\r\n featurizer_linear_kernel = Featurizer()\r\n # Initialize parameters\r\n epsilonOPT = torch.log(MatConvert(np.random.rand(1) * 10 ** (-10), device, dtype))\r\n epsilonOPT.requires_grad = True\r\n sigmaOPT = MatConvert(np.ones(1) * np.sqrt(2*32*32), device, dtype)\r\n sigmaOPT.requires_grad = True\r\n sigma0OPT = MatConvert(np.ones(1) * np.sqrt(0.005), device, dtype)\r\n sigma0OPT.requires_grad = True\r\n print(epsilonOPT.item())\r\n if cuda:\r\n featurizer.cuda()\r\n discriminator.cuda()\r\n featurizer_linear_kernel.cuda()\r\n adversarial_loss.cuda()\r\n\r\n # Collect real MNIST images\r\n np.random.seed(seed=819 * (kk + 9) + N1)\r\n train_data = []\r\n ind_M_all = np.arange(4000)\r\n ind_M_tr = np.random.choice(4000, N1, replace=False)\r\n ind_M_te = np.delete(ind_M_all,ind_M_tr)\r\n for i in ind_M_tr:\r\n train_data.append([data_all[i], label_all[i]])\r\n\r\n dataloader = torch.utils.data.DataLoader(\r\n train_data,\r\n batch_size=opt.batch_size,\r\n shuffle=True,\r\n )\r\n\r\n # Collect fake MNIST images\r\n Fake_MNIST = pickle.load(open('./Fake_MNIST_data_EP100_N10000.pckl', 'rb'))\r\n ind_all = np.arange(4000)\r\n ind_tr = np.random.choice(4000, N1, replace=False)\r\n ind_te = np.delete(ind_all,ind_tr)\r\n Fake_MNIST_tr = torch.from_numpy(Fake_MNIST[0][ind_tr])\r\n Fake_MNIST_te = torch.from_numpy(Fake_MNIST[0][ind_te])\r\n # REPLACE above 6 lines with\r\n # Fake_MNIST_tr = data_all[ind_M_tr_all[N1:]]\r\n # Fake_MNIST_te = data_all[ind_M_te]\r\n # for validating type-I error\r\n\r\n # Initialize optimizers\r\n optimizer_F = torch.optim.Adam(list(featurizer.parameters()) + [epsilonOPT] + [sigmaOPT] + [sigma0OPT], lr=opt.lr)\r\n optimizer_F_linear_kernel = torch.optim.Adam(list(featurizer_linear_kernel.parameters()), lr=opt.lr)\r\n optimizer_D = torch.optim.Adam(discriminator.parameters(), lr=opt.lr)\r\n Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor\r\n\r\n # -------------------------------------------------------\r\n # Training L+J and G+J and deep networks of G+C and D+C\r\n # -------------------------------------------------------\r\n np.random.seed(seed=1102)\r\n torch.manual_seed(1102)\r\n torch.cuda.manual_seed(1102)\r\n for epoch in range(opt.n_epochs):\r\n for i, (imgs, _) in enumerate(dataloader):\r\n if True:\r\n ind = np.random.choice(N1, imgs.shape[0], replace=False)\r\n Fake_imgs = Fake_MNIST_tr[ind]\r\n # Adversarial ground truths\r\n valid = Variable(Tensor(imgs.shape[0], 1).fill_(1.0), requires_grad=False)\r\n fake = Variable(Tensor(imgs.shape[0], 1).fill_(0.0), requires_grad=False)\r\n # Configure input\r\n real_imgs = Variable(imgs.type(Tensor))\r\n Fake_imgs = Variable(Fake_imgs.type(Tensor))\r\n X = torch.cat([real_imgs, Fake_imgs], 0)\r\n Y = torch.cat([valid, fake], 0).squeeze().long()\r\n\r\n # -----------\r\n # Train G+J\r\n # -----------\r\n optimizer_F.zero_grad()\r\n modelu_output = featurizer(X)\r\n ep = torch.exp(epsilonOPT) / (1 + torch.exp(epsilonOPT))\r\n sigma = sigmaOPT ** 2\r\n sigma0_u = sigma0OPT ** 2\r\n TEMP = MMDu(modelu_output, imgs.shape[0], X.view(X.shape[0],-1), sigma, sigma0_u, ep, is_smooth=False)\r\n mmd_value_temp = -1 * (TEMP[0])\r\n mmd_std_temp = torch.sqrt(TEMP[1] + 10 ** (-8))\r\n if mmd_std_temp.item() == 0:\r\n print('error std!!')\r\n if np.isnan(mmd_std_temp.item()):\r\n print('error mmd!!')\r\n STAT_u = torch.div(mmd_value_temp, mmd_std_temp)\r\n STAT_u.backward()\r\n optimizer_F.step()\r\n\r\n # -----------\r\n # Train L+J\r\n # -----------\r\n optimizer_F_linear_kernel.zero_grad()\r\n modelu_output_linear = featurizer_linear_kernel(X)\r\n TEMP_l = MMDu_linear_kernel(modelu_output_linear, imgs.shape[0])\r\n mmd_value_temp_l = -1 * (TEMP_l[0])\r\n mmd_std_temp_l = torch.sqrt(TEMP_l[1] + 10 ** (-8))\r\n if mmd_std_temp_l.item() == 0:\r\n print('error std!!')\r\n if np.isnan(mmd_std_temp_l.item()):\r\n print('error mmd!!')\r\n STAT_u_l = torch.div(mmd_value_temp_l, mmd_std_temp_l)\r\n STAT_u_l.backward()\r\n optimizer_F_linear_kernel.step()\r\n\r\n # ------------------------------------\r\n # Train deep network for G+C and D+C\r\n # ------------------------------------\r\n optimizer_D.zero_grad()\r\n loss_C = adversarial_loss(discriminator(X)[0], Y)\r\n loss_C.backward()\r\n optimizer_D.step()\r\n if (epoch+1) % 100 == 0:\r\n print(\r\n \"[Epoch %d/%d] [Batch %d/%d] [CE loss: %f] [Stat J of L+J: %f] [Stat J of G+J: %f]\"\r\n % (epoch, opt.n_epochs, i, len(dataloader), loss_C.item(), -STAT_u.item(), -STAT_u_l.item())\r\n )\r\n batches_done = epoch * len(dataloader) + i\r\n else:\r\n break\r\n\r\n # Fetch training data\r\n s1 = data_all[ind_M_tr]\r\n s2 = Variable(Fake_MNIST_tr.type(Tensor))\r\n S = torch.cat([s1.cpu(),s2.cpu()],0).cuda()\r\n Sv = S.view(2*N1,-1)\r\n\r\n # Train G+C\r\n np.random.seed(seed=1102)\r\n torch.manual_seed(1102)\r\n torch.cuda.manual_seed(1102)\r\n S_m_v = discriminator(S)[1].view(2 * N1, -1)\r\n Dxy = Pdist2(S_m_v[:N1, :], S_m_v[N1:, :])\r\n sigma0 = torch.tensor(2*100) * torch.ones([1]).to(device, dtype)\r\n sigma0.requires_grad = True\r\n optimizer_sigma0 = torch.optim.Adam([sigma0], lr=0.001)\r\n for t in range(2000):\r\n TEMPa = MMDu(S_m_v, N1, S_m_v, sigma, sigma0, is_smooth=False)\r\n mmd_value_tempa = -1 * (TEMPa[0] + 10 ** (-8))\r\n mmd_std_tempa = torch.sqrt(TEMPa[1] + 10 ** (-8))\r\n if mmd_std_tempa.item() == 0:\r\n print('error!!')\r\n if np.isnan(mmd_std_tempa.item()):\r\n print('error!!')\r\n STAT_adaptive = torch.div(mmd_value_tempa, mmd_std_tempa)\r\n optimizer_sigma0.zero_grad()\r\n STAT_adaptive.backward(retain_graph=True)\r\n optimizer_sigma0.step()\r\n if t % 100 == 0:\r\n print(\"mmd_value: \", -1 * mmd_value_tempa.item(), \"mmd_std: \", mmd_std_tempa.item(), \"Statistic: \",\r\n -1 * STAT_adaptive.item())\r\n\r\n # Train D+C\r\n np.random.seed(seed=1102)\r\n torch.manual_seed(1102)\r\n torch.cuda.manual_seed(1102)\r\n S_m_v = discriminator(S)[1].view(2 * N1, -1)\r\n epsilonOPT_dc = torch.log(MatConvert(np.random.rand(1) * 10 ** (-10), device, dtype))\r\n epsilonOPT_dc.requires_grad = True\r\n sigmaOPT_dc = MatConvert(np.ones(1) * np.sqrt(8 * 32 * 32), device, dtype)\r\n sigmaOPT_dc.requires_grad = True\r\n sigma0OPT_dc = MatConvert(np.ones(1) * np.sqrt(2*200), device, dtype)\r\n sigma0OPT_dc.requires_grad = True\r\n optimizer_sigma0_dc = torch.optim.Adam([epsilonOPT_dc] + [sigmaOPT_dc] + [sigma0OPT_dc], lr=0.001)\r\n for t in range(2000):\r\n ep_dc = torch.exp(epsilonOPT_dc) / (1 + torch.exp(epsilonOPT_dc))\r\n sigma_dc = sigmaOPT_dc ** 2\r\n sigma0_dc = sigma0OPT_dc ** 2\r\n TEMPa_dc = MMDu(S_m_v, N1, Sv, sigma_dc, sigma0_dc, ep_dc)\r\n mmd_value_tempa_dc = -1 * (TEMPa_dc[0] + 10 ** (-8))\r\n mmd_std_tempa_dc = torch.sqrt(TEMPa_dc[1] + 10 ** (-8))\r\n STAT_adaptive_dc = torch.div(mmd_value_tempa_dc, mmd_std_tempa_dc)\r\n optimizer_sigma0_dc.zero_grad()\r\n STAT_adaptive_dc.backward(retain_graph=True)\r\n optimizer_sigma0_dc.step()\r\n if t % 100 == 0:\r\n print(\"mmd_value: \", -1 * mmd_value_tempa_dc.item(), \"mmd_std: \", mmd_std_tempa_dc.item(), \"Statistic J: \",\r\n -1 * STAT_adaptive_dc.item())\r\n\r\n # Run two-sample test on the training set\r\n # G+C\r\n h_adaptive, threshold_adaptive, mmd_value_adaptive = TST_MMD_adaptive_bandwidth(S_m_v, N_per, N1, S_m_v, sigma,\r\n sigma0, alpha, device, dtype)\r\n # G+J\r\n h_u, threshold_u, mmd_value_u = TST_MMD_u(featurizer(S), N_per, N1, Sv, sigma, sigma0_u, ep, alpha, device, dtype,\r\n is_smooth=False)\r\n # L+J\r\n h_u_l, threshold_u_l, mmd_value_u_l = TST_MMD_u_linear_kernel(featurizer(S), N_per, N1, alpha, device, dtype)\r\n\r\n # D+C\r\n h_adaptive_dc, threshold_adaptive_dc, mmd_value_adaptive_dc = TST_MMD_u(S_m_v, N_per, N1, Sv, sigma_dc,\r\n sigma0_dc, ep_dc, alpha,device, dtype)\r\n\r\n # Record best epsilon, sigma and sigma_0\r\n ep_OPT[kk] = ep.item()\r\n s_OPT[kk] = sigma.item()\r\n s0_OPT[kk] = sigma0_u.item()\r\n\r\n # Compute test power of MMD-D and baselines\r\n H_u = np.zeros(N)\r\n T_u = np.zeros(N)\r\n M_u = np.zeros(N)\r\n H_u_l = np.zeros(N)\r\n T_u_l = np.zeros(N)\r\n M_u_l = np.zeros(N)\r\n H_adaptive = np.zeros(N)\r\n T_adaptive = np.zeros(N)\r\n M_adaptive = np.zeros(N)\r\n H_adaptive_dc = np.zeros(N)\r\n T_adaptive_dc = np.zeros(N)\r\n M_adaptive_dc = np.zeros(N)\r\n np.random.seed(1102)\r\n count_u = 0\r\n count_adp = 0\r\n count_u_l = 0\r\n count_adp_dc = 0\r\n for k in range(N):\r\n # Fetch test data\r\n np.random.seed(seed=1102 * (k + 1) + N1)\r\n ind_M = np.random.choice(len(ind_M_te), N1, replace=False)\r\n s1 = data_all[ind_M_te[ind_M]]\r\n np.random.seed(seed=819 * (k + 3) + N1)\r\n ind_F = np.random.choice(len(Fake_MNIST_te), N1, replace=False)\r\n s2 = Variable(Fake_MNIST_te[ind_F].type(Tensor))\r\n S = torch.cat([s1.cpu(), s2.cpu()], 0).cuda()\r\n Sv = S.view(2 * N1, -1)\r\n S_m_v = discriminator(S)[1].view(2 * N1, -1)\r\n\r\n # Run two-sample test on the test set\r\n # G+C\r\n h_adaptive, threshold_adaptive, mmd_value_adaptive = TST_MMD_adaptive_bandwidth(S_m_v, N_per, N1, S_m_v, sigma,\r\n sigma0, alpha, device, dtype)\r\n # G+J\r\n h_u, threshold_u, mmd_value_u = TST_MMD_u(featurizer(S), N_per, N1, Sv, sigma, sigma0_u, ep, alpha, device,\r\n dtype, is_smooth=False)\r\n # L+J\r\n h_u_l, threshold_u_l, mmd_value_u_l = TST_MMD_u_linear_kernel(featurizer(S), N_per, N1, alpha, device, dtype)\r\n\r\n # D+C\r\n h_adaptive_dc, threshold_adaptive_dc, mmd_value_adaptive_dc = TST_MMD_u(S_m_v, N_per, N1, Sv, sigma_dc,\r\n sigma0_dc, ep_dc, alpha, device, dtype)\r\n # Gather results\r\n count_u = count_u + h_u\r\n count_adp = count_adp + h_adaptive\r\n count_u_l = count_u_l + h_u_l\r\n count_adp_dc = count_adp_dc + h_adaptive_dc\r\n print(\"L+J:\", count_u_l,\"G+J:\", count_u,\"G+C:\", count_adp,\"D+C:\", count_adp_dc)\r\n H_u[k] = h_u\r\n T_u[k] = threshold_u\r\n M_u[k] = mmd_value_u\r\n H_u_l[k] = h_u_l\r\n T_u_l[k] = threshold_u_l\r\n M_u_l[k] = mmd_value_u_l\r\n H_adaptive[k] = h_adaptive\r\n T_adaptive[k] = threshold_adaptive\r\n M_adaptive[k] = mmd_value_adaptive\r\n H_adaptive_dc[k] = h_adaptive_dc\r\n T_adaptive_dc[k] = threshold_adaptive_dc\r\n M_adaptive_dc[k] = mmd_value_adaptive_dc\r\n print(\"Reject rate_LJ: \", H_u_l.sum() / N_f, \"Reject rate_GJ: \", H_u.sum() / N_f, \"Reject rate_GC:\",\r\n H_adaptive.sum() / N_f,\r\n \"Reject rate_DC: \", H_adaptive_dc.sum() / N_f)\r\n Results[0, kk] = H_u_l.sum() / N_f\r\n Results[1, kk] = H_u.sum() / N_f\r\n Results[2, kk] = H_adaptive.sum() / N_f\r\n Results[3, kk] = H_adaptive_dc.sum() / N_f\r\n print(\"Test Power of deep kernel based tests (K times): \")\r\n print(Results)\r\n print(\"Average Test Power of deep kernel based tests (K times): \")\r\n print(Results.sum(1) / (kk + 1))"
] |
[
[
"torch.nn.Softmax",
"torch.nn.Dropout2d",
"numpy.sqrt",
"torch.cat",
"torch.utils.data.DataLoader",
"torch.cuda.is_available",
"torch.device",
"torch.nn.CrossEntropyLoss",
"torch.ones",
"torch.sqrt",
"numpy.arange",
"torch.from_numpy",
"torch.tensor",
"numpy.zeros",
"torch.optim.Adam",
"torch.div",
"numpy.random.choice",
"torch.nn.Conv2d",
"torch.exp",
"torch.nn.Linear",
"numpy.delete",
"torch.nn.LeakyReLU",
"numpy.random.rand",
"torch.nn.BatchNorm2d",
"torch.cuda.manual_seed",
"numpy.random.seed",
"torch.manual_seed",
"numpy.ones",
"torch.nn.ReLU"
]
] |
AakashKT/analytic_ss_cpu
|
[
"1d6528d5a86db314c336906cd579a1ac46d4b53c"
] |
[
"plot_runtime.py"
] |
[
"import os, sys, math, random, time, csv, copy, argparse\n\nimport matplotlib\nfrom matplotlib import cm\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nimport cv2\n\nfig = None\nax1 = None\nax2 = None\nax3 = None\n\ndef plot_overall():\n # max_vals = [\n # 94.03,\n # 98.06,\n # 94.43,\n # ]\n # vals = [\n # [3.6, 4.53, 10.01, 53.98, 14.16],\n # [4.05, 13.29, 19.0, 27.93, 26.31],\n # [4.57, 5.05, 11.04, 50.25, 16.29],\n # ]\n scene_names = ['Dining Room', 'Table', 'Living Room']\n for i, _ in enumerate(vals):\n vals[i].append(max_vals[i]-sum(vals[i]))\n \n vals = np.array(vals).T\n labels = ['Frustum Culling', 'LTC Integration', 'Lights Preproc', 'Occluder Preproc', 'Set Difference', 'Misc']\n colors = ['tomato', 'sandybrown', 'wheat', 'khaki', 'lightgreen', 'lightgrey']\n\n ind = np.arange(len(max_vals))\n\n ax1.set_xticks(ind)\n ax1.set_xticklabels(scene_names)\n \n for i in range(vals.shape[0]):\n if i == 0:\n ax1.bar(ind, vals[i, :], 0.35, color=colors[i])\n else:\n ax1.bar(ind, vals[i, :], 0.35, bottom=np.sum(vals[:i, :], axis=0), color=colors[i])\n\n ax1.set_ylabel('Relative Time')\n ax1.set_xlabel('Scenes')\n ax1.legend(labels=labels)\n\ndef plot_lights():\n # max_vals = [\n # 10.01,\n # 19.0,\n # 11.04,\n # ]\n # vals = [\n # [0.27, 0.24, 2.66, 0.89, 3.68],\n # [0.63, 0.57, 2.09, 6.04, 5.51],\n # [0.42, 0.21, 1.81, 3.28, 2.97],\n # ]\n scene_names = ['Dining Room', 'Table', 'Living Room']\n for i, _ in enumerate(vals):\n vals[i].append(max_vals[i]-sum(vals[i]))\n \n vals = np.array(vals).T\n labels = ['Clip To Horizon', 'Local Shading Transform', 'Project To Plane', 'Silhouette Comp.', 'Sort Edges', 'Misc']\n colors = ['tomato', 'sandybrown', 'wheat', 'khaki', 'lightgreen', 'lightgrey']\n\n ind = np.arange(len(max_vals))\n\n ax2.set_xticks(ind)\n ax2.set_xticklabels(scene_names)\n\n for i in range(vals.shape[0]):\n if i == 0:\n ax2.bar(ind, vals[i, :], 0.35, color=colors[i])\n else:\n ax2.bar(ind, vals[i, :], 0.35, bottom=np.sum(vals[:i, :], axis=0), color=colors[i])\n\n ax2.set_ylabel('Relative Time')\n ax2.set_xlabel('Light Preprocess')\n ax2.legend(labels=labels)\n\ndef plot_occluder():\n # max_vals = [\n # 53.98,\n # 27.93,\n # 50.25,\n # ]\n # vals = [\n # [4.04, 1.38, 10.77, 14.96, 15.65],\n # [1.11, 0.99, 3.56, 9.64, 7.01],\n # [1.96, 1.27, 9.03, 15.8, 14.5],\n # ]\n scene_names = ['Dining Room', 'Table', 'Living Room']\n for i, _ in enumerate(vals):\n vals[i].append(max_vals[i]-sum(vals[i]))\n \n vals = np.array(vals).T\n labels = ['Clip To Horizon', 'Local Shading Transform', 'Project To Plane', 'Silhouette Comp.', 'Sort Edges', 'Misc']\n colors = ['tomato', 'sandybrown', 'wheat', 'khaki', 'lightgreen', 'lightgrey']\n\n ind = np.arange(len(max_vals))\n\n ax3.set_xticks(ind)\n ax3.set_xticklabels(scene_names)\n\n for i in range(vals.shape[0]):\n if i == 0:\n ax3.bar(ind, vals[i, :], 0.35, color=colors[i])\n else:\n ax3.bar(ind, vals[i, :], 0.35, bottom=np.sum(vals[:i, :], axis=0), color=colors[i])\n\n ax3.set_ylabel('Relative Time')\n ax3.set_xlabel('Occluder Preprocess')\n ax3.legend(labels=labels)\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n args = parser.parse_args()\n\n nrows = 1\n ncols = 3\n\n fig = plt.figure(figsize=(16, 8))\n\n ax1 = fig.add_subplot(nrows, ncols, 1)\n ax2 = fig.add_subplot(nrows, ncols, 2)\n ax3 = fig.add_subplot(nrows, ncols, 3)\n\n plot_overall()\n plot_lights()\n plot_occluder()\n\n plt.show()"
] |
[
[
"numpy.array",
"matplotlib.pyplot.show",
"numpy.sum",
"matplotlib.pyplot.figure"
]
] |
geyang/gym-sawyer
|
[
"c6e81ab4faefafcfa3886d74672976cc16452747"
] |
[
"sawyer/peg_3d.py"
] |
[
"from collections import OrderedDict\nimport numpy as np\nimport gym\nfrom gym.spaces import Box, Dict\n\nfrom .env_util import get_asset_full_path\nfrom .base import SawyerXYZEnv, SawyerCamEnv, pick\n\n\nclass SawyerPeg3DEnv(SawyerCamEnv, SawyerXYZEnv):\n\n def __init__(\n self,\n task=None,\n slot_low=None,\n slot_high=None,\n init_mode=None,\n goal_mode=None,\n cam_id=-1,\n **kwargs\n ):\n self.task = task\n\n model_name = get_asset_full_path(f'sawyer_peg_3d.xml')\n\n SawyerXYZEnv.__init__(self, model_name=model_name, **kwargs)\n SawyerCamEnv.__init__(self, cam_id=cam_id, **kwargs)\n\n self.init_mode = init_mode\n self.goal_mode = goal_mode\n\n # extend the observation space with objects\n self.slot_space = Box(np.array(slot_low), np.array(slot_high))\n d = pick(self.observation_space.spaces, *self.obs_keys)\n d[f'slot'] = self.slot_space\n self.observation_space = gym.spaces.Dict(**d)\n\n obs_keys = \"hand\", \"slot\"\n goal_keys = \"hand\",\n\n def get_slot_pos(self):\n return self.data.get_body_xpos('slot').copy()\n\n def _set_slot_xyz(self, pos, slot_id=0):\n qpos = self.data.qpos.flat.copy()\n qvel = self.data.qvel.flat.copy()\n offset = slot_id * 7\n qpos[9 + offset:12 + offset] = pos.copy()\n # qvel[9 + offset:12 + offset] = 0\n self.set_state(qpos, qvel)\n\n def _set_markers(self):\n self._set_slot_xyz(self.slot_pos)\n\n def state_dict(self):\n state = super().state_dict()\n return {**state, \"slot\": self.get_slot_pos()}\n\n # todo: might need to change the mode.\n def reset_model(self, mode=None, to_goal=None):\n \"\"\"Provide high-level `mode` for sampling types of goal configurations.\"\"\"\n self._fast_reset()\n mode = mode or (self.goal_mode if to_goal else self.init_mode)\n\n self.slot_pos = self.slot_space.sample()\n self._set_slot_xyz(self.slot_pos)\n\n rd = self.np_random.rand()\n if mode is None:\n if rd < 0.90:\n mode = 'hover'\n else:\n mode = \"inserted\"\n\n if mode == 'hover': # hover\n\n self.gripper = self.np_random.choice([-1, 1], size=1)\n\n target = self.hand_space.sample()\n target += [0, 0, 0.1]\n self._reset_hand(target, [1, -1])\n\n elif mode == \"inserted\":\n\n self.gripper = 1 # always close the pincher\n\n target = self.slot_pos + [0, 0, 0.1]\n self._reset_hand(target, [1, -1])\n target = [*self.slot_pos[:2], 0.05]\n self._reset_hand(target, [1, -1])\n else:\n raise NotImplementedError(f\"{mode} is not supported\")\n\n # todo: might be necessary\n # self._set_slot_xyz(self.slot_pos)\n return self.get_obs()\n\n\ngym.envs.register(\n id=\"Peg3D-v0\",\n entry_point=SawyerPeg3DEnv,\n # Place goal has to be on the surface.\n kwargs=dict(frame_skip=5,\n # init_mode=\"hover\",\n goal_mode=\"inserted\",\n mocap_low=(-0.1, 0.45, 0.05),\n mocap_high=(0.1, 0.55, 0.40),\n slot_low=(0.0, 0.5, 0.025),\n slot_high=(0.0, 0.5, 0.025)\n ),\n # max_episode_steps=100,\n reward_threshold=-3.75,\n)\n"
] |
[
[
"numpy.array"
]
] |
sam210723/xrit-rx
|
[
"405b01578240ff554752a6ea64da403d7c606859"
] |
[
"src/products.py"
] |
[
"\"\"\"\nproducts.py\nhttps://github.com/sam210723/xrit-rx\n\nParsing and assembly functions for downlinked products\n\"\"\"\n\nimport collections\nimport colorama\nfrom colorama import Fore, Back, Style\nimport io\nimport numpy as np\nimport pathlib\nfrom PIL import Image, ImageFile, UnidentifiedImageError\nimport subprocess\n\n\ndef new(config, name):\n \"\"\"\n Get new product class\n \"\"\"\n\n types = {\n \"GK-2A\": {\n \"LRIT\": {\n \"FD\": MultiSegmentImage,\n \"ANT\": AlphanumericText\n },\n \"HRIT\": {\n \"FD\": MultiSegmentImage\n }\n }\n }\n\n # Observation mode\n mode = name.split(\"_\")[1]\n\n try:\n # Get product type from dict\n pclass = types[config.spacecraft][config.downlink][mode]\n except KeyError:\n # Treat all other products as single segment images\n pclass = SingleSegmentImage\n \n return pclass(config, name)\n\n\nclass Product:\n \"\"\"\n Product base class\n \"\"\"\n\n def __init__(self, config, name):\n self.config = config # Configuration tuple\n self.name = self.parse_name(name) # Product name\n self.alias = \"PRODUCT\" # Product type alias\n self.complete = False # Completed product flag\n self.last = None # Path to last file saved\n \n def parse_name(self, n):\n \"\"\"\n Parse file name into namedtuple\n \"\"\"\n\n name = collections.namedtuple(\"name\", \"type mode sequence date time full\")\n parts = n.split(\"_\")\n full = n.split(\".\")[0][:-3]\n\n if parts[0] == \"IMG\":\n # Generalise filename for multi-channel HRIT images\n if self.config.downlink == \"HRIT\":\n gen = n.split(\"_\")\n gen[3] = \"<CHANNEL>\"\n full = \"_\".join(gen).split(\".\")[0][:-3]\n \n tup = name(\n parts[0],\n parts[1],\n int(parts[2]),\n self.parse_date(parts[4]),\n self.parse_time(parts[5]),\n full\n )\n else:\n tup = name(\n parts[0],\n parts[1],\n int(parts[2]),\n self.parse_date(parts[3]),\n self.parse_time(parts[4]),\n full\n )\n \n return tup\n\n def parse_date(self, date):\n d = date[6:]\n m = date[4:6]\n y = date[:4]\n\n return (d, m, y)\n\n def parse_time(self, time):\n h = time[:2]\n m = time[2:4]\n s = time[4:6]\n\n return (h, m ,s)\n\n def get_save_path(self, ext=\"\", filename=True):\n \"\"\"\n Get save path of product (without extension)\n \"\"\"\n\n # Build file output path (root + date + observation mode)\n root = self.config.output\n date = \"{2}{1}{0}\".format(*self.name.date)\n path = \"{}{}/{}/\".format(root, date, self.name.mode)\n\n # Check output directories exist\n pathlib.Path(path).mkdir(parents=True, exist_ok=True)\n\n # Assemble final file path and name\n return \"{}{}{}\".format(\n path,\n \"\" if not filename else self.name.full,\n \"\" if not ext else \".{}\".format(ext)\n )\n\n def print_info(self):\n \"\"\"\n Print product info\n \"\"\"\n\n print(\" [PRODUCT] {} #{} {}:{}:{} UTC {}/{}/{}\".format(\n self.name.mode,\n self.name.sequence,\n *self.name.time,\n *self.name.date\n ))\n\n\nclass MultiSegmentImage(Product):\n \"\"\"\n Multi-segment image products (e.g. Full Disk)\n \"\"\"\n\n def __init__(self, config, name):\n # Call parent class init method\n Product.__init__(self, config, name)\n \n # Product specific setup\n self.counter = 0 # Segment counter\n self.images = {} # Image list\n self.ext = \"jpg\" # Output file extension\n self.lastproglen = 0 # Last number of lines in progress indicator\n\n def add(self, xrit):\n \"\"\"\n Add data to product\n \"\"\"\n\n # Get channel and segment number\n chan = xrit.FILE_NAME.split(\"_\")[3]\n num = int(xrit.FILE_NAME.split(\".\")[0][-2:])\n\n # Check object for current channel exists\n try:\n self.images[chan]\n except:\n self.images[chan] = {}\n\n # Get file name\n fname = xrit.FILE_NAME.split(\".\")[0]\n\n if self.config.downlink == \"LRIT\":\n # Get image from JPG payload\n buf = io.BytesIO(xrit.DATA_FIELD)\n \n try:\n img = Image.open(buf)\n except UnidentifiedImageError:\n print(\" \" + Fore.WHITE + Back.RED + Style.BRIGHT + \"NO IMAGE FOUND IN XRIT FILE\")\n return\n else:\n # Get image from J2K payload\n img = self.convert_to_img(self.get_save_path(filename=False), fname, xrit.DATA_FIELD)\n\n # Add segment to channel object\n self.images[chan][num] = img\n self.counter += 1\n\n # Update progress bar\n if not self.config.verbose:\n self.progress()\n\n # Mark product as complete\n total_segs = { \"LRIT\": 10, \"HRIT\": 50 }\n if self.counter == total_segs[self.config.downlink]: self.complete = True\n\n def save(self):\n \"\"\"\n Save product to disk\n \"\"\"\n \n path = self.get_save_path(filename=False)\n\n for c in self.images:\n # Create output image\n img = Image.new(\"RGB\", self.get_res(c))\n\n # Combine segments into final image\n for s in self.images[c]:\n height = self.images[c][s].size[1]\n offset = height * (s - 1)\n \n try:\n img.paste(\n self.images[c][s],\n ( 0, offset )\n )\n except OSError:\n print(\" \" + Fore.WHITE + Back.RED + Style.BRIGHT + \"SKIPPING TRUNCATED IMAGE SEGMENT\")\n \n # Get image path for current channel\n channel_path = \"{}{}.{}\".format(\n path,\n self.name.full.replace(\"<CHANNEL>\", c),\n self.ext\n )\n\n # Save final image\n img.save(channel_path, format='JPEG', subsampling=0, quality=100)\n print(\" \" + Fore.GREEN + Style.BRIGHT + \"Saved \\\"{}\\\"\".format(channel_path))\n self.last = channel_path\n \n def convert_to_img(self, path, name, data):\n \"\"\"\n Converts J2K to Pillow Image object via PPM using libjpeg\n\n Arguments:\n path {string} -- Path for temporary files\n data {bytes} -- JPEG2000 image\n\n Returns:\n Pillow.Image -- Pillow Image object\n \"\"\"\n\n # Save JP2 to disk\n jp2Name = path + name + \".jp2\"\n f = open(jp2Name, \"wb\")\n f.write(data)\n f.close()\n\n # Convert J2P to PPM\n ppmName = path + name + \".ppm\"\n subprocess.call([\"tools\\\\libjpeg\\\\jpeg\", jp2Name, ppmName], stdout=subprocess.DEVNULL)\n pathlib.Path(jp2Name).unlink()\n \n # Load and convert 16-bit PPM to 8-bit image\n img = Image.open(ppmName)\n iarr = np.uint8(np.array(img) / 4)\n img = Image.fromarray(iarr)\n pathlib.Path(ppmName).unlink()\n return img\n \n def get_res(self, channel):\n \"\"\"\n Returns the horizontal and vertical resolution of the given satellte, downlink, observation mode and channel\n \"\"\"\n\n res = {\n \"GK-2A\": {\n \"LRIT\": {\n \"FD\": {\n \"IR105\": (2200, 2200)\n }\n },\n \"HRIT\": {\n \"FD\": {\n \"IR105\": (2750, 2750),\n \"IR123\": (2750, 2750),\n \"SW038\": (2750, 2750),\n \"WV069\": (2750, 2750),\n \"VI006\": (11000, 11000)\n }\n }\n }\n }\n\n try:\n return res[self.config.spacecraft][self.config.downlink][self.name.mode][channel]\n except:\n return (None, None)\n\n def progress(self):\n \"\"\"\n Renders progress bar for multi-segment mult-wavelength images\n \"\"\"\n\n # Clear previous console lines\n for i in range(self.lastproglen):\n print(\"\\33[2K\\r\", end=\"\", flush=True)\n print(\"\\033[1A\", end=\"\", flush=True)\n\n line = \"\"\n self.lastproglen = 0\n\n # Loop through channels\n for c in self.images:\n line += \" {} {}{}{}{}{}{}{}{}{}{} {}/{}\\n\".format(\n c,\n \"\\u2588\\u2588\" if 1 in self.images[c].keys() else \"\\u2591\\u2591\",\n \"\\u2588\\u2588\" if 2 in self.images[c].keys() else \"\\u2591\\u2591\",\n \"\\u2588\\u2588\" if 3 in self.images[c].keys() else \"\\u2591\\u2591\",\n \"\\u2588\\u2588\" if 4 in self.images[c].keys() else \"\\u2591\\u2591\",\n \"\\u2588\\u2588\" if 5 in self.images[c].keys() else \"\\u2591\\u2591\",\n \"\\u2588\\u2588\" if 6 in self.images[c].keys() else \"\\u2591\\u2591\",\n \"\\u2588\\u2588\" if 7 in self.images[c].keys() else \"\\u2591\\u2591\",\n \"\\u2588\\u2588\" if 8 in self.images[c].keys() else \"\\u2591\\u2591\",\n \"\\u2588\\u2588\" if 9 in self.images[c].keys() else \"\\u2591\\u2591\",\n \"\\u2588\\u2588\" if 10 in self.images[c].keys() else \"\\u2591\\u2591\",\n len(self.images[c]),\n 10\n )\n self.lastproglen += 1\n \n print(line, end=\"\", flush=True)\n\n\nclass SingleSegmentImage(Product):\n \"\"\"\n Single segment image products (e.g. Additional Data)\n \"\"\"\n\n def __init__(self, config, name):\n # Call parent class init method\n Product.__init__(self, config, name)\n \n # Product specific setup\n self.payload = None\n\n def add(self, xrit):\n \"\"\"\n Add data to product\n \"\"\"\n\n self.payload = xrit.DATA_FIELD\n self.complete = True\n\n def save(self):\n \"\"\"\n Save product to disk\n \"\"\"\n\n self.ext = self.get_ext()\n path = self.get_save_path(self.ext)\n\n outf = open(path, mode=\"wb\")\n outf.write(self.payload)\n outf.close()\n\n print(\" \" + Fore.GREEN + Style.BRIGHT + \"Saved \\\"{}\\\"\".format(path))\n self.last = path\n\n def get_ext(self):\n \"\"\"\n Detects output extension based on file signature\n \"\"\"\n\n ext = \"bin\"\n if self.payload[:3] == b'GIF':\n ext = \"gif\"\n elif self.payload[1:4] == b'PNG':\n ext = \"png\"\n\n return ext\n\n\nclass AlphanumericText(Product):\n \"\"\"\n Plain text products (e.g. Transmission Schedule)\n \"\"\"\n\n def __init__(self, config, name):\n # Call parent class init method\n Product.__init__(self, config, name)\n \n # Product specific setup\n self.payload = None\n self.ext = \"txt\"\n\n def add(self, xrit):\n \"\"\"\n Add data to product\n \"\"\"\n\n self.payload = xrit.DATA_FIELD\n self.complete = True\n\n def save(self):\n \"\"\"\n Save product to disk\n \"\"\"\n\n path = self.get_save_path(self.ext)\n \n outf = open(path, mode=\"wb\")\n outf.write(self.payload)\n outf.close()\n\n # Detect GK-2A LRIT DOP\n if self.payload[:40].decode('utf-8') == \"GK-2A AMI LRIT DOP(Daily Operation Plan)\":\n print(\" GK-2A LRIT Daily Operation Plan\")\n\n print(\" \" + Fore.GREEN + Style.BRIGHT + \"Saved \\\"{}\\\"\".format(path))\n self.last = path\n"
] |
[
[
"numpy.array"
]
] |
cthoyt/pykeen
|
[
"e2164149492291ba5e4b130ab8d2f9babfc55a50",
"e2164149492291ba5e4b130ab8d2f9babfc55a50"
] |
[
"tests/test_models.py",
"src/pykeen/datasets/ogb.py"
] |
[
"# -*- coding: utf-8 -*-\n\n\"\"\"Test that models can be executed.\"\"\"\n\nimport importlib\nimport os\nimport tempfile\nimport traceback\nimport unittest\nfrom typing import Any, ClassVar, Mapping, Optional, Type\nfrom unittest.mock import patch\n\nimport numpy\nimport pytest\nimport torch\nfrom click.testing import CliRunner, Result\nfrom torch import nn, optim\nfrom torch.optim import SGD\nfrom torch.optim.adagrad import Adagrad\n\nimport pykeen.experiments\nimport pykeen.models\nfrom pykeen.datasets.kinships import KINSHIPS_TRAIN_PATH\nfrom pykeen.datasets.nations import NATIONS_TEST_PATH, NATIONS_TRAIN_PATH, Nations\nfrom pykeen.models import _MODELS\nfrom pykeen.models.base import (\n EntityEmbeddingModel,\n EntityRelationEmbeddingModel,\n Model,\n MultimodalModel,\n _extend_batch,\n get_novelty_mask,\n)\nfrom pykeen.models.cli import build_cli_from_cls\nfrom pykeen.models.unimodal.rgcn import (\n inverse_indegree_edge_weights,\n inverse_outdegree_edge_weights,\n symmetric_edge_weights,\n)\nfrom pykeen.models.unimodal.trans_d import _project_entity\nfrom pykeen.nn import Embedding, RepresentationModule\nfrom pykeen.training import LCWATrainingLoop, SLCWATrainingLoop, TrainingLoop\nfrom pykeen.triples import TriplesFactory\nfrom pykeen.utils import all_in_bounds, clamp_norm, set_random_seed\n\nSKIP_MODULES = {\n Model.__name__,\n 'DummyModel',\n MultimodalModel.__name__,\n EntityEmbeddingModel.__name__,\n EntityRelationEmbeddingModel.__name__,\n 'MockModel',\n 'models',\n 'get_model_cls',\n 'SimpleInteractionModel',\n}\nfor cls in MultimodalModel.__subclasses__():\n SKIP_MODULES.add(cls.__name__)\n\n_EPSILON = 1.0e-07\n\n\nclass _CustomRepresentations(RepresentationModule):\n \"\"\"A custom representation module with minimal implementation.\"\"\"\n\n def __init__(self, num_entities: int, embedding_dim: int = 2):\n super().__init__()\n self.num_embeddings = num_entities\n self.embedding_dim = embedding_dim\n self.x = nn.Parameter(torch.rand(embedding_dim))\n\n def forward(self, indices: Optional[torch.LongTensor] = None) -> torch.FloatTensor:\n n = self.num_embeddings if indices is None else indices.shape[0]\n return self.x.unsqueeze(dim=0).repeat(n, 1)\n\n def get_in_canonical_shape(\n self,\n indices: Optional[torch.LongTensor] = None,\n ) -> torch.FloatTensor:\n x = self(indices=indices)\n if indices is None:\n return x.unsqueeze(dim=0)\n return x.unsqueeze(dim=1)\n\n\nclass _ModelTestCase:\n \"\"\"A test case for quickly defining common tests for KGE models.\"\"\"\n\n #: The class of the model to test\n model_cls: ClassVar[Type[Model]]\n\n #: Additional arguments passed to the model's constructor method\n model_kwargs: ClassVar[Optional[Mapping[str, Any]]] = None\n\n #: Additional arguments passed to the training loop's constructor method\n training_loop_kwargs: ClassVar[Optional[Mapping[str, Any]]] = None\n\n #: The triples factory instance\n factory: TriplesFactory\n\n #: The model instance\n model: Model\n\n #: The batch size for use for forward_* tests\n batch_size: int = 20\n\n #: The embedding dimensionality\n embedding_dim: int = 3\n\n #: Whether to create inverse triples (needed e.g. by ConvE)\n create_inverse_triples: bool = False\n\n #: The sampler to use for sLCWA (different e.g. for R-GCN)\n sampler = 'default'\n\n #: The batch size for use when testing training procedures\n train_batch_size = 400\n\n #: The number of epochs to train the model\n train_num_epochs = 2\n\n #: A random number generator from torch\n generator: torch.Generator\n\n #: The number of parameters which receive a constant (i.e. non-randomized)\n # initialization\n num_constant_init: int = 0\n\n def setUp(self) -> None:\n \"\"\"Set up the test case with a triples factory and model.\"\"\"\n _, self.generator, _ = set_random_seed(42)\n\n dataset = Nations(create_inverse_triples=self.create_inverse_triples)\n self.factory = dataset.training\n self.model = self.model_cls(\n self.factory,\n embedding_dim=self.embedding_dim,\n **(self.model_kwargs or {}),\n ).to_device_()\n\n def test_get_grad_parameters(self):\n \"\"\"Test the model's ``get_grad_params()`` method.\"\"\"\n # assert there is at least one trainable parameter\n assert len(list(self.model.get_grad_params())) > 0\n\n # Check that all the parameters actually require a gradient\n for parameter in self.model.get_grad_params():\n assert parameter.requires_grad\n\n # Try to initialize an optimizer\n optimizer = SGD(params=self.model.get_grad_params(), lr=1.0)\n assert optimizer is not None\n\n def test_reset_parameters_(self):\n \"\"\"Test :func:`Model.reset_parameters_`.\"\"\"\n # get model parameters\n params = list(self.model.parameters())\n old_content = {\n id(p): p.data.detach().clone()\n for p in params\n }\n\n # re-initialize\n self.model.reset_parameters_()\n\n # check that the operation works in-place\n new_params = list(self.model.parameters())\n assert set(id(np) for np in new_params) == set(id(p) for p in params)\n\n # check that the parameters where modified\n num_equal_weights_after_re_init = sum(\n 1\n for np in new_params\n if (np.data == old_content[id(np)]).all()\n )\n assert num_equal_weights_after_re_init == self.num_constant_init, (\n num_equal_weights_after_re_init, self.num_constant_init,\n )\n\n def _check_scores(self, batch, scores) -> None:\n \"\"\"Check the scores produced by a forward function.\"\"\"\n # check for finite values by default\n self.assertTrue(torch.all(torch.isfinite(scores)).item(), f'Some scores were not finite:\\n{scores}')\n\n # check whether a gradient can be back-propgated\n scores.mean().backward()\n\n def test_save(self) -> None:\n \"\"\"Test that the model can be saved properly.\"\"\"\n with tempfile.TemporaryDirectory() as temp_directory:\n torch.save(self.model, os.path.join(temp_directory, 'model.pickle'))\n\n def test_score_hrt(self) -> None:\n \"\"\"Test the model's ``score_hrt()`` function.\"\"\"\n batch = self.factory.mapped_triples[:self.batch_size, :].to(self.model.device)\n try:\n scores = self.model.score_hrt(batch)\n except RuntimeError as e:\n if str(e) == 'fft: ATen not compiled with MKL support':\n self.skipTest(str(e))\n else:\n raise e\n assert scores.shape == (self.batch_size, 1)\n self._check_scores(batch, scores)\n\n def test_score_t(self) -> None:\n \"\"\"Test the model's ``score_t()`` function.\"\"\"\n batch = self.factory.mapped_triples[:self.batch_size, :2].to(self.model.device)\n # assert batch comprises (head, relation) pairs\n assert batch.shape == (self.batch_size, 2)\n assert (batch[:, 0] < self.factory.num_entities).all()\n assert (batch[:, 1] < self.factory.num_relations).all()\n try:\n scores = self.model.score_t(batch)\n except NotImplementedError:\n self.fail(msg='Score_o not yet implemented')\n except RuntimeError as e:\n if str(e) == 'fft: ATen not compiled with MKL support':\n self.skipTest(str(e))\n else:\n raise e\n assert scores.shape == (self.batch_size, self.model.num_entities)\n self._check_scores(batch, scores)\n\n def test_score_h(self) -> None:\n \"\"\"Test the model's ``score_h()`` function.\"\"\"\n batch = self.factory.mapped_triples[:self.batch_size, 1:].to(self.model.device)\n # assert batch comprises (relation, tail) pairs\n assert batch.shape == (self.batch_size, 2)\n assert (batch[:, 0] < self.factory.num_relations).all()\n assert (batch[:, 1] < self.factory.num_entities).all()\n try:\n scores = self.model.score_h(batch)\n except NotImplementedError:\n self.fail(msg='Score_s not yet implemented')\n except RuntimeError as e:\n if str(e) == 'fft: ATen not compiled with MKL support':\n self.skipTest(str(e))\n else:\n raise e\n assert scores.shape == (self.batch_size, self.model.num_entities)\n self._check_scores(batch, scores)\n\n @pytest.mark.slow\n def test_train_slcwa(self) -> None:\n \"\"\"Test that sLCWA training does not fail.\"\"\"\n loop = SLCWATrainingLoop(\n model=self.model,\n optimizer=Adagrad(params=self.model.get_grad_params(), lr=0.001),\n **(self.training_loop_kwargs or {}),\n )\n losses = self._safe_train_loop(\n loop,\n num_epochs=self.train_num_epochs,\n batch_size=self.train_batch_size,\n sampler=self.sampler,\n )\n self.assertIsInstance(losses, list)\n\n @pytest.mark.slow\n def test_train_lcwa(self) -> None:\n \"\"\"Test that LCWA training does not fail.\"\"\"\n loop = LCWATrainingLoop(\n model=self.model,\n optimizer=Adagrad(params=self.model.get_grad_params(), lr=0.001),\n **(self.training_loop_kwargs or {}),\n )\n losses = self._safe_train_loop(\n loop,\n num_epochs=self.train_num_epochs,\n batch_size=self.train_batch_size,\n sampler='default',\n )\n self.assertIsInstance(losses, list)\n\n def _safe_train_loop(self, loop: TrainingLoop, num_epochs, batch_size, sampler):\n try:\n losses = loop.train(num_epochs=num_epochs, batch_size=batch_size, sampler=sampler, use_tqdm=False)\n except RuntimeError as e:\n if str(e) == 'fft: ATen not compiled with MKL support':\n self.skipTest(str(e))\n else:\n raise e\n else:\n return losses\n\n def test_save_load_model_state(self):\n \"\"\"Test whether a saved model state can be re-loaded.\"\"\"\n original_model = self.model_cls(\n self.factory,\n embedding_dim=self.embedding_dim,\n random_seed=42,\n **(self.model_kwargs or {}),\n ).to_device_()\n\n loaded_model = self.model_cls(\n self.factory,\n embedding_dim=self.embedding_dim,\n random_seed=21,\n **(self.model_kwargs or {}),\n ).to_device_()\n\n def _equal_embeddings(a: RepresentationModule, b: RepresentationModule) -> bool:\n \"\"\"Test whether two embeddings are equal.\"\"\"\n return (a(indices=None) == b(indices=None)).all()\n\n if isinstance(original_model, EntityEmbeddingModel):\n assert not _equal_embeddings(original_model.entity_embeddings, loaded_model.entity_embeddings)\n if isinstance(original_model, EntityRelationEmbeddingModel):\n assert not _equal_embeddings(original_model.relation_embeddings, loaded_model.relation_embeddings)\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n file_path = os.path.join(tmpdirname, 'test.pt')\n original_model.save_state(path=file_path)\n loaded_model.load_state(path=file_path)\n if isinstance(original_model, EntityEmbeddingModel):\n assert _equal_embeddings(original_model.entity_embeddings, loaded_model.entity_embeddings)\n if isinstance(original_model, EntityRelationEmbeddingModel):\n assert _equal_embeddings(original_model.relation_embeddings, loaded_model.relation_embeddings)\n\n @property\n def cli_extras(self):\n kwargs = self.model_kwargs or {}\n extras = [\n '--silent',\n ]\n for k, v in kwargs.items():\n extras.append('--' + k.replace('_', '-'))\n extras.append(str(v))\n\n # For the high/low memory test cases of NTN, SE, etc.\n if self.training_loop_kwargs and 'automatic_memory_optimization' in self.training_loop_kwargs:\n automatic_memory_optimization = self.training_loop_kwargs.get('automatic_memory_optimization')\n if automatic_memory_optimization is True:\n extras.append('--automatic-memory-optimization')\n elif automatic_memory_optimization is False:\n extras.append('--no-automatic-memory-optimization')\n # else, leave to default\n\n extras += [\n '--number-epochs', self.train_num_epochs,\n '--embedding-dim', self.embedding_dim,\n '--batch-size', self.train_batch_size,\n ]\n extras = [str(e) for e in extras]\n return extras\n\n @pytest.mark.slow\n def test_cli_training_nations(self):\n \"\"\"Test running the pipeline on almost all models with only training data.\"\"\"\n self._help_test_cli(['-t', NATIONS_TRAIN_PATH] + self.cli_extras)\n\n @pytest.mark.slow\n def test_cli_training_kinships(self):\n \"\"\"Test running the pipeline on almost all models with only training data.\"\"\"\n self._help_test_cli(['-t', KINSHIPS_TRAIN_PATH] + self.cli_extras)\n\n @pytest.mark.slow\n def test_cli_training_nations_testing(self):\n \"\"\"Test running the pipeline on almost all models with only training data.\"\"\"\n self._help_test_cli(['-t', NATIONS_TRAIN_PATH, '-q', NATIONS_TEST_PATH] + self.cli_extras)\n\n def _help_test_cli(self, args):\n \"\"\"Test running the pipeline on all models.\"\"\"\n if issubclass(self.model_cls, pykeen.models.RGCN):\n self.skipTest('There is a problem with non-reproducible unittest for R-GCN.')\n runner = CliRunner()\n cli = build_cli_from_cls(self.model_cls)\n # TODO: Catch HolE MKL error?\n result: Result = runner.invoke(cli, args)\n\n self.assertEqual(\n 0,\n result.exit_code,\n msg=f'''\nCommand\n=======\n$ pykeen train {self.model_cls.__name__.lower()} {' '.join(args)}\n\nOutput\n======\n{result.output}\n\nException\n=========\n{result.exc_info[1]}\n\nTraceback\n=========\n{''.join(traceback.format_tb(result.exc_info[2]))}\n ''',\n )\n\n def test_has_hpo_defaults(self):\n \"\"\"Test that there are defaults for HPO.\"\"\"\n try:\n d = self.model_cls.hpo_default\n except AttributeError:\n self.fail(msg=f'{self.model_cls.__name__} is missing hpo_default class attribute')\n else:\n self.assertIsInstance(d, dict)\n\n def test_post_parameter_update_regularizer(self):\n \"\"\"Test whether post_parameter_update resets the regularization term.\"\"\"\n # set regularizer term\n self.model.regularizer.regularization_term = None\n\n # call post_parameter_update\n self.model.post_parameter_update()\n\n # assert that the regularization term has been reset\n assert self.model.regularizer.regularization_term == torch.zeros(1, dtype=torch.float, device=self.model.device)\n\n def test_post_parameter_update(self):\n \"\"\"Test whether post_parameter_update correctly enforces model constraints.\"\"\"\n # do one optimization step\n opt = optim.SGD(params=self.model.parameters(), lr=1.)\n batch = self.factory.mapped_triples[:self.batch_size, :].to(self.model.device)\n scores = self.model.score_hrt(hrt_batch=batch)\n fake_loss = scores.mean()\n fake_loss.backward()\n opt.step()\n\n # call post_parameter_update\n self.model.post_parameter_update()\n\n # check model constraints\n self._check_constraints()\n\n def _check_constraints(self):\n \"\"\"Check model constraints.\"\"\"\n\n def test_score_h_with_score_hrt_equality(self) -> None:\n \"\"\"Test the equality of the model's ``score_h()`` and ``score_hrt()`` function.\"\"\"\n batch = self.factory.mapped_triples[:self.batch_size, 1:].to(self.model.device)\n self.model.eval()\n # assert batch comprises (relation, tail) pairs\n assert batch.shape == (self.batch_size, 2)\n assert (batch[:, 0] < self.factory.num_relations).all()\n assert (batch[:, 1] < self.factory.num_entities).all()\n try:\n scores_h = self.model.score_h(batch)\n scores_hrt = super(self.model.__class__, self.model).score_h(batch)\n except NotImplementedError:\n self.fail(msg='Score_h not yet implemented')\n except RuntimeError as e:\n if str(e) == 'fft: ATen not compiled with MKL support':\n self.skipTest(str(e))\n else:\n raise e\n\n assert torch.allclose(scores_h, scores_hrt, atol=1e-06)\n\n def test_score_r_with_score_hrt_equality(self) -> None:\n \"\"\"Test the equality of the model's ``score_r()`` and ``score_hrt()`` function.\"\"\"\n batch = self.factory.mapped_triples[:self.batch_size, [0, 2]].to(self.model.device)\n self.model.eval()\n # assert batch comprises (relation, tail) pairs\n assert batch.shape == (self.batch_size, 2)\n assert (batch[:, 0] < self.factory.num_entities).all()\n assert (batch[:, 1] < self.factory.num_entities).all()\n try:\n scores_r = self.model.score_r(batch)\n scores_hrt = super(self.model.__class__, self.model).score_r(batch)\n except NotImplementedError:\n self.fail(msg='Score_h not yet implemented')\n except RuntimeError as e:\n if str(e) == 'fft: ATen not compiled with MKL support':\n self.skipTest(str(e))\n else:\n raise e\n\n assert torch.allclose(scores_r, scores_hrt, atol=1e-06)\n\n def test_score_t_with_score_hrt_equality(self) -> None:\n \"\"\"Test the equality of the model's ``score_t()`` and ``score_hrt()`` function.\"\"\"\n batch = self.factory.mapped_triples[:self.batch_size, :-1].to(self.model.device)\n self.model.eval()\n # assert batch comprises (relation, tail) pairs\n assert batch.shape == (self.batch_size, 2)\n assert (batch[:, 0] < self.factory.num_entities).all()\n assert (batch[:, 1] < self.factory.num_relations).all()\n try:\n scores_t = self.model.score_t(batch)\n scores_hrt = super(self.model.__class__, self.model).score_t(batch)\n except NotImplementedError:\n self.fail(msg='Score_h not yet implemented')\n except RuntimeError as e:\n if str(e) == 'fft: ATen not compiled with MKL support':\n self.skipTest(str(e))\n else:\n raise e\n\n assert torch.allclose(scores_t, scores_hrt, atol=1e-06)\n\n def test_reset_parameters_constructor_call(self):\n \"\"\"Tests whether reset_parameters is called in the constructor.\"\"\"\n with patch.object(self.model_cls, 'reset_parameters_', return_value=None) as mock_method:\n try:\n self.model_cls(\n triples_factory=self.factory,\n embedding_dim=self.embedding_dim,\n **(self.model_kwargs or {}),\n )\n except TypeError as error:\n assert error.args == (\"'NoneType' object is not callable\",)\n mock_method.assert_called_once()\n\n def test_custom_representations(self):\n \"\"\"Tests whether we can provide custom representations.\"\"\"\n if isinstance(self.model, EntityEmbeddingModel):\n old_embeddings = self.model.entity_embeddings\n self.model.entity_embeddings = _CustomRepresentations(\n num_entities=self.factory.num_entities,\n embedding_dim=old_embeddings.embedding_dim,\n )\n # call some functions\n self.model.reset_parameters_()\n self.test_score_hrt()\n self.test_score_t()\n # reset to old state\n self.model.entity_embeddings = old_embeddings\n elif isinstance(self.model, EntityRelationEmbeddingModel):\n old_embeddings = self.model.relation_embeddings\n self.model.relation_embeddings = _CustomRepresentations(\n num_entities=self.factory.num_relations,\n embedding_dim=old_embeddings.embedding_dim,\n )\n # call some functions\n self.model.reset_parameters_()\n self.test_score_hrt()\n self.test_score_t()\n # reset to old state\n self.model.relation_embeddings = old_embeddings\n else:\n self.skipTest(f'Not testing custom representations for model: {self.model.__class__.__name__}')\n\n\nclass _DistanceModelTestCase(_ModelTestCase):\n \"\"\"A test case for distance-based models.\"\"\"\n\n def _check_scores(self, batch, scores) -> None:\n super()._check_scores(batch=batch, scores=scores)\n # Distance-based model\n assert (scores <= 0.0).all()\n\n\nclass TestComplex(_ModelTestCase, unittest.TestCase):\n \"\"\"Test the ComplEx model.\"\"\"\n\n model_cls = pykeen.models.ComplEx\n\n\nclass TestConvE(_ModelTestCase, unittest.TestCase):\n \"\"\"Test the ConvE model.\"\"\"\n\n model_cls = pykeen.models.ConvE\n embedding_dim = 12\n create_inverse_triples = True\n model_kwargs = {\n 'output_channels': 2,\n 'embedding_height': 3,\n 'embedding_width': 4,\n }\n # 3x batch norm: bias + scale --> 6\n # entity specific bias --> 1\n # ==================================\n # 7\n num_constant_init = 7\n\n\nclass TestConvKB(_ModelTestCase, unittest.TestCase):\n \"\"\"Test the ConvKB model.\"\"\"\n\n model_cls = pykeen.models.ConvKB\n model_kwargs = {\n 'num_filters': 2,\n }\n # two bias terms, one conv-filter\n num_constant_init = 3\n\n\nclass TestDistMult(_ModelTestCase, unittest.TestCase):\n \"\"\"Test the DistMult model.\"\"\"\n\n model_cls = pykeen.models.DistMult\n\n def _check_constraints(self):\n \"\"\"Check model constraints.\n\n Entity embeddings have to have unit L2 norm.\n \"\"\"\n entity_norms = self.model.entity_embeddings(indices=None).norm(p=2, dim=-1)\n assert torch.allclose(entity_norms, torch.ones_like(entity_norms))\n\n def _test_score_all_triples(self, k: Optional[int], batch_size: int = 16):\n \"\"\"Test score_all_triples.\n\n :param k: The number of triples to return. Set to None, to keep all.\n :param batch_size: The batch size to use for calculating scores.\n \"\"\"\n top_triples, top_scores = self.model.score_all_triples(k=k, batch_size=batch_size, return_tensors=True)\n\n # check type\n assert torch.is_tensor(top_triples)\n assert torch.is_tensor(top_scores)\n assert top_triples.dtype == torch.long\n assert top_scores.dtype == torch.float32\n\n # check shape\n actual_k, n_cols = top_triples.shape\n assert n_cols == 3\n if k is None:\n assert actual_k == self.factory.num_entities ** 2 * self.factory.num_relations\n else:\n assert actual_k == min(k, self.factory.num_triples)\n assert top_scores.shape == (actual_k,)\n\n # check ID ranges\n assert (top_triples >= 0).all()\n assert top_triples[:, [0, 2]].max() < self.model.num_entities\n assert top_triples[:, 1].max() < self.model.num_relations\n\n def test_score_all_triples(self):\n \"\"\"Test score_all_triples with a large batch size.\"\"\"\n # this is only done in one of the models\n self._test_score_all_triples(k=15, batch_size=16)\n\n def test_score_all_triples_singleton_batch(self):\n \"\"\"Test score_all_triples with a batch size of 1.\"\"\"\n self._test_score_all_triples(k=15, batch_size=1)\n\n def test_score_all_triples_large_batch(self):\n \"\"\"Test score_all_triples with a batch size larger than k.\"\"\"\n self._test_score_all_triples(k=10, batch_size=16)\n\n def test_score_all_triples_keep_all(self):\n \"\"\"Test score_all_triples with k=None.\"\"\"\n # this is only done in one of the models\n self._test_score_all_triples(k=None)\n\n\nclass TestERMLP(_ModelTestCase, unittest.TestCase):\n \"\"\"Test the ERMLP model.\"\"\"\n\n model_cls = pykeen.models.ERMLP\n model_kwargs = {\n 'hidden_dim': 4,\n }\n # Two linear layer biases\n num_constant_init = 2\n\n\nclass TestERMLPE(_ModelTestCase, unittest.TestCase):\n \"\"\"Test the extended ERMLP model.\"\"\"\n\n model_cls = pykeen.models.ERMLPE\n model_kwargs = {\n 'hidden_dim': 4,\n }\n # Two BN layers, bias & scale\n num_constant_init = 4\n\n\nclass TestHolE(_ModelTestCase, unittest.TestCase):\n \"\"\"Test the HolE model.\"\"\"\n\n model_cls = pykeen.models.HolE\n\n def _check_constraints(self):\n \"\"\"Check model constraints.\n\n Entity embeddings have to have at most unit L2 norm.\n \"\"\"\n assert all_in_bounds(self.model.entity_embeddings(indices=None).norm(p=2, dim=-1), high=1., a_tol=_EPSILON)\n\n\nclass _TestKG2E(_ModelTestCase):\n \"\"\"General tests for the KG2E model.\"\"\"\n\n model_cls = pykeen.models.KG2E\n\n def _check_constraints(self):\n \"\"\"Check model constraints.\n\n * Entity and relation embeddings have to have at most unit L2 norm.\n * Covariances have to have values between c_min and c_max\n \"\"\"\n for embedding in (self.model.entity_embeddings, self.model.relation_embeddings):\n assert all_in_bounds(embedding(indices=None).norm(p=2, dim=-1), high=1., a_tol=_EPSILON)\n for cov in (self.model.entity_covariances, self.model.relation_covariances):\n assert all_in_bounds(cov(indices=None), low=self.model.c_min, high=self.model.c_max)\n\n\nclass TestKG2EWithKL(_TestKG2E, unittest.TestCase):\n \"\"\"Test the KG2E model with KL similarity.\"\"\"\n\n model_kwargs = {\n 'dist_similarity': 'KL',\n }\n\n\nclass TestKG2EWithEL(_TestKG2E, unittest.TestCase):\n \"\"\"Test the KG2E model with EL similarity.\"\"\"\n\n model_kwargs = {\n 'dist_similarity': 'EL',\n }\n\n\nclass _BaseNTNTest(_ModelTestCase, unittest.TestCase):\n \"\"\"Test the NTN model.\"\"\"\n\n model_cls = pykeen.models.NTN\n\n def test_can_slice(self):\n \"\"\"Test that the slicing properties are calculated correctly.\"\"\"\n self.assertTrue(self.model.can_slice_h)\n self.assertFalse(self.model.can_slice_r)\n self.assertTrue(self.model.can_slice_t)\n\n\nclass TestNTNLowMemory(_BaseNTNTest):\n \"\"\"Test the NTN model with automatic memory optimization.\"\"\"\n\n model_kwargs = {\n 'num_slices': 2,\n }\n\n training_loop_kwargs = {\n 'automatic_memory_optimization': True,\n }\n\n\nclass TestNTNHighMemory(_BaseNTNTest):\n \"\"\"Test the NTN model without automatic memory optimization.\"\"\"\n\n model_kwargs = {\n 'num_slices': 2,\n }\n\n training_loop_kwargs = {\n 'automatic_memory_optimization': False,\n }\n\n\nclass TestProjE(_ModelTestCase, unittest.TestCase):\n \"\"\"Test the ProjE model.\"\"\"\n\n model_cls = pykeen.models.ProjE\n\n\nclass TestRESCAL(_ModelTestCase, unittest.TestCase):\n \"\"\"Test the RESCAL model.\"\"\"\n\n model_cls = pykeen.models.RESCAL\n\n\nclass _TestRGCN(_ModelTestCase):\n \"\"\"Test the R-GCN model.\"\"\"\n\n model_cls = pykeen.models.RGCN\n sampler = 'schlichtkrull'\n\n def _check_constraints(self):\n \"\"\"Check model constraints.\n\n Enriched embeddings have to be reset.\n \"\"\"\n assert self.model.entity_representations.enriched_embeddings is None\n\n\nclass TestRGCNBasis(_TestRGCN, unittest.TestCase):\n \"\"\"Test the R-GCN model.\"\"\"\n\n model_kwargs = {\n 'decomposition': 'basis',\n }\n #: one bias per layer\n num_constant_init = 2\n\n\nclass TestRGCNBlock(_TestRGCN, unittest.TestCase):\n \"\"\"Test the R-GCN model with block decomposition.\"\"\"\n\n embedding_dim = 6\n model_kwargs = {\n 'decomposition': 'block',\n 'num_bases_or_blocks': 3,\n 'edge_weighting': symmetric_edge_weights,\n 'use_batch_norm': True,\n }\n #: (scale & bias for BN) * layers\n num_constant_init = 4\n\n\nclass TestRotatE(_ModelTestCase, unittest.TestCase):\n \"\"\"Test the RotatE model.\"\"\"\n\n model_cls = pykeen.models.RotatE\n\n def _check_constraints(self):\n \"\"\"Check model constraints.\n\n Relation embeddings' entries have to have absolute value 1 (i.e. represent a rotation in complex plane)\n \"\"\"\n relation_abs = (\n self.model\n .relation_embeddings(indices=None)\n .view(self.factory.num_relations, -1, 2)\n .norm(p=2, dim=-1)\n )\n assert torch.allclose(relation_abs, torch.ones_like(relation_abs))\n\n\nclass TestSimplE(_ModelTestCase, unittest.TestCase):\n \"\"\"Test the SimplE model.\"\"\"\n\n model_cls = pykeen.models.SimplE\n\n\nclass _BaseTestSE(_ModelTestCase, unittest.TestCase):\n \"\"\"Test the Structured Embedding model.\"\"\"\n\n model_cls = pykeen.models.StructuredEmbedding\n\n def _check_constraints(self):\n \"\"\"Check model constraints.\n\n Entity embeddings have to have unit L2 norm.\n \"\"\"\n norms = self.model.entity_embeddings(indices=None).norm(p=2, dim=-1)\n assert torch.allclose(norms, torch.ones_like(norms))\n\n\nclass TestSELowMemory(_BaseTestSE):\n \"\"\"Tests SE with low memory.\"\"\"\n\n training_loop_kwargs = {\n 'automatic_memory_optimization': True,\n }\n\n\nclass TestSEHighMemory(_BaseTestSE):\n \"\"\"Tests SE with low memory.\"\"\"\n\n training_loop_kwargs = {\n 'automatic_memory_optimization': False,\n }\n\n\nclass TestTransD(_DistanceModelTestCase, unittest.TestCase):\n \"\"\"Test the TransD model.\"\"\"\n\n model_cls = pykeen.models.TransD\n model_kwargs = {\n 'relation_dim': 4,\n }\n\n def _check_constraints(self):\n \"\"\"Check model constraints.\n\n Entity and relation embeddings have to have at most unit L2 norm.\n \"\"\"\n for emb in (self.model.entity_embeddings, self.model.relation_embeddings):\n assert all_in_bounds(emb(indices=None).norm(p=2, dim=-1), high=1., a_tol=_EPSILON)\n\n def test_score_hrt_manual(self):\n \"\"\"Manually test interaction function of TransD.\"\"\"\n # entity embeddings\n weights = torch.as_tensor(data=[[2., 2.], [4., 4.]], dtype=torch.float)\n entity_embeddings = Embedding(\n num_embeddings=2,\n embedding_dim=2,\n )\n entity_embeddings._embeddings.weight.data.copy_(weights)\n self.model.entity_embeddings = entity_embeddings\n\n projection_weights = torch.as_tensor(data=[[3., 3.], [2., 2.]], dtype=torch.float)\n entity_projection_embeddings = Embedding(\n num_embeddings=2,\n embedding_dim=2,\n )\n entity_projection_embeddings._embeddings.weight.data.copy_(projection_weights)\n self.model.entity_projections = entity_projection_embeddings\n\n # relation embeddings\n relation_weights = torch.as_tensor(data=[[4.], [4.]], dtype=torch.float)\n relation_embeddings = Embedding(\n num_embeddings=2,\n embedding_dim=1,\n )\n relation_embeddings._embeddings.weight.data.copy_(relation_weights)\n self.model.relation_embeddings = relation_embeddings\n\n relation_projection_weights = torch.as_tensor(data=[[5.], [3.]], dtype=torch.float)\n relation_projection_embeddings = Embedding(\n num_embeddings=2,\n embedding_dim=1,\n )\n relation_projection_embeddings._embeddings.weight.data.copy_(relation_projection_weights)\n self.model.relation_projections = relation_projection_embeddings\n\n # Compute Scores\n batch = torch.as_tensor(data=[[0, 0, 0], [0, 0, 1]], dtype=torch.long)\n scores = self.model.score_hrt(hrt_batch=batch)\n self.assertEqual(scores.shape[0], 2)\n self.assertEqual(scores.shape[1], 1)\n first_score = scores[0].item()\n self.assertAlmostEqual(first_score, -16, delta=0.01)\n\n # Use different dimension for relation embedding: relation_dim > entity_dim\n # relation embeddings\n relation_weights = torch.as_tensor(data=[[3., 3., 3.], [3., 3., 3.]], dtype=torch.float)\n relation_embeddings = Embedding(\n num_embeddings=2,\n embedding_dim=3,\n )\n relation_embeddings._embeddings.weight.data.copy_(relation_weights)\n self.model.relation_embeddings = relation_embeddings\n\n relation_projection_weights = torch.as_tensor(data=[[4., 4., 4.], [4., 4., 4.]], dtype=torch.float)\n relation_projection_embeddings = Embedding(\n num_embeddings=2,\n embedding_dim=3,\n )\n relation_projection_embeddings._embeddings.weight.data.copy_(relation_projection_weights)\n self.model.relation_projections = relation_projection_embeddings\n\n # Compute Scores\n batch = torch.as_tensor(data=[[0, 0, 0]], dtype=torch.long)\n scores = self.model.score_hrt(hrt_batch=batch)\n self.assertAlmostEqual(scores.item(), -27, delta=0.01)\n\n batch = torch.as_tensor(data=[[0, 0, 0], [0, 0, 0]], dtype=torch.long)\n scores = self.model.score_hrt(hrt_batch=batch)\n self.assertEqual(scores.shape[0], 2)\n self.assertEqual(scores.shape[1], 1)\n first_score = scores[0].item()\n second_score = scores[1].item()\n self.assertAlmostEqual(first_score, -27, delta=0.01)\n self.assertAlmostEqual(second_score, -27, delta=0.01)\n\n # Use different dimension for relation embedding: relation_dim < entity_dim\n # entity embeddings\n weights = torch.as_tensor(data=[[1., 1., 1.], [1., 1., 1.]], dtype=torch.float)\n entity_embeddings = Embedding(\n num_embeddings=2,\n embedding_dim=3,\n )\n entity_embeddings._embeddings.weight.data.copy_(weights)\n self.model.entity_embeddings = entity_embeddings\n\n projection_weights = torch.as_tensor(data=[[2., 2., 2.], [2., 2., 2.]], dtype=torch.float)\n entity_projection_embeddings = Embedding(\n num_embeddings=2,\n embedding_dim=3,\n )\n entity_projection_embeddings._embeddings.weight.data.copy_(projection_weights)\n self.model.entity_projections = entity_projection_embeddings\n\n # relation embeddings\n relation_weights = torch.as_tensor(data=[[3., 3.], [3., 3.]], dtype=torch.float)\n relation_embeddings = Embedding(\n num_embeddings=2,\n embedding_dim=2,\n )\n relation_embeddings._embeddings.weight.data.copy_(relation_weights)\n self.model.relation_embeddings = relation_embeddings\n\n relation_projection_weights = torch.as_tensor(data=[[4., 4.], [4., 4.]], dtype=torch.float)\n relation_projection_embeddings = Embedding(\n num_embeddings=2,\n embedding_dim=2,\n )\n relation_projection_embeddings._embeddings.weight.data.copy_(relation_projection_weights)\n self.model.relation_projections = relation_projection_embeddings\n\n # Compute Scores\n batch = torch.as_tensor(data=[[0, 0, 0], [0, 0, 0]], dtype=torch.long)\n scores = self.model.score_hrt(hrt_batch=batch)\n self.assertEqual(scores.shape[0], 2)\n self.assertEqual(scores.shape[1], 1)\n first_score = scores[0].item()\n second_score = scores[1].item()\n self.assertAlmostEqual(first_score, -18, delta=0.01)\n self.assertAlmostEqual(second_score, -18, delta=0.01)\n\n def test_project_entity(self):\n \"\"\"Test _project_entity.\"\"\"\n # random entity embeddings & projections\n e = torch.rand(1, self.model.num_entities, self.embedding_dim, generator=self.generator)\n e = clamp_norm(e, maxnorm=1, p=2, dim=-1)\n e_p = torch.rand(1, self.model.num_entities, self.embedding_dim, generator=self.generator)\n\n # random relation embeddings & projections\n r = torch.rand(self.batch_size, 1, self.model.relation_dim, generator=self.generator)\n r = clamp_norm(r, maxnorm=1, p=2, dim=-1)\n r_p = torch.rand(self.batch_size, 1, self.model.relation_dim, generator=self.generator)\n\n # project\n e_bot = _project_entity(e=e, e_p=e_p, r=r, r_p=r_p)\n\n # check shape:\n assert e_bot.shape == (self.batch_size, self.model.num_entities, self.model.relation_dim)\n\n # check normalization\n assert (torch.norm(e_bot, dim=-1, p=2) <= 1.0 + 1.0e-06).all()\n\n\nclass TestTransE(_DistanceModelTestCase, unittest.TestCase):\n \"\"\"Test the TransE model.\"\"\"\n\n model_cls = pykeen.models.TransE\n\n def _check_constraints(self):\n \"\"\"Check model constraints.\n\n Entity embeddings have to have unit L2 norm.\n \"\"\"\n entity_norms = self.model.entity_embeddings(indices=None).norm(p=2, dim=-1)\n assert torch.allclose(entity_norms, torch.ones_like(entity_norms))\n\n\nclass TestTransH(_DistanceModelTestCase, unittest.TestCase):\n \"\"\"Test the TransH model.\"\"\"\n\n model_cls = pykeen.models.TransH\n\n def _check_constraints(self):\n \"\"\"Check model constraints.\n\n Entity embeddings have to have unit L2 norm.\n \"\"\"\n entity_norms = self.model.normal_vector_embeddings(indices=None).norm(p=2, dim=-1)\n assert torch.allclose(entity_norms, torch.ones_like(entity_norms))\n\n\nclass TestTransR(_DistanceModelTestCase, unittest.TestCase):\n \"\"\"Test the TransR model.\"\"\"\n\n model_cls = pykeen.models.TransR\n model_kwargs = {\n 'relation_dim': 4,\n }\n\n def test_score_hrt_manual(self):\n \"\"\"Manually test interaction function of TransR.\"\"\"\n # entity embeddings\n weights = torch.as_tensor(data=[[2., 2.], [3., 3.]], dtype=torch.float)\n entity_embeddings = Embedding(\n num_embeddings=2,\n embedding_dim=2,\n )\n entity_embeddings._embeddings.weight.data.copy_(weights)\n self.model.entity_embeddings = entity_embeddings\n\n # relation embeddings\n relation_weights = torch.as_tensor(data=[[4., 4], [5., 5.]], dtype=torch.float)\n relation_embeddings = Embedding(\n num_embeddings=2,\n embedding_dim=2,\n )\n relation_embeddings._embeddings.weight.data.copy_(relation_weights)\n self.model.relation_embeddings = relation_embeddings\n\n relation_projection_weights = torch.as_tensor(data=[[5., 5., 6., 6.], [7., 7., 8., 8.]], dtype=torch.float)\n relation_projection_embeddings = Embedding(\n num_embeddings=2,\n embedding_dim=4,\n )\n relation_projection_embeddings._embeddings.weight.data.copy_(relation_projection_weights)\n self.model.relation_projections = relation_projection_embeddings\n\n # Compute Scores\n batch = torch.as_tensor(data=[[0, 0, 0], [0, 0, 1]], dtype=torch.long)\n scores = self.model.score_hrt(hrt_batch=batch)\n self.assertEqual(scores.shape[0], 2)\n self.assertEqual(scores.shape[1], 1)\n first_score = scores[0].item()\n # second_score = scores[1].item()\n self.assertAlmostEqual(first_score, -32, delta=0.01)\n\n def _check_constraints(self):\n \"\"\"Check model constraints.\n\n Entity and relation embeddings have to have at most unit L2 norm.\n \"\"\"\n for emb in (self.model.entity_embeddings, self.model.relation_embeddings):\n assert all_in_bounds(emb(indices=None).norm(p=2, dim=-1), high=1., a_tol=1.0e-06)\n\n\nclass TestTuckEr(_ModelTestCase, unittest.TestCase):\n \"\"\"Test the TuckEr model.\"\"\"\n\n model_cls = pykeen.models.TuckER\n model_kwargs = {\n 'relation_dim': 4,\n }\n #: 2xBN (bias & scale)\n num_constant_init = 4\n\n\nclass TestUM(_DistanceModelTestCase, unittest.TestCase):\n \"\"\"Test the Unstructured Model.\"\"\"\n\n model_cls = pykeen.models.UnstructuredModel\n\n\nclass TestTesting(unittest.TestCase):\n \"\"\"Yo dawg, I heard you like testing, so I wrote a test to test the tests so you can test while you're testing.\"\"\"\n\n def test_testing(self):\n \"\"\"Check that there's a test for all models.\n\n For now, this is excluding multimodel models. Not sure how to test those yet.\n \"\"\"\n model_names = {\n cls.__name__\n for cls in pykeen.models.models.values()\n }\n model_names -= SKIP_MODULES\n\n tested_model_names = {\n value.model_cls.__name__\n for name, value in globals().items()\n if (\n isinstance(value, type)\n and issubclass(value, _ModelTestCase)\n and not name.startswith('_')\n and not issubclass(value.model_cls, MultimodalModel)\n )\n }\n tested_model_names -= SKIP_MODULES\n\n self.assertEqual(model_names, tested_model_names, msg='Some models have not been tested')\n\n def test_importing(self):\n \"\"\"Test that all models are available from :mod:`pykeen.models`.\"\"\"\n models_path = os.path.abspath(os.path.dirname(pykeen.models.__file__))\n\n model_names = set()\n for directory, _, filenames in os.walk(models_path):\n for filename in filenames:\n if not filename.endswith('.py'):\n continue\n\n path = os.path.join(directory, filename)\n relpath = os.path.relpath(path, models_path)\n if relpath.endswith('__init__.py'):\n continue\n\n import_path = 'pykeen.models.' + relpath[:-len('.py')].replace(os.sep, '.')\n module = importlib.import_module(import_path)\n\n for name in dir(module):\n value = getattr(module, name)\n if (\n isinstance(value, type)\n and issubclass(value, Model)\n ):\n model_names.add(value.__name__)\n\n star_model_names = set(pykeen.models.__all__) - SKIP_MODULES\n model_names -= SKIP_MODULES\n\n self.assertEqual(model_names, star_model_names, msg='Forgot to add some imports')\n\n def test_models_have_experiments(self):\n \"\"\"Test that each model has an experiment folder in :mod:`pykeen.experiments`.\"\"\"\n experiments_path = os.path.abspath(os.path.dirname(pykeen.experiments.__file__))\n experiment_blacklist = {\n 'DistMultLiteral', # FIXME\n 'ComplExLiteral', # FIXME\n 'UnstructuredModel',\n 'StructuredEmbedding',\n 'RESCAL',\n 'NTN',\n 'ERMLP',\n 'ProjE', # FIXME\n 'ERMLPE', # FIXME\n }\n model_names = set(pykeen.models.__all__) - SKIP_MODULES - experiment_blacklist\n missing = {\n model\n for model in model_names\n if not os.path.exists(os.path.join(experiments_path, model.lower()))\n }\n if missing:\n _s = '\\n'.join(f'- [ ] {model.lower()}' for model in sorted(missing))\n self.fail(f'Missing experimental configuration directories for the following models:\\n{_s}')\n\n\nclass MessageWeightingTests(unittest.TestCase):\n \"\"\"unittests for message weighting.\"\"\"\n\n #: The number of entities\n num_entities: int = 16\n\n #: The number of triples\n num_triples: int = 101\n\n def setUp(self) -> None:\n \"\"\"Initialize data for unittest.\"\"\"\n self.source, self.target = torch.randint(self.num_entities, size=(2, self.num_triples))\n\n def _test_message_weighting(self, weight_func):\n \"\"\"Perform common tests for message weighting.\"\"\"\n weights = weight_func(source=self.source, target=self.target)\n\n # check shape\n assert weights.shape == self.source.shape\n\n # check dtype\n assert weights.dtype == torch.float32\n\n # check finite values (e.g. due to division by zero)\n assert torch.isfinite(weights).all()\n\n # check non-negativity\n assert (weights >= 0.).all()\n\n def test_inverse_indegree_edge_weights(self):\n \"\"\"Test inverse_indegree_edge_weights.\"\"\"\n self._test_message_weighting(weight_func=inverse_indegree_edge_weights)\n\n def test_inverse_outdegree_edge_weights(self):\n \"\"\"Test inverse_outdegree_edge_weights.\"\"\"\n self._test_message_weighting(weight_func=inverse_outdegree_edge_weights)\n\n def test_symmetric_edge_weights(self):\n \"\"\"Test symmetric_edge_weights.\"\"\"\n self._test_message_weighting(weight_func=symmetric_edge_weights)\n\n\nclass TestModelUtilities(unittest.TestCase):\n \"\"\"Extra tests for utility functions.\"\"\"\n\n def test_abstract(self):\n \"\"\"Test that classes are checked as abstract properly.\"\"\"\n self.assertTrue(EntityEmbeddingModel._is_base_model)\n self.assertTrue(EntityRelationEmbeddingModel._is_base_model)\n self.assertTrue(MultimodalModel._is_base_model)\n for model_cls in _MODELS:\n self.assertFalse(\n model_cls._is_base_model,\n msg=f'{model_cls.__name__} should not be marked as a a base model',\n )\n\n def test_get_novelty_mask(self):\n \"\"\"Test `get_novelty_mask()`.\"\"\"\n num_triples = 7\n base = torch.arange(num_triples)\n mapped_triples = torch.stack([base, base, 3 * base], dim=-1)\n query_ids = torch.randperm(num_triples).numpy()[:num_triples // 2]\n exp_novel = query_ids != 0\n col = 2\n other_col_ids = numpy.asarray([0, 0])\n mask = get_novelty_mask(\n mapped_triples=mapped_triples,\n query_ids=query_ids,\n col=col,\n other_col_ids=other_col_ids,\n )\n assert mask.shape == query_ids.shape\n assert (mask == exp_novel).all()\n\n def test_extend_batch(self):\n \"\"\"Test `_extend_batch()`.\"\"\"\n batch = torch.tensor([[a, b] for a in range(3) for b in range(4)]).view(-1, 2)\n all_ids = [2 * i for i in range(5)]\n\n batch_size = batch.shape[0]\n num_choices = len(all_ids)\n\n for dim in range(3):\n h_ext_batch = _extend_batch(batch=batch, all_ids=all_ids, dim=dim)\n\n # check shape\n assert h_ext_batch.shape == (batch_size * num_choices, 3)\n\n # check content\n actual_content = set(tuple(map(int, hrt)) for hrt in h_ext_batch)\n exp_content = set()\n for i in all_ids:\n for b in batch:\n c = list(map(int, b))\n c.insert(dim, i)\n exp_content.add(tuple(c))\n\n assert actual_content == exp_content\n",
"# -*- coding: utf-8 -*-\n\n\"\"\"Load the OGB datasets.\n\nRun with python -m pykeen.datasets.ogb\n\"\"\"\n\nfrom typing import ClassVar, Optional\n\nimport numpy as np\n\nfrom .base import LazyDataset\nfrom ..triples import TriplesFactory\n\n__all__ = [\n 'OGBLoader',\n 'OGBBioKG',\n 'OGBWikiKG',\n]\n\n\nclass OGBLoader(LazyDataset):\n \"\"\"Load from the Open Graph Benchmark (OGB).\"\"\"\n\n #: The name of the dataset to download\n name: ClassVar[str]\n\n def __init__(self, cache_root: Optional[str] = None, create_inverse_triples: bool = False):\n self.cache_root = self._help_cache(cache_root)\n self.create_inverse_triples = create_inverse_triples\n\n def _load(self) -> None:\n try:\n from ogb.linkproppred import LinkPropPredDataset\n except ImportError as e:\n raise ModuleNotFoundError(\n f'Need to `pip install ogb` to use pykeen.datasets.{self.__class__.__name__}.',\n ) from e\n\n dataset = LinkPropPredDataset(name=self.name, root=self.cache_root)\n edge_split = dataset.get_edge_split()\n self._training = self._make_tf(edge_split[\"train\"])\n self._testing = self._make_tf(\n edge_split[\"test\"],\n entity_to_id=self._training.entity_to_id,\n relation_to_id=self._training.relation_to_id,\n )\n self._validation = self._make_tf(\n edge_split[\"valid\"],\n entity_to_id=self._training.entity_to_id,\n relation_to_id=self._training.relation_to_id,\n )\n\n def _loaded_validation(self) -> bool:\n return self._loaded\n\n def _load_validation(self) -> None:\n pass\n\n def _make_tf(self, x, entity_to_id=None, relation_to_id=None):\n triples = np.stack([x['head'], x['relation'], x['tail']], axis=1)\n\n # FIXME these are already identifiers\n triples = triples.astype(np.str)\n\n return TriplesFactory.from_labeled_triples(\n triples=triples,\n create_inverse_triples=self.create_inverse_triples,\n entity_to_id=entity_to_id,\n relation_to_id=relation_to_id,\n )\n\n\nclass OGBBioKG(OGBLoader):\n \"\"\"The OGB BioKG dataset.\n\n .. seealso:: https://ogb.stanford.edu/docs/linkprop/#ogbl-biokg\n \"\"\"\n\n name = 'ogbl-biokg'\n\n\nclass OGBWikiKG(OGBLoader):\n \"\"\"The OGB WikiKG dataset.\n\n .. seealso:: https://ogb.stanford.edu/docs/linkprop/#ogbl-wikikg\n \"\"\"\n\n name = 'ogbl-wikikg'\n\n\nif __name__ == '__main__':\n for _cls in [OGBBioKG, OGBWikiKG]:\n _cls().summarize()\n"
] |
[
[
"torch.norm",
"torch.randint",
"torch.zeros",
"numpy.asarray",
"torch.randperm",
"torch.is_tensor",
"torch.isfinite",
"torch.rand",
"torch.arange",
"torch.stack",
"torch.allclose",
"torch.ones_like",
"torch.as_tensor"
],
[
"numpy.stack"
]
] |
voidstrike/FPSG
|
[
"238b1de1402e72669e7df432ce1e7ab6efe4a6e9"
] |
[
"src/models/support_models.py"
] |
[
"import torch\nimport torch.nn as nn\nimport numpy as np\nimport torch.nn.functional as F\n\nclass AuxClassifier(nn.Module):\n def __init__(self, in_dim, out_dim, num_layer=3):\n super(AuxClassifier, self).__init__()\n self.fc1 = nn.Linear(in_dim, 512)\n self.fc2 = nn.Linear(512, 256)\n self.fc3 = nn.Linear(256, out_dim)\n\n self.dropout = nn.Dropout(p=.3)\n self.bn1 = nn.BatchNorm1d(512)\n self.bn2 = nn.BatchNorm1d(256)\n\n self._init_weight()\n\n def forward(self, x):\n x = F.relu(self.bn1(self.fc1(x)))\n x = F.relu(self.bn2(self.dropout(self.fc2(x))))\n x = self.fc3(x)\n return F.log_softmax(x, dim=1)\n # return x # logit\n\n def _init_weight(self,):\n nn.init.xavier_normal_(self.fc1.weight.data)\n nn.init.xavier_normal_(self.fc2.weight.data)\n nn.init.xavier_normal_(self.fc3.weight.data)\n\n\nclass FCMaskAlloacter(nn.Module):\n def __init__(self, img_dim, proto_dim):\n super(FCMaskAlloacter, self).__init__()\n self.fc1 = nn.Linear(img_dim + proto_dim, 256)\n self.fc2 = nn.Linear(256, 256)\n self.fc3 = nn.Linear(256, proto_dim)\n\n self.bn1 = nn.BatchNorm1d(256)\n self.bn2 = nn.BatchNorm1d(256)\n\n def forward(self, x):\n x = F.relu(self.bn1(self.fc1(x)))\n x = F.relu(self.bn2(self.fc2(x)))\n x = self.fc3(x)\n return F.sigmoid(x)\n # return F.softmax(x, dim=1)\n\n def _init_weight(self,):\n nn.init.xavier_normal_(self.fc1.weight.data)\n nn.init.xavier_normal_(self.fc2.weight.data)\n nn.init.xavier_normal_(self.fc3.weight.data)\n\nclass TransMaskAllocater(nn.Module):\n def __init__(self, img_dim, proto_dim, hidden_dim=256):\n super(TransMaskAllocater, self).__init__()\n self.fc_q = nn.Linear(img_dim, hidden_dim)\n self.fc_k = nn.Linear(proto_dim, hidden_dim)\n \n def forward(self, query, key, value):\n # Query -- Img -- 1 (or NP) * 512\n # Key -- PC -- 1 (or NP) * 1024\n # Value -- PC -- 1 (or NP) * 1024\n pass\n"
] |
[
[
"torch.nn.BatchNorm1d",
"torch.nn.Dropout",
"torch.nn.functional.log_softmax",
"torch.nn.init.xavier_normal_",
"torch.nn.Linear",
"torch.nn.functional.sigmoid"
]
] |
alexmasterdi/CoCosNet
|
[
"5d1e58eccca3cb67e1ae93e3719f425e7b8f0a67"
] |
[
"models/networks/architecture.py"
] |
[
"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nimport torch.nn.utils.spectral_norm as spectral_norm\nfrom models.networks.normalization import SPADE, equal_lr, SPADE_TwoPath\n\n\n# ResNet block that uses SPADE.\n# It differs from the ResNet block of pix2pixHD in that\n# it takes in the segmentation map as input, learns the skip connection if necessary,\n# and applies normalization first and then convolution.\n# This architecture seemed like a standard architecture for unconditional or\n# class-conditional GAN architecture using residual block.\n# The code was inspired from https://github.com/LMescheder/GAN_stability.\nclass SPADEResnetBlock(nn.Module):\n def __init__(self, fin, fout, opt, use_se=False, dilation=1):\n super().__init__()\n # Attributes\n self.learned_shortcut = (fin != fout)\n fmiddle = min(fin, fout)\n self.opt = opt\n self.pad_type = 'zero'\n self.use_se = use_se\n\n # create conv layers\n if self.pad_type != 'zero':\n self.pad = nn.ReflectionPad2d(dilation)\n self.conv_0 = nn.Conv2d(fin, fmiddle, kernel_size=3, padding=0, dilation=dilation)\n self.conv_1 = nn.Conv2d(fmiddle, fout, kernel_size=3, padding=0, dilation=dilation)\n else:\n self.conv_0 = nn.Conv2d(fin, fmiddle, kernel_size=3, padding=dilation, dilation=dilation)\n self.conv_1 = nn.Conv2d(fmiddle, fout, kernel_size=3, padding=dilation, dilation=dilation)\n if self.learned_shortcut:\n self.conv_s = nn.Conv2d(fin, fout, kernel_size=1, bias=False)\n\n # apply spectral norm if specified\n if 'spectral' in opt.norm_G:\n if opt.eqlr_sn:\n self.conv_0 = equal_lr(self.conv_0)\n self.conv_1 = equal_lr(self.conv_1)\n if self.learned_shortcut:\n self.conv_s = equal_lr(self.conv_s)\n else:\n self.conv_0 = spectral_norm(self.conv_0)\n self.conv_1 = spectral_norm(self.conv_1)\n if self.learned_shortcut:\n self.conv_s = spectral_norm(self.conv_s)\n\n # define normalization layers\n spade_config_str = opt.norm_G.replace('spectral', '')\n \n if 'spade_ic' in opt:\n ic = opt.spade_ic\n else:\n ic = 0 + (3 if 'warp' in opt.CBN_intype else 0) + (opt.semantic_nc if 'mask' in opt.CBN_intype else 0)\n self.norm_0 = SPADE(spade_config_str, fin, ic, PONO=opt.PONO, use_apex=opt.apex)\n self.norm_1 = SPADE(spade_config_str, fmiddle, ic, PONO=opt.PONO, use_apex=opt.apex)\n if self.learned_shortcut:\n self.norm_s = SPADE(spade_config_str, fin, ic, PONO=opt.PONO, use_apex=opt.apex)\n\n if use_se:\n self.se_layar = SELayer(fout)\n\n # note the resnet block with SPADE also takes in |seg|,\n # the semantic segmentation map as input\n def forward(self, x, seg1):\n x_s = self.shortcut(x, seg1)\n if self.pad_type != 'zero':\n dx = self.conv_0(self.pad(self.actvn(self.norm_0(x, seg1)))) # throw error with input data tensor's rank\n dx = self.conv_1(self.pad(self.actvn(self.norm_1(dx, seg1))))\n if self.use_se:\n dx = self.se_layar(dx)\n else:\n dx = self.conv_0(self.actvn(self.norm_0(x, seg1)))\n dx = self.conv_1(self.actvn(self.norm_1(dx, seg1)))\n if self.use_se:\n dx = self.se_layar(dx)\n \n out = x_s + dx\n\n return out\n\n def shortcut(self, x, seg1):\n if self.learned_shortcut:\n x_s = self.conv_s(self.norm_s(x, seg1))\n else:\n x_s = x\n return x_s\n\n def actvn(self, x):\n return F.leaky_relu(x, 2e-1)\n\nclass Attention(nn.Module):\n def __init__(self, ch, use_sn):\n super(Attention, self).__init__()\n # Channel multiplier\n self.ch = ch\n self.theta = nn.Conv2d(self.ch, self.ch // 8, kernel_size=1, padding=0, bias=False)\n self.phi = nn.Conv2d(self.ch, self.ch // 8, kernel_size=1, padding=0, bias=False)\n self.g = nn.Conv2d(self.ch, self.ch // 2, kernel_size=1, padding=0, bias=False)\n self.o = nn.Conv2d(self.ch // 2, self.ch, kernel_size=1, padding=0, bias=False)\n if use_sn:\n self.theta = spectral_norm(self.theta)\n self.phi = spectral_norm(self.phi)\n self.g = spectral_norm(self.g)\n self.o = spectral_norm(self.o)\n # Learnable gain parameter\n self.gamma = nn.Parameter(torch.tensor(0.), requires_grad=True)\n\n def forward(self, x, y=None):\n # Apply convs\n theta = self.theta(x)\n phi = F.max_pool2d(self.phi(x), [2,2])\n g = F.max_pool2d(self.g(x), [2,2]) \n # Perform reshapes\n theta = theta.view(-1, self. ch // 8, x.shape[2] * x.shape[3])\n phi = phi.view(-1, self. ch // 8, x.shape[2] * x.shape[3] // 4)\n g = g.view(-1, self. ch // 2, x.shape[2] * x.shape[3] // 4)\n # Matmul and softmax to get attention maps\n beta = F.softmax(torch.bmm(theta.transpose(1, 2), phi), -1)\n # Attention map times g path\n o = self.o(torch.bmm(g, beta.transpose(1,2)).view(-1, self.ch // 2, x.shape[2], x.shape[3]))\n return self.gamma * o + x\n\n# ResNet block used in pix2pixHD\n# We keep the same architecture as pix2pixHD.\nclass ResnetBlock(nn.Module):\n def __init__(self, dim, norm_layer, activation=nn.ReLU(False), kernel_size=3):\n super().__init__()\n\n pw = (kernel_size - 1) // 2\n self.conv_block = nn.Sequential(\n nn.ReflectionPad2d(pw),\n norm_layer(nn.Conv2d(dim, dim, kernel_size=kernel_size)),\n activation,\n nn.ReflectionPad2d(pw),\n norm_layer(nn.Conv2d(dim, dim, kernel_size=kernel_size))\n )\n\n def forward(self, x):\n y = self.conv_block(x)\n out = x + y\n return out\n\n\n# VGG architecter, used for the perceptual loss using a pretrained VGG network\nclass VGG19(torch.nn.Module):\n def __init__(self, requires_grad=False):\n super().__init__()\n vgg_pretrained_features = torchvision.models.vgg19(pretrained=True).features\n self.slice1 = torch.nn.Sequential()\n self.slice2 = torch.nn.Sequential()\n self.slice3 = torch.nn.Sequential()\n self.slice4 = torch.nn.Sequential()\n self.slice5 = torch.nn.Sequential()\n for x in range(2):\n self.slice1.add_module(str(x), vgg_pretrained_features[x]) #r11\n for x in range(2, 7):\n self.slice2.add_module(str(x), vgg_pretrained_features[x]) #r21\n for x in range(7, 12):\n self.slice3.add_module(str(x), vgg_pretrained_features[x]) #r31\n for x in range(12, 21):\n self.slice4.add_module(str(x), vgg_pretrained_features[x]) #r41\n for x in range(21, 30):\n self.slice5.add_module(str(x), vgg_pretrained_features[x]) #r51\n if not requires_grad:\n for param in self.parameters():\n param.requires_grad = False\n\n def forward(self, X):\n h_relu1 = self.slice1(X)\n h_relu2 = self.slice2(h_relu1)\n h_relu3 = self.slice3(h_relu2)\n h_relu4 = self.slice4(h_relu3)\n h_relu5 = self.slice5(h_relu4)\n out = [h_relu1, h_relu2, h_relu3, h_relu4, h_relu5]\n return out\n\nclass SELayer(nn.Module):\n def __init__(self, channel, reduction=16):\n super(SELayer, self).__init__()\n self.avg_pool = nn.AdaptiveAvgPool2d(1)\n self.fc = nn.Sequential(\n nn.Linear(channel, channel // reduction, bias=False),\n nn.ReLU(inplace=True),\n nn.Linear(channel // reduction, channel, bias=False),\n nn.Sigmoid()\n )\n\n def forward(self, x):\n b, c, _, _ = x.size()\n y = self.avg_pool(x).view(b, c)\n y = self.fc(y).view(b, c, 1, 1)\n return x * y.expand_as(x)\n"
] |
[
[
"torch.nn.Sequential",
"torch.nn.ReflectionPad2d",
"torch.nn.utils.spectral_norm",
"torch.nn.Conv2d",
"torch.tensor",
"torch.nn.Sigmoid",
"torch.nn.Linear",
"torch.nn.AdaptiveAvgPool2d",
"torch.nn.functional.leaky_relu",
"torch.nn.ReLU"
]
] |
kota7/kgschart
|
[
"a08a1ac37d351a9c999c0221ba3a35c28492f148"
] |
[
"kgschart/parser.py"
] |
[
"# -*- coding: utf-8 -*-\n\n\nfrom PIL import Image\nimport os\nimport sys\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom datetime import datetime\nfrom datetime import timedelta\n\nfrom .colors import BLACK, WHITE, BEIGE, GRAY, GREEN\nfrom .utils import rgb_dist, detect_consecutive_true, str_to_num_rank\nfrom .parts import Yaxis, Caption, Graph\n\n\n# on python3, we can multiply timedelta and float\n# we cannot do so on python2, so write a bit of code\nPY3 = (sys.version_info[0] == 3)\n\n\nclass KgsChart:\n\n # image: original image in RGB array \n # assumed to be of shape (nrow, ncol, 3)\n image = None\n\n # tbrl: 4-dim list of the indices of graph boundary\n # [top, bottom, right, left]\n # i.e. image[top:bottom][right:left] is the graph\n tblr = [0,0,0,0]\n\n\n # line_index: numpy array whose size equals the ncol\n # each element indicates the index of graph line\n # within the graph area\n line_index = np.empty(0)\n\n\n # graph, caption, yaxis: sub image class objects\n graph = None\n caption = None\n yaxis = None\n\n\n # horizontal and vertical range\n rank_range = () # e.g. (2k, 3d)\n time_range = () # e.g. (2013-04-03, 2014-05-12)\n\n # output data\n data = None\n\n\n def __init__(self, imagefile): \n self.image = np.asarray(Image.open(imagefile))\n self.tblr = self.detect_graph_area()\n \n im = self.image\n t,b,l,r = self.tblr\n\n if b-t > 0 and r-l > 0:\n self.graph = Graph(im[t:b, l:r])\n self.yaxis = Yaxis(im[:, 0:(l-1)]) \n self.caption = Caption(im[0:(t-1), l:r])\n\n \n def detect_graph_area(self):\n \"\"\"\n Identify three key areas within the image\n returns a 4-dim list of integers of graph boundary\n \"\"\"\n if self.image is None: return [0,0,0,0]\n\n im = self.image\n \n # strategy: find a box white \n thres_dist = 0.05\n\n # find white rows\n dist = rgb_dist(im[:, im.shape[1]//2], WHITE)\n white_rows = (dist < thres_dist)\n i1,i2 = detect_consecutive_true(white_rows)\n # if there is a graph, there must be two white rows\n if len(i1) != 2: return [0,0,0,0]\n top = i2[0]\n bottom = i1[1]\n\n # find white cols\n dist = rgb_dist(im[im.shape[0]//2], WHITE)\n white_cols = (dist < thres_dist)\n j1,j2 = detect_consecutive_true(white_cols)\n # if there is a graph, there must be two white rows\n if len(j1) != 2: return [0,0,0,0]\n left = j2[0]\n right = j1[1]\n\n return [top, bottom, left, right]\n\n \n\n def parse(self):\n if self.image is None: return\n\n if self.graph is None: return \n # obtain the line graph height\n self.line_index = self.graph.get_line_index()\n\n # obtain number of grid lines\n # this helps to detect y-axis labels\n ngrids = self.graph.get_num_grids()\n #print('num grids', ngrids)\n \n positions = None\n if ngrids is not None:\n top = self.tblr[0]\n bottom = self.tblr[1]\n step = (bottom-top)//(ngrids+1)\n positions = list(range(top, bottom+1, step)) \n #print('positions', positions)\n\n # obtain the rank range from yaxis\n self.set_rank_range(self.yaxis.get_rank_range(positions)) \n #print('rank range', self.rank_range)\n \n # obtain date-time range from caption\n self.set_time_range(self.caption.get_time_range()) \n #print('time range', self.time_range)\n\n # compile data\n self.data = self.make_data()\n\n def make_data(self):\n \"\"\"\n Compile and return data frame\n \"\"\"\n y = self.line_index\n n = len(y)\n if n == 0: \n # empty dataframe if line index is empty \n return pd.DataFrame(dict(time=[], rate=[]))\n if n == 1:\n # this won't happen for normal input \n # just write this so that the later computation\n # never raises error\n return pd.DataFrame(dict(time=[np.nan], rate=y))\n \n # scale y\n if len(self.rank_range) != 2:\n y = -y \n else:\n y1,y2 = [str_to_num_rank(r) for r in self.rank_range]\n if np.isnan(y1) or np.isnan(y2):\n y = -y\n else:\n z2 = 0\n z1 = self.tblr[1] - self.tblr[2]\n # (z1, z2) <-> (y1, y2)\n b = (y2-y1)/(z2-z1)\n a = y1-b*z1\n y = a + b*(y+0.5)\n \n # scale x\n #print(self.time_range)\n if len(self.time_range) != 2:\n x = np.arange(n)\n else:\n x1,x2 = self.time_range \n b = (x2-x1)/n \n if PY3:\n x = x1 + (np.arange(n)+0.5)*b\n else:\n x = np.array([x1 + timedelta(seconds=b.total_seconds()*(0.5+i)) for i in range(n)])\n\n return pd.DataFrame(dict(time=x, rate=y), columns=['time', 'rate'])\n \n def update_data(self):\n self.data = self.make_data()\n \n \n def extract_label_letters(self):\n if self.yaxis is None: return []\n return self.yaxis.extract_letters()\n\n def extract_caption_letters(self):\n if self.caption is None: return []\n return self.caption.extract_letters()\n\n\n # functions to set range for x and y axis\n # can be used for user specification as well\n def set_time_range(self, time_range):\n self.time_range = time_range\n \n def set_rank_range(self, rank_range):\n self.rank_range = rank_range\n\n \n # plot image and parts\n # mainly for debugging\n def plot_image(self):\n plt.subplot(221)\n plt.plot(1)\n \n if self.image is not None:\n plt.subplot(221)\n plt.imshow(self.image)\n if self.yaxis is not None:\n plt.subplot(222)\n self.yaxis.plot(False)\n if self.graph is not None:\n plt.subplot(223)\n self.graph.plot(False)\n if self.caption is not None:\n plt.subplot(224)\n self.caption.plot(False)\n plt.show()\n\n\n def plot_data(self, block=True):\n if self.data is None: \n plt.plot()\n plt.show()\n return\n plt.plot(self.data['time'], self.data['rate'])\n plt.grid()\n plt.show(block)\n\n\n\n\n\n\n"
] |
[
[
"matplotlib.pyplot.imshow",
"numpy.isnan",
"numpy.arange",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.show",
"numpy.empty"
]
] |
FullMetalNicky/FrontNetPorting
|
[
"8dc12f1c83ae770936101cfe815523dd7e95188b"
] |
[
"pulp/Calibrator.py"
] |
[
"#!/usr/bin/env python\n\n\nimport numpy as np\nimport cv2\nimport os\nfrom time import time\nimport sys, getopt\n\nheight = 244\nwidth = 324\npage_size = 4096\n\n\ndef read_from_pipe(pipein):\n\tremaining_size = height * width\n\t\n\tdata = []\n\twhile(remaining_size >= page_size):\n\t\toutput = os.read(pipein, page_size)\n\t\tremaining_size = remaining_size - len(output)\n\t\tdata.append(output)\n\n\tdata.append(os.read(pipein, max(0, remaining_size)))\n\tdata=''.join(data)\n\n\tif (len(data) < height*width):\n\t\t\tprint(\"Error, expecting {} bytes, received {}.\".format(height*width, len(data)))\n\t\t\treturn None\n\n\tdata = np.frombuffer(data, dtype=np.uint8)\n\n\treturn data\n\t\n\ndef main(argv):\n\n\tprint(argv[1])\n\tfolder_path = \"calibration/\"\n\tif ((int(argv[1]) == 0) or (int(argv[1]) == 2)):\n\t\tpipe_name = \"image_pipe\"\n\t\tif not os.path.exists(pipe_name):\n\t\t\tos.mkfifo(pipe_name)\n\n\t\tpipein = os.open(pipe_name, os.O_RDONLY)\n\t\tframe_id = 11\n\t\twhile (1):\n\t\t\tdata = read_from_pipe(pipein)\n\t\t\tif data is not None:\n\t\t\t\tcv_image = np.reshape(data, (height, width))\n\t\t\t\tcv2.imshow(\"Calibration\", cv_image)\n\t\t\t\tc = cv2.waitKey(10)\n\t\t\t\tif 'c' == chr(c & 255):\n\t\t\t\t\timg_name = folder_path + \"{}.jpg\".format(frame_id)\n\t\t\t\t\tframe_id = frame_id + 1\n\t\t\t\t\tcv2.imwrite(img_name, cv_image)\n\t\t\t\tif 'q' == chr(c & 255):\n\t\t\t\t\tbreak\n\n\t\tos.close(pipein)\n\tif ((int(argv[1]) == 1) or (int(argv[1]) == 2)):\n\t\tfiles = []\n\n\t\tfor r, d, f in os.walk(folder_path):\n\t\t\t\tfor file in f:\n\t\t\t\t if '.jpg' in file:\n\t\t\t\t files.append(os.path.join(r, file))\n\n\n\t\tcriteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)\n\t\tobjp = np.zeros((4*6,3), np.float32)\n\t\tobjp[:,:2] = np.mgrid[0:6,0:4].T.reshape(-1,2)\n\t\tobjpoints = [] \n\t\timgpoints = [] \n\t\tfor f in files:\n\t\t\timg = cv2.imread(f)\n\t\t\tgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n\t\t\tret, corners = cv2.findChessboardCorners(gray, (6,4),cv2.CALIB_CB_ADAPTIVE_THRESH + cv2.CALIB_CB_NORMALIZE_IMAGE)\n\n\t\t\tif ret == True:\n\t\t\t\tobjpoints.append(objp)\n\t\t\t\tcorners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)\n\t\t\t\timgpoints.append(corners2)\n\n\t\t\t\timg = cv2.drawChessboardCorners(img, (6,4), corners2,ret)\n\t\t\t\tcv2.imshow('img',img)\n\t\t\t\tcv2.waitKey(50)\n\t\tcv2.destroyAllWindows()\n\t\tret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)\n\t\th, w = img.shape[:2]\n\t\tfovx, fovy, focalLength, principalPoint, aspectRatio = cv2.calibrationMatrixValues(mtx, (w, h), 0.0036, 0.0036) \n\t\tprint(\"himax fovx {} fovy {}\".format(fovx, fovy))\n\t\t\n\t\tcv_file = cv2.FileStorage(\"calibration.yaml\", cv2.FILE_STORAGE_WRITE)\n\t\tcv_file.write(\"k\", mtx)\n\t\tcv_file.write(\"D\", dist)\n\t\tcv_file.write(\"size\", np.array([h, w]))\n\t\tcv_file.release()\n\n\nif __name__ == '__main__':\n main(sys.argv)\n"
] |
[
[
"numpy.reshape",
"numpy.frombuffer",
"numpy.array",
"numpy.zeros"
]
] |
ruiningTang/mmdetection
|
[
"100b0b5e0edddc45af0812b9f1474493c61671ef",
"100b0b5e0edddc45af0812b9f1474493c61671ef"
] |
[
"mmdet/models/dense_heads/gfocal_head.py",
"tools/feature_visualization.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom mmcv.cnn import ConvModule, Scale, bias_init_with_prob, normal_init\nfrom mmcv.runner import force_fp32\n\nfrom mmdet.core import (anchor_inside_flags, bbox2distance, bbox_overlaps,\n build_assigner, build_sampler, distance2bbox,\n images_to_levels, multi_apply, multiclass_nms,\n reduce_mean, unmap)\nfrom ..builder import HEADS, build_loss\nfrom .anchor_head import AnchorHead\n\n\nclass Integral(nn.Module):\n \"\"\"A fixed layer for calculating integral result from distribution.\n This layer calculates the target location by :math: `sum{P(y_i) * y_i}`,\n P(y_i) denotes the softmax vector that represents the discrete distribution\n y_i denotes the discrete set, usually {0, 1, 2, ..., reg_max}\n Args:\n reg_max (int): The maximal value of the discrete set. Default: 16. You\n may want to reset it according to your new dataset or related\n settings.\n \"\"\"\n\n def __init__(self, reg_max=16):\n super(Integral, self).__init__()\n self.reg_max = reg_max\n self.register_buffer('project',\n torch.linspace(0, self.reg_max, self.reg_max + 1))\n\n def forward(self, x):\n \"\"\"Forward feature from the regression head to get integral result of\n bounding box location.\n Args:\n x (Tensor): Features of the regression head, shape (N, 4*(n+1)),\n n is self.reg_max.\n Returns:\n x (Tensor): Integral result of box locations, i.e., distance\n offsets from the box center in four directions, shape (N, 4).\n \"\"\"\n x = F.softmax(x.reshape(-1, self.reg_max + 1), dim=1)\n x = F.linear(x, self.project.type_as(x)).reshape(-1, 4)\n return x\n\n\[email protected]_module()\nclass GFocalHead(AnchorHead):\n \"\"\"Generalized Focal Loss V2: Learning Reliable Localization Quality\n Estimation for Dense Object Detection.\n GFocal head structure is similar with GFL head, however GFocal uses\n the statistics of learned distribution to guide the \n localization quality estimation (LQE)\n Args:\n num_classes (int): Number of categories excluding the background\n category.\n in_channels (int): Number of channels in the input feature map.\n stacked_convs (int): Number of conv layers in cls and reg tower.\n Default: 4.\n conv_cfg (dict): dictionary to construct and config conv layer.\n Default: None.\n norm_cfg (dict): dictionary to construct and config norm layer.\n Default: dict(type='GN', num_groups=32, requires_grad=True).\n loss_qfl (dict): Config of Quality Focal Loss (QFL).\n reg_max (int): Max value of integral set :math: `{0, ..., reg_max}`\n in QFL setting. Default: 16.\n reg_topk (int): top-k statistics of distribution to guide LQE\n reg_channels (int): hidden layer unit to generate LQE\n Example:\n >>> self = GFocalHead(11, 7)\n >>> feats = [torch.rand(1, 7, s, s) for s in [4, 8, 16, 32, 64]]\n >>> cls_quality_score, bbox_pred = self.forward(feats)\n >>> assert len(cls_quality_score) == len(self.scales)\n \"\"\"\n\n def __init__(self,\n num_classes,\n in_channels,\n stacked_convs=4,\n conv_cfg=None,\n norm_cfg=dict(type='GN', num_groups=32, requires_grad=True),\n loss_dfl=dict(type='DistributionFocalLoss', loss_weight=0.25),\n reg_max=16,\n reg_topk=4,\n reg_channels=64,\n add_mean=True,\n **kwargs):\n self.stacked_convs = stacked_convs\n self.conv_cfg = conv_cfg\n self.norm_cfg = norm_cfg\n self.reg_max = reg_max\n self.reg_topk = reg_topk\n self.reg_channels = reg_channels\n self.add_mean = add_mean\n self.total_dim = reg_topk\n if add_mean:\n self.total_dim += 1\n print('total dim = ', self.total_dim * 4)\n\n super(GFocalHead, self).__init__(num_classes, in_channels, **kwargs)\n\n self.sampling = False\n if self.train_cfg:\n self.assigner = build_assigner(self.train_cfg.assigner)\n # SSD sampling=False so use PseudoSampler\n sampler_cfg = dict(type='PseudoSampler')\n self.sampler = build_sampler(sampler_cfg, context=self)\n\n self.integral = Integral(self.reg_max)\n self.loss_dfl = build_loss(loss_dfl)\n\n def _init_layers(self):\n \"\"\"Initialize layers of the head.\"\"\"\n self.relu = nn.ReLU(inplace=True)\n self.cls_convs = nn.ModuleList()\n self.reg_convs = nn.ModuleList()\n for i in range(self.stacked_convs):\n chn = self.in_channels if i == 0 else self.feat_channels\n self.cls_convs.append(\n ConvModule(\n chn,\n self.feat_channels,\n 3,\n stride=1,\n padding=1,\n conv_cfg=self.conv_cfg,\n norm_cfg=self.norm_cfg))\n self.reg_convs.append(\n ConvModule(\n chn,\n self.feat_channels,\n 3,\n stride=1,\n padding=1,\n conv_cfg=self.conv_cfg,\n norm_cfg=self.norm_cfg))\n assert self.num_anchors == 1, 'anchor free version'\n self.gfl_cls = nn.Conv2d(\n self.feat_channels, self.cls_out_channels, 3, padding=1)\n self.gfl_reg = nn.Conv2d(\n self.feat_channels, 4 * (self.reg_max + 1), 3, padding=1)\n self.scales = nn.ModuleList(\n [Scale(1.0) for _ in self.anchor_generator.strides])\n\n conf_vector = [nn.Conv2d(4 * self.total_dim, self.reg_channels, 1)]\n conf_vector += [self.relu]\n conf_vector += [nn.Conv2d(self.reg_channels, 1, 1), nn.Sigmoid()]\n\n self.reg_conf = nn.Sequential(*conf_vector)\n\n def init_weights(self):\n \"\"\"Initialize weights of the head.\"\"\"\n for m in self.cls_convs:\n normal_init(m.conv, std=0.01)\n for m in self.reg_convs:\n normal_init(m.conv, std=0.01)\n for m in self.reg_conf:\n if isinstance(m, nn.Conv2d):\n normal_init(m, std=0.01)\n bias_cls = bias_init_with_prob(0.01)\n normal_init(self.gfl_cls, std=0.01, bias=bias_cls)\n normal_init(self.gfl_reg, std=0.01)\n\n def forward(self, feats):\n \"\"\"Forward features from the upstream network.\n Args:\n feats (tuple[Tensor]): Features from the upstream network, each is\n a 4D-tensor.\n Returns:\n tuple: Usually a tuple of classification scores and bbox prediction\n cls_scores (list[Tensor]): Classification and quality (IoU)\n joint scores for all scale levels, each is a 4D-tensor,\n the channel number is num_classes.\n bbox_preds (list[Tensor]): Box distribution logits for all\n scale levels, each is a 4D-tensor, the channel number is\n 4*(n+1), n is max value of integral set.\n \"\"\"\n return multi_apply(self.forward_single, feats, self.scales)\n\n def forward_single(self, x, scale):\n \"\"\"Forward feature of a single scale level.\n Args:\n x (Tensor): Features of a single scale level.\n scale (:obj: `mmcv.cnn.Scale`): Learnable scale module to resize\n the bbox prediction.\n Returns:\n tuple:\n cls_score (Tensor): Cls and quality joint scores for a single\n scale level the channel number is num_classes.\n bbox_pred (Tensor): Box distribution logits for a single scale\n level, the channel number is 4*(n+1), n is max value of\n integral set.\n \"\"\"\n cls_feat = x\n reg_feat = x\n for cls_conv in self.cls_convs:\n cls_feat = cls_conv(cls_feat)\n for reg_conv in self.reg_convs:\n reg_feat = reg_conv(reg_feat)\n\n bbox_pred = scale(self.gfl_reg(reg_feat)).float()\n N, C, H, W = bbox_pred.size()\n prob = F.softmax(bbox_pred.reshape(N, 4, self.reg_max+1, H, W), dim=2)\n prob_topk, _ = prob.topk(self.reg_topk, dim=2)\n\n if self.add_mean:\n stat = torch.cat([prob_topk, prob_topk.mean(dim=2, keepdim=True)],\n dim=2)\n else:\n stat = prob_topk\n\n quality_score = self.reg_conf(stat.reshape(N, -1, H, W))\n cls_score = self.gfl_cls(cls_feat).sigmoid() * quality_score\n\n return cls_score, bbox_pred\n\n def anchor_center(self, anchors):\n \"\"\"Get anchor centers from anchors.\n Args:\n anchors (Tensor): Anchor list with shape (N, 4), \"xyxy\" format.\n Returns:\n Tensor: Anchor centers with shape (N, 2), \"xy\" format.\n \"\"\"\n anchors_cx = (anchors[:, 2] + anchors[:, 0]) / 2\n anchors_cy = (anchors[:, 3] + anchors[:, 1]) / 2\n return torch.stack([anchors_cx, anchors_cy], dim=-1)\n\n def loss_single(self, anchors, cls_score, bbox_pred, labels, label_weights,\n bbox_targets, stride, num_total_samples):\n \"\"\"Compute loss of a single scale level.\n Args:\n anchors (Tensor): Box reference for each scale level with shape\n (N, num_total_anchors, 4).\n cls_score (Tensor): Cls and quality joint scores for each scale\n level has shape (N, num_classes, H, W).\n bbox_pred (Tensor): Box distribution logits for each scale\n level with shape (N, 4*(n+1), H, W), n is max value of integral\n set.\n labels (Tensor): Labels of each anchors with shape\n (N, num_total_anchors).\n label_weights (Tensor): Label weights of each anchor with shape\n (N, num_total_anchors)\n bbox_targets (Tensor): BBox regression targets of each anchor wight\n shape (N, num_total_anchors, 4).\n stride (tuple): Stride in this scale level.\n num_total_samples (int): Number of positive samples that is\n reduced over all GPUs.\n Returns:\n dict[str, Tensor]: A dictionary of loss components.\n \"\"\"\n assert stride[0] == stride[1], 'h stride is not equal to w stride!'\n anchors = anchors.reshape(-1, 4)\n cls_score = cls_score.permute(0, 2, 3,\n 1).reshape(-1, self.cls_out_channels)\n bbox_pred = bbox_pred.permute(0, 2, 3,\n 1).reshape(-1, 4 * (self.reg_max + 1))\n bbox_targets = bbox_targets.reshape(-1, 4)\n labels = labels.reshape(-1)\n label_weights = label_weights.reshape(-1)\n\n # FG cat_id: [0, num_classes -1], BG cat_id: num_classes\n bg_class_ind = self.num_classes\n pos_inds = ((labels >= 0)\n & (labels < bg_class_ind)).nonzero().squeeze(1)\n score = label_weights.new_zeros(labels.shape)\n\n if len(pos_inds) > 0:\n pos_bbox_targets = bbox_targets[pos_inds]\n pos_bbox_pred = bbox_pred[pos_inds]\n pos_anchors = anchors[pos_inds]\n pos_anchor_centers = self.anchor_center(pos_anchors) / stride[0]\n\n weight_targets = cls_score.detach()\n weight_targets = weight_targets.max(dim=1)[0][pos_inds]\n pos_bbox_pred_corners = self.integral(pos_bbox_pred)\n pos_decode_bbox_pred = distance2bbox(pos_anchor_centers,\n pos_bbox_pred_corners)\n pos_decode_bbox_targets = pos_bbox_targets / stride[0]\n score[pos_inds] = bbox_overlaps(\n pos_decode_bbox_pred.detach(),\n pos_decode_bbox_targets,\n is_aligned=True)\n pred_corners = pos_bbox_pred.reshape(-1, self.reg_max + 1)\n target_corners = bbox2distance(pos_anchor_centers,\n pos_decode_bbox_targets,\n self.reg_max).reshape(-1)\n\n # regression loss\n loss_bbox = self.loss_bbox(\n pos_decode_bbox_pred,\n pos_decode_bbox_targets,\n weight=weight_targets,\n avg_factor=1.0)\n\n # dfl loss\n loss_dfl = self.loss_dfl(\n pred_corners,\n target_corners,\n weight=weight_targets[:, None].expand(-1, 4).reshape(-1),\n avg_factor=4.0)\n else:\n loss_bbox = bbox_pred.sum() * 0\n loss_dfl = bbox_pred.sum() * 0\n weight_targets = torch.tensor(0).cuda()\n\n # cls (qfl) loss\n loss_cls = self.loss_cls(\n cls_score, (labels, score),\n weight=label_weights,\n avg_factor=num_total_samples)\n\n return loss_cls, loss_bbox, loss_dfl, weight_targets.sum()\n\n @force_fp32(apply_to=('cls_scores', 'bbox_preds'))\n def loss(self,\n cls_scores,\n bbox_preds,\n gt_bboxes,\n gt_labels,\n img_metas,\n gt_bboxes_ignore=None):\n \"\"\"Compute losses of the head.\n Args:\n cls_scores (list[Tensor]): Cls and quality scores for each scale\n level has shape (N, num_classes, H, W).\n bbox_preds (list[Tensor]): Box distribution logits for each scale\n level with shape (N, 4*(n+1), H, W), n is max value of integral\n set.\n gt_bboxes (list[Tensor]): Ground truth bboxes for each image with\n shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format.\n gt_labels (list[Tensor]): class indices corresponding to each box\n img_metas (list[dict]): Meta information of each image, e.g.,\n image size, scaling factor, etc.\n gt_bboxes_ignore (list[Tensor] | None): specify which bounding\n boxes can be ignored when computing the loss.\n Returns:\n dict[str, Tensor]: A dictionary of loss components.\n \"\"\"\n\n featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]\n assert len(featmap_sizes) == self.anchor_generator.num_levels\n\n device = cls_scores[0].device\n anchor_list, valid_flag_list = self.get_anchors(\n featmap_sizes, img_metas, device=device)\n label_channels = self.cls_out_channels if self.use_sigmoid_cls else 1\n\n cls_reg_targets = self.get_targets(\n anchor_list,\n valid_flag_list,\n gt_bboxes,\n img_metas,\n gt_bboxes_ignore_list=gt_bboxes_ignore,\n gt_labels_list=gt_labels,\n label_channels=label_channels)\n if cls_reg_targets is None:\n return None\n\n (anchor_list, labels_list, label_weights_list, bbox_targets_list,\n bbox_weights_list, num_total_pos, num_total_neg) = cls_reg_targets\n\n num_total_samples = reduce_mean(\n torch.tensor(num_total_pos).cuda()).item()\n num_total_samples = max(num_total_samples, 1.0)\n\n losses_cls, losses_bbox, losses_dfl,\\\n avg_factor = multi_apply(\n self.loss_single,\n anchor_list,\n cls_scores,\n bbox_preds,\n labels_list,\n label_weights_list,\n bbox_targets_list,\n self.anchor_generator.strides,\n num_total_samples=num_total_samples)\n\n avg_factor = sum(avg_factor)\n avg_factor = reduce_mean(avg_factor).item()\n losses_bbox = list(map(lambda x: x / avg_factor, losses_bbox))\n losses_dfl = list(map(lambda x: x / avg_factor, losses_dfl))\n return dict(\n loss_cls=losses_cls, loss_bbox=losses_bbox, loss_dfl=losses_dfl)\n\n def _get_bboxes_single(self,\n cls_scores,\n bbox_preds,\n mlvl_anchors,\n img_shape,\n scale_factor,\n cfg,\n rescale=False,\n with_nms=True):\n \"\"\"Transform outputs for a single batch item into labeled boxes.\n Args:\n cls_scores (list[Tensor]): Box scores for a single scale level\n has shape (num_classes, H, W).\n bbox_preds (list[Tensor]): Box distribution logits for a single\n scale level with shape (4*(n+1), H, W), n is max value of\n integral set.\n mlvl_anchors (list[Tensor]): Box reference for a single scale level\n with shape (num_total_anchors, 4).\n img_shape (tuple[int]): Shape of the input image,\n (height, width, 3).\n scale_factor (ndarray): Scale factor of the image arange as\n (w_scale, h_scale, w_scale, h_scale).\n cfg (mmcv.Config | None): Test / postprocessing configuration,\n if None, test_cfg would be used.\n rescale (bool): If True, return boxes in original image space.\n Default: False.\n with_nms (bool): If True, do nms before return boxes.\n Default: True.\n Returns:\n tuple(Tensor):\n det_bboxes (Tensor): Bbox predictions in shape (N, 5), where\n the first 4 columns are bounding box positions\n (tl_x, tl_y, br_x, br_y) and the 5-th column is a score\n between 0 and 1.\n det_labels (Tensor): A (N,) tensor where each item is the\n predicted class label of the corresponding box.\n \"\"\"\n cfg = self.test_cfg if cfg is None else cfg\n assert len(cls_scores) == len(bbox_preds) == len(mlvl_anchors)\n mlvl_bboxes = []\n mlvl_scores = []\n for cls_score, bbox_pred, stride, anchors in zip(\n cls_scores, bbox_preds, self.anchor_generator.strides,\n mlvl_anchors):\n assert cls_score.size()[-2:] == bbox_pred.size()[-2:]\n assert stride[0] == stride[1]\n\n scores = cls_score.permute(1, 2, 0).reshape(\n -1, self.cls_out_channels)\n bbox_pred = bbox_pred.permute(1, 2, 0)\n bbox_pred = self.integral(bbox_pred) * stride[0]\n\n nms_pre = cfg.get('nms_pre', -1)\n if nms_pre > 0 and scores.shape[0] > nms_pre:\n max_scores, _ = scores.max(dim=1)\n _, topk_inds = max_scores.topk(nms_pre)\n anchors = anchors[topk_inds, :]\n bbox_pred = bbox_pred[topk_inds, :]\n scores = scores[topk_inds, :]\n\n bboxes = distance2bbox(\n self.anchor_center(anchors), bbox_pred, max_shape=img_shape)\n mlvl_bboxes.append(bboxes)\n mlvl_scores.append(scores)\n\n mlvl_bboxes = torch.cat(mlvl_bboxes)\n if rescale:\n mlvl_bboxes /= mlvl_bboxes.new_tensor(scale_factor)\n\n mlvl_scores = torch.cat(mlvl_scores)\n # Add a dummy background class to the backend when using sigmoid\n # remind that we set FG labels to [0, num_class-1] since mmdet v2.0\n # BG cat_id: num_class\n padding = mlvl_scores.new_zeros(mlvl_scores.shape[0], 1)\n mlvl_scores = torch.cat([mlvl_scores, padding], dim=1)\n\n if with_nms:\n det_bboxes, det_labels = multiclass_nms(mlvl_bboxes, mlvl_scores,\n cfg.score_thr, cfg.nms,\n cfg.max_per_img)\n return det_bboxes, det_labels\n else:\n return mlvl_bboxes, mlvl_scores\n\n def get_targets(self,\n anchor_list,\n valid_flag_list,\n gt_bboxes_list,\n img_metas,\n gt_bboxes_ignore_list=None,\n gt_labels_list=None,\n label_channels=1,\n unmap_outputs=True):\n \"\"\"Get targets for GFL head.\n This method is almost the same as `AnchorHead.get_targets()`. Besides\n returning the targets as the parent method does, it also returns the\n anchors as the first element of the returned tuple.\n \"\"\"\n num_imgs = len(img_metas)\n assert len(anchor_list) == len(valid_flag_list) == num_imgs\n\n # anchor number of multi levels\n num_level_anchors = [anchors.size(0) for anchors in anchor_list[0]]\n num_level_anchors_list = [num_level_anchors] * num_imgs\n\n # concat all level anchors and flags to a single tensor\n for i in range(num_imgs):\n assert len(anchor_list[i]) == len(valid_flag_list[i])\n anchor_list[i] = torch.cat(anchor_list[i])\n valid_flag_list[i] = torch.cat(valid_flag_list[i])\n\n # compute targets for each image\n if gt_bboxes_ignore_list is None:\n gt_bboxes_ignore_list = [None for _ in range(num_imgs)]\n if gt_labels_list is None:\n gt_labels_list = [None for _ in range(num_imgs)]\n (all_anchors, all_labels, all_label_weights, all_bbox_targets,\n all_bbox_weights, pos_inds_list, neg_inds_list) = multi_apply(\n self._get_target_single,\n anchor_list,\n valid_flag_list,\n num_level_anchors_list,\n gt_bboxes_list,\n gt_bboxes_ignore_list,\n gt_labels_list,\n img_metas,\n label_channels=label_channels,\n unmap_outputs=unmap_outputs)\n # no valid anchors\n if any([labels is None for labels in all_labels]):\n return None\n # sampled anchors of all images\n num_total_pos = sum([max(inds.numel(), 1) for inds in pos_inds_list])\n num_total_neg = sum([max(inds.numel(), 1) for inds in neg_inds_list])\n # split targets to a list w.r.t. multiple levels\n anchors_list = images_to_levels(all_anchors, num_level_anchors)\n labels_list = images_to_levels(all_labels, num_level_anchors)\n label_weights_list = images_to_levels(all_label_weights,\n num_level_anchors)\n bbox_targets_list = images_to_levels(all_bbox_targets,\n num_level_anchors)\n bbox_weights_list = images_to_levels(all_bbox_weights,\n num_level_anchors)\n return (anchors_list, labels_list, label_weights_list,\n bbox_targets_list, bbox_weights_list, num_total_pos,\n num_total_neg)\n\n def _get_target_single(self,\n flat_anchors,\n valid_flags,\n num_level_anchors,\n gt_bboxes,\n gt_bboxes_ignore,\n gt_labels,\n img_meta,\n label_channels=1,\n unmap_outputs=True):\n \"\"\"Compute regression, classification targets for anchors in a single\n image.\n Args:\n flat_anchors (Tensor): Multi-level anchors of the image, which are\n concatenated into a single tensor of shape (num_anchors, 4)\n valid_flags (Tensor): Multi level valid flags of the image,\n which are concatenated into a single tensor of\n shape (num_anchors,).\n num_level_anchors Tensor): Number of anchors of each scale level.\n gt_bboxes (Tensor): Ground truth bboxes of the image,\n shape (num_gts, 4).\n gt_bboxes_ignore (Tensor): Ground truth bboxes to be\n ignored, shape (num_ignored_gts, 4).\n gt_labels (Tensor): Ground truth labels of each box,\n shape (num_gts,).\n img_meta (dict): Meta info of the image.\n label_channels (int): Channel of label.\n unmap_outputs (bool): Whether to map outputs back to the original\n set of anchors.\n Returns:\n tuple: N is the number of total anchors in the image.\n anchors (Tensor): All anchors in the image with shape (N, 4).\n labels (Tensor): Labels of all anchors in the image with shape\n (N,).\n label_weights (Tensor): Label weights of all anchor in the\n image with shape (N,).\n bbox_targets (Tensor): BBox targets of all anchors in the\n image with shape (N, 4).\n bbox_weights (Tensor): BBox weights of all anchors in the\n image with shape (N, 4).\n pos_inds (Tensor): Indices of postive anchor with shape\n (num_pos,).\n neg_inds (Tensor): Indices of negative anchor with shape\n (num_neg,).\n \"\"\"\n inside_flags = anchor_inside_flags(flat_anchors, valid_flags,\n img_meta['img_shape'][:2],\n self.train_cfg.allowed_border)\n if not inside_flags.any():\n return (None, ) * 7\n # assign gt and sample anchors\n anchors = flat_anchors[inside_flags, :]\n\n num_level_anchors_inside = self.get_num_level_anchors_inside(\n num_level_anchors, inside_flags)\n assign_result = self.assigner.assign(anchors, num_level_anchors_inside,\n gt_bboxes, gt_bboxes_ignore,\n gt_labels)\n\n sampling_result = self.sampler.sample(assign_result, anchors,\n gt_bboxes)\n\n num_valid_anchors = anchors.shape[0]\n bbox_targets = torch.zeros_like(anchors)\n bbox_weights = torch.zeros_like(anchors)\n labels = anchors.new_full((num_valid_anchors, ),\n self.num_classes,\n dtype=torch.long)\n label_weights = anchors.new_zeros(num_valid_anchors, dtype=torch.float)\n\n pos_inds = sampling_result.pos_inds\n neg_inds = sampling_result.neg_inds\n if len(pos_inds) > 0:\n pos_bbox_targets = sampling_result.pos_gt_bboxes\n bbox_targets[pos_inds, :] = pos_bbox_targets\n bbox_weights[pos_inds, :] = 1.0\n if gt_labels is None:\n # Only rpn gives gt_labels as None\n # Foreground is the first class\n labels[pos_inds] = 0\n else:\n labels[pos_inds] = gt_labels[\n sampling_result.pos_assigned_gt_inds]\n if self.train_cfg.pos_weight <= 0:\n label_weights[pos_inds] = 1.0\n else:\n label_weights[pos_inds] = self.train_cfg.pos_weight\n if len(neg_inds) > 0:\n label_weights[neg_inds] = 1.0\n\n # map up to original set of anchors\n if unmap_outputs:\n num_total_anchors = flat_anchors.size(0)\n anchors = unmap(anchors, num_total_anchors, inside_flags)\n labels = unmap(\n labels, num_total_anchors, inside_flags, fill=self.num_classes)\n label_weights = unmap(label_weights, num_total_anchors,\n inside_flags)\n bbox_targets = unmap(bbox_targets, num_total_anchors, inside_flags)\n bbox_weights = unmap(bbox_weights, num_total_anchors, inside_flags)\n\n return (anchors, labels, label_weights, bbox_targets, bbox_weights,\n pos_inds, neg_inds)\n\n def get_num_level_anchors_inside(self, num_level_anchors, inside_flags):\n split_inside_flags = torch.split(inside_flags, num_level_anchors)\n num_level_anchors_inside = [\n int(flags.sum()) for flags in split_inside_flags\n ]\n return num_level_anchors_inside\n",
"import cv2\r\nimport mmcv\r\nimport numpy as np\r\nimport os\r\nimport torch\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef featuremap_2_heatmap(feature_map):\r\n assert isinstance(feature_map, torch.Tensor)\r\n feature_map = feature_map.detach()\r\n heatmap = feature_map[:,0,:,:]*0\r\n heatmaps = []\r\n for c in range(feature_map.shape[1]):\r\n heatmap+=feature_map[:,c,:,:]\r\n heatmap = heatmap.cpu().numpy()\r\n heatmap = np.mean(heatmap, axis=0)\r\n\r\n heatmap = np.maximum(heatmap, 0)\r\n heatmap /= np.max(heatmap)\r\n heatmaps.append(heatmap)\r\n\r\n return heatmaps\r\n\r\ndef draw_feature_map(features,save_dir = '/media/amax/CC4260DC4260CCB0/mmdetv2.14/mmdetection/temp/results/feature_map',name = None):\r\n i=0\r\n if isinstance(features,torch.Tensor):\r\n for heat_maps in features:\r\n heat_maps=heat_maps.unsqueeze(0)\r\n heatmaps = featuremap_2_heatmap(heat_maps)\r\n # 这里的h,w指的是你想要把特征图resize成多大的尺寸\r\n # heatmap = cv2.resize(heatmap, (h, w)) \r\n for heatmap in heatmaps:\r\n heatmap = np.uint8(255 * heatmap)\r\n # 下面这行将热力图转换为RGB格式 ,如果注释掉就是灰度图\r\n heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)\r\n superimposed_img = heatmap\r\n # print(superimposed_img)\r\n # plt.imshow(superimposed_img,cmap='gray')\r\n # plt.show()\r\n #cv2.imwrite(os.path.join(save_dir,'111.png'), superimposed_img)\r\n cv2.imwrite('/media/amax/CC4260DC4260CCB0/mmdetv2.14/mmdetection/temp/results/111.jpg',superimposed_img)\r\n else:\r\n for featuremap in features:\r\n heatmaps = featuremap_2_heatmap(featuremap)\r\n # heatmap = cv2.resize(heatmap, (img.shape[1], img.shape[0])) # 将热力图的大小调整为与原始图像相同\r\n for heatmap in heatmaps:\r\n heatmap = np.uint8(255 * heatmap) # 将热力图转换为RGB格式\r\n heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET)\r\n # superimposed_img = heatmap * 0.5 + img*0.3\r\n superimposed_img = heatmap\r\n #plt.imshow(superimposed_img,cmap='gray')\r\n #plt.show()\r\n # 下面这些是对特征图进行保存,使用时取消注释\r\n #cv2.imshow(\"1\",superimposed_img)\r\n #cv2.waitKey(0)\r\n #cv2.destroyAllWindows()\r\n path = save_dir + str(i) +'-' + name + '.jpg'\r\n print(path)\r\n cv2.imwrite(path, superimposed_img)\r\n i=i+1\r\n"
] |
[
[
"torch.nn.Sequential",
"torch.linspace",
"torch.cat",
"torch.nn.ModuleList",
"torch.nn.Conv2d",
"torch.zeros_like",
"torch.nn.Sigmoid",
"torch.tensor",
"torch.split",
"torch.stack",
"torch.nn.ReLU"
],
[
"numpy.max",
"numpy.maximum",
"numpy.uint8",
"numpy.mean"
]
] |
stefanosantaris/DynVGAE
|
[
"f5cba46b055e7c7aa3048ace0d24fce1a5300313"
] |
[
"utils/dataset/GraphLoader.py"
] |
[
"import networkx as nx\nimport numpy as np\nimport scipy.sparse as sps\n\nclass GraphLoader():\n def __init__(self, path):\n super(GraphLoader, self).__init__()\n self.path = path\n\n def load_graph(self, file):\n return nx.read_weighted_edgelist(self.path + \"edges\" + str(file) +\".csv\", delimiter=',', nodetype=int,encoding='utf-8')\n\n def read_adjacency(self, file, max_id):\n G = self.load_graph(file)\n node_list = list(G.nodes())\n node_list.sort()\n if node_list[-1] > max_id:\n max_id = node_list[-1]\n\n adj = np.zeros((max_id + 1, max_id + 1))\n edge_list = G.edges(data=True)\n for edge in edge_list:\n src = edge[0]\n dst = edge[1]\n weight = edge[2]['weight']\n adj[src][dst] = weight\n adj[dst][src] = weight\n return sps.csr_matrix(adj, dtype=float)"
] |
[
[
"numpy.zeros",
"scipy.sparse.csr_matrix"
]
] |
chen-zichen/SelfTextAttack
|
[
"d241122d91e871a5ed6adaf1afb21f6ba06dfcaa"
] |
[
"robust_train_bowen.py"
] |
[
"import numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom textattack.models.bert_models import BertSModel, Attacker\nfrom tqdm import tqdm\nfrom transformers import BertTokenizer, BertForSequenceClassification, AdamW\n\nimport os\n\ndef write_adv(file_addr, orig_list, adv_list, label_list):\n with open(file_addr, 'w', encoding = 'utf-8') as f:\n for i in range(len(orig_list)):\n orig = orig_list[i]\n adv = adv_list[i]\n label = label_list[i]\n f.write(orig + '\\n')\n f.write(adv + '\\n')\n f.write(str(label) + '\\n\\n')\n\nclass Config():\n model_type = 'bert-base-uncased'\n output_dir = 'repos/TextAttack/checkpoints/bert-sst-at/bowen'\n dataset_dir = 'repos/text_grad/sst-2/'\n cache_dir = 'repos/model_cache/bert_model/bert-base-uncased/'\n finetune_dir = 'repos/text_grad/checkpoints/bert-base-uncased-sst/'\n num_labels = 2\n log_dir = '/ATLog/'\n\n # at_type = 'augmentation' ## augmentation/epoch_aug/batch_aug\n # at_type = 'epoch_aug' ## augmentation/epoch_aug/batch_aug\n at_type = 'batch_aug' ## augmentation/epoch_aug/batch_aug\n\n num_epochs = 5\n batch_size = 32\n\n\nconfig = Config()\ndevice = torch.device(\"cuda\")\ncls_model = BertSModel(model_type = config.model_type, output_dir = config.output_dir, cache_dir = config.cache_dir,\n dataset_dir = config.dataset_dir, num_labels = config.num_labels, device = device)\n\nlog_dir = config.log_dir\n\nif config.at_type in ['augmentation', 'epoch_aug']:\n surrogate_model = BertSModel(fine_tune_dir = config.finetune_dir, num_labels = config.num_labels, device = device)\n attacker = Attacker(victim_model = surrogate_model.model, tokenizer = surrogate_model.tokenizer)\nelif config.at_type in ['batch_aug']:\n attacker = Attacker(victim_model = cls_model.model, tokenizer = cls_model.tokenizer)\nelse:\n raise NotImplementedError\n\ntrain_corpus, train_label, valid_corpus, valid_label, test_corpus, test_label = cls_model.load_dataset()\noutput_dir = config.output_dir\n# train_corpus = train_corpus[:50]\n# train_label = train_label[:50]\n\ntrain_set = [(train_corpus[i], train_label[i]) for i in range(len(train_corpus))]\n\nif config.at_type in ['augmentation', 'epoch_aug']:\n surrogate_model.model.eval()\n surrogate_model.eval_on_test()\n print(\"generate adversarial examples for epoch 0...\")\n perturbed_examples = attacker.perturb(train_set, visualize = True)\n file_addr = log_dir + 'aug_epoch0.txt'\n write_adv(file_addr, train_corpus, perturbed_examples, train_label)\n\n perturbed_label = train_label[:]\n concat_train_corpus = train_corpus + perturbed_examples\n concat_train_label = train_label + perturbed_label\n concat_train_xs, concat_train_masks = cls_model.tokenize_corpus(concat_train_corpus)\n concat_train_ys = np.array(concat_train_label)\n\nelse:\n # breakpoint()\n train_xs, train_masks = cls_model.tokenize_corpus(train_corpus)\n train_ys = np.array(train_label)\n\n\nvalid_xs, valid_masks = cls_model.tokenize_corpus(valid_corpus)\nvalid_ys = np.array(valid_label)\ntest_xs, test_masks = cls_model.tokenize_corpus(test_corpus)\ntest_ys = np.array(test_label)\n\nbatch_size = config.batch_size\nglobal_acc = 0\nif not os.path.exists(cls_model.output_dir):\n os.makedirs(cls_model.output_dir)\nlog_file = os.path.join(cls_model.output_dir, \"batch_accuracy.txt\")\nwith open(log_file, 'a') as file1:\n file1.write(\"epoch, epoch_loss, epoch_accuracy, local_ac \\n\")\nfor epoch in range(config.num_epochs):\n epoch_loss = 0\n epoch_accuracy = 0\n if config.at_type == 'augmentation':\n cls_model.model.train()\n num_examples = concat_train_xs.shape[0]\n selection = np.random.choice(num_examples,size = num_examples,replace = False)\n batches_per_epoch = num_examples // batch_size\n for idx in tqdm(range(int(batches_per_epoch))):\n batch_idx = np.array(selection[idx * batch_size:(idx + 1) * batch_size])\n batch_xs = torch.LongTensor(concat_train_xs[batch_idx]).to(cls_model.device)\n batch_ys = torch.LongTensor(concat_train_ys[batch_idx]).to(cls_model.device)\n batch_masks = torch.LongTensor(concat_train_masks[batch_idx]).to(cls_model.device)\n # print(batch_xs.size())\n cls_model.optimizer.zero_grad()\n # model.zero_grad()\n result = cls_model.model(input_ids = batch_xs,labels = batch_ys,attention_mask = batch_masks)\n loss = result.loss\n logits = result.logits\n epoch_loss += loss.item()\n epoch_accuracy += torch.argmax(logits,dim = 1).eq(batch_ys).sum().item()/batch_size\n loss.backward()\n cls_model.optimizer.step()\n epoch_loss /= batches_per_epoch\n epoch_accuracy /= batches_per_epoch\n\n elif config.at_type == 'epoch_aug':\n if epoch > 0: ## augment \n cls_model.model.eval()\n print(f\"generate adversarial examples for epoch {epoch}...\")\n perturbed_examples = attacker.perturb(train_set,)\n perturbed_label = train_label[:]\n concat_train_corpus = train_corpus + perturbed_examples\n concat_train_label = train_label + perturbed_label\n\n concat_train_xs, concat_train_masks = cls_model.tokenize_corpus(concat_train_corpus)\n concat_train_ys = np.array(concat_train_label)\n cls_model.model.train()\n num_examples = concat_train_xs.shape[0]\n selection = np.random.choice(num_examples,size = num_examples,replace = False)\n batches_per_epoch = num_examples // batch_size\n for idx in range(batches_per_epoch):\n batch_idx = np.array(selection[idx * batch_size:(idx + 1) * batch_size])\n batch_xs = torch.LongTensor(concat_train_xs[batch_idx]).to(cls_model.device)\n batch_ys = torch.LongTensor(concat_train_ys[batch_idx]).to(cls_model.device)\n batch_masks = torch.LongTensor(concat_train_masks[batch_idx]).to(cls_model.device)\n # print(batch_xs.size())\n cls_model.optimizer.zero_grad()\n # model.zero_grad()\n result = cls_model.model(input_ids = batch_xs,labels = batch_ys,attention_mask = batch_masks)\n loss = result.loss\n logits = result.logits\n epoch_loss += loss.item()\n epoch_accuracy += torch.argmax(logits,dim = 1).eq(batch_ys).sum().item()/batch_size\n loss.backward()\n cls_model.optimizer.step()\n epoch_loss /= batches_per_epoch\n epoch_accuracy /= batches_per_epoch \n\n else:\n batch_size /= 2 \n batch_size = int(batch_size)\n num_examples = train_xs.shape[0]\n selection = np.random.choice(num_examples,size = num_examples,replace = False)\n batches_per_epoch = num_examples // batch_size \n for idx in tqdm(range(int(batches_per_epoch))):\n # breakpoint()\n batch_idx = selection[idx * batch_size:(idx + 1) * batch_size]\n batch_corpus = [train_corpus[x] for x in batch_idx]\n batch_labels = [train_label[x] for x in batch_idx]\n # batch_idx = np.array(selection[idx * batch_size:(idx + 1) * batch_size])\n # batch_xs = torch.LongTensor(train_xs[batch_idx]).to(cls_model.device)\n # batch_ys = torch.LongTensor(train_ys[batch_idx]).to(cls_model.device)\n\n batch_instances = [train_set[x] for x in batch_idx]\n\n cls_model.model.eval()\n adv_corpus = attacker.perturb(batch_instances)\n adv_labels = batch_labels[:]\n concat_batch_corpus = adv_corpus\n concat_batch_labels = adv_labels\n\n concat_xs, concat_masks = cls_model.tokenize_corpus(concat_batch_corpus)\n batch_xs = torch.LongTensor(concat_xs).to(cls_model.device)\n batch_masks = torch.LongTensor(concat_masks).to(cls_model.device)\n batch_ys = torch.LongTensor(concat_batch_labels).to(cls_model.device)\n\n batch_order = torch.randperm(batch_xs.size(0))\n batch_xs = batch_xs[batch_order]\n batch_masks = batch_masks[batch_order]\n batch_ys = batch_ys[batch_order]\n\n\n # batch_xs = torch.LongTensor(train_xs[batch_idx]).to(cls_model.device)\n # batch_ys = torch.LongTensor(train_ys[batch_idx]).to(cls_model.device)\n # batch_masks = torch.LongTensor(train_masks[batch_idx]).to(cls_model.device)\n # print(batch_xs.size())\n cls_model.model.train()\n cls_model.optimizer.zero_grad()\n # model.zero_grad()\n result = cls_model.model(input_ids = batch_xs,labels = batch_ys,attention_mask = batch_masks)\n loss = result.loss\n logits = result.logits\n epoch_loss += loss.item()\n epoch_accuracy += torch.argmax(logits,dim = 1).eq(batch_ys).sum().item()/batch_size\n loss.backward()\n cls_model.optimizer.step()\n \n epoch_loss /= batches_per_epoch\n epoch_accuracy /= batches_per_epoch \n print(epoch,' ',epoch_loss, ' ',epoch_accuracy) \n # print('Train accuracy = ', cls_model.evaluate_accuracy(train_xs,train_ys,train_masks,batch_size))\n local_acc = cls_model.evaluate_accuracy(valid_xs, valid_ys, valid_masks, batch_size)\n print(\"valid accuracy = \", local_acc)\n \n # output_dir_epoch = os.path.join(cls_model.output_dir, f'epoch{epoch}')\n if not os.path.exists(cls_model.output_dir):\n os.makedirs(cls_model.output_dir)\n save_path = cls_model.output_dir + '/' + str(epoch)\n cls_model.model.save_pretrained(save_path)\n cls_model.tokenizer.save_pretrained(save_path)\n with open(log_file, 'a') as file1:\n file1.write(f\"{epoch}, {epoch_loss}, {epoch_accuracy}, {local_acc} \\n\")\n\n\ncls_model.model = BertForSequenceClassification.from_pretrained(save_path)\ncls_model.model.to(cls_model.device)\nprint(\"Test accuracy = \", cls_model.evaluate_accuracy(test_xs,test_ys,test_masks,batch_size))\nprint(\"All done\")\ncls_model.model.eval() \n\n\n\n\n"
] |
[
[
"torch.LongTensor",
"numpy.random.choice",
"torch.device",
"numpy.array",
"torch.argmax"
]
] |
bsgiovanini/transformer
|
[
"e128fa862f1b3d17d7b92df169a2bbee3f08366f"
] |
[
"conf.py"
] |
[
"\"\"\"\n@author : Hyunwoong\n@when : 2019-10-22\n@homepage : https://github.com/gusdnd852\n\"\"\"\nimport torch\n\n# GPU device setting\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n# model parameter setting\nbatch_size = 32\nmax_len = 256\nd_model = 512\nn_layers = 6\nn_heads = 8\nffn_hidden = 2048\ndrop_prob = 0.1\n\n# optimizer parameter setting\ninit_lr = 1e-5\nfactor = 0.9\nadam_eps = 5e-9\npatience = 10\nwarmup = 100\nepoch = 1000\nclip = 1.0\nweight_decay = 5e-4\ninf = float('inf')\n"
] |
[
[
"torch.cuda.is_available"
]
] |
SConsul/multi-head-training-da
|
[
"407db085e4284ac11ff6abc842d11c24e1153acd"
] |
[
"wilds/datasets/camelyon17_dataset.py"
] |
[
"import os\nimport torch\nimport pandas as pd\nfrom PIL import Image\nimport numpy as np\nfrom wilds.datasets.wilds_dataset import WILDSDataset\nfrom wilds.common.grouper import CombinatorialGrouper\nfrom wilds.common.metrics.all_metrics import Accuracy\n\nclass Camelyon17Dataset(WILDSDataset):\n \"\"\"\n The CAMELYON17-WILDS histopathology dataset.\n This is a modified version of the original CAMELYON17 dataset.\n\n Supported `split_scheme`:\n - 'official'\n - 'mixed-to-test'\n\n Input (x):\n 96x96 image patches extracted from histopathology slides.\n\n Label (y):\n y is binary. It is 1 if the central 32x32 region contains any tumor tissue, and 0 otherwise.\n\n Metadata:\n Each patch is annotated with the ID of the hospital it came from (integer from 0 to 4)\n and the slide it came from (integer from 0 to 49).\n\n Website:\n https://camelyon17.grand-challenge.org/\n\n Original publication:\n @article{bandi2018detection,\n title={From detection of individual metastases to classification of lymph node status at the patient level: the camelyon17 challenge},\n author={Bandi, Peter and Geessink, Oscar and Manson, Quirine and Van Dijk, Marcory and Balkenhol, Maschenka and Hermsen, Meyke and Bejnordi, Babak Ehteshami and Lee, Byungjae and Paeng, Kyunghyun and Zhong, Aoxiao and others},\n journal={IEEE transactions on medical imaging},\n volume={38},\n number={2},\n pages={550--560},\n year={2018},\n publisher={IEEE}\n }\n\n License:\n This dataset is in the public domain and is distributed under CC0.\n https://creativecommons.org/publicdomain/zero/1.0/\n \"\"\"\n\n _dataset_name = 'camelyon17'\n _versions_dict = {\n '1.0': {\n 'download_url': 'https://worksheets.codalab.org/rest/bundles/0xe45e15f39fb54e9d9e919556af67aabe/contents/blob/',\n 'compressed_size': 10_658_709_504}}\n\n def __init__(self, version=None, root_dir='data', download=False, split_scheme='official'):\n self._version = version\n self._data_dir = self.initialize_data_dir(root_dir, download)\n self._original_resolution = (96,96)\n\n # Read in metadata\n self._metadata_df = pd.read_csv(\n os.path.join(self._data_dir, 'metadata.csv'),\n index_col=0,\n dtype={'patient': 'str'})\n\n # Get the y values\n self._y_array = torch.LongTensor(self._metadata_df['tumor'].values)\n self._y_size = 1\n self._n_classes = 2\n\n # Get filenames\n self._input_array = [\n f'patches/patient_{patient}_node_{node}/patch_patient_{patient}_node_{node}_x_{x}_y_{y}.png'\n for patient, node, x, y in\n self._metadata_df.loc[:, ['patient', 'node', 'x_coord', 'y_coord']].itertuples(index=False, name=None)]\n\n # Extract splits\n # Note that the hospital numbering here is different from what's in the paper,\n # where to avoid confusing readers we used a 1-indexed scheme and just labeled the test hospital as 5.\n # Here, the numbers are 0-indexed.\n test_center = 2\n val_center = 1\n\n self._split_dict = {\n 'train': 0,\n 'id_val': 1,\n 'test': 2,\n 'val': 3\n }\n self._split_names = {\n 'train': 'Train',\n 'id_val': 'Validation (ID)',\n 'test': 'Test',\n 'val': 'Validation (OOD)',\n }\n centers = self._metadata_df['center'].values.astype('long')\n num_centers = int(np.max(centers)) + 1\n val_center_mask = (self._metadata_df['center'] == val_center)\n test_center_mask = (self._metadata_df['center'] == test_center)\n self._metadata_df.loc[val_center_mask, 'split'] = self.split_dict['val']\n self._metadata_df.loc[test_center_mask, 'split'] = self.split_dict['test']\n\n self._split_scheme = split_scheme\n if self._split_scheme == 'official':\n pass\n elif self._split_scheme == 'mixed-to-test':\n # For the mixed-to-test setting,\n # we move slide 23 (corresponding to patient 042, node 3 in the original dataset)\n # from the test set to the training set\n slide_mask = (self._metadata_df['slide'] == 23)\n self._metadata_df.loc[slide_mask, 'split'] = self.split_dict['train']\n else:\n raise ValueError(f'Split scheme {self._split_scheme} not recognized')\n self._split_array = self._metadata_df['split'].values\n\n self._metadata_array = torch.stack(\n (torch.LongTensor(centers),\n torch.LongTensor(self._metadata_df['slide'].values),\n self._y_array),\n dim=1)\n self._metadata_fields = ['hospital', 'slide', 'y']\n\n self._eval_grouper = CombinatorialGrouper(\n dataset=self,\n groupby_fields=['slide'])\n\n super().__init__(root_dir, download, split_scheme)\n\n def get_input(self, idx):\n \"\"\"\n Returns x for a given idx.\n \"\"\"\n img_filename = os.path.join(\n self.data_dir,\n self._input_array[idx])\n x = Image.open(img_filename).convert('RGB')\n return x\n\n def eval(self, y_pred, y_true, metadata, prediction_fn=None):\n \"\"\"\n Computes all evaluation metrics.\n Args:\n - y_pred (Tensor): Predictions from a model. By default, they are predicted labels (LongTensor).\n But they can also be other model outputs such that prediction_fn(y_pred)\n are predicted labels.\n - y_true (LongTensor): Ground-truth labels\n - metadata (Tensor): Metadata\n - prediction_fn (function): A function that turns y_pred into predicted labels\n Output:\n - results (dictionary): Dictionary of evaluation metrics\n - results_str (str): String summarizing the evaluation metrics\n \"\"\"\n metric = Accuracy(prediction_fn=prediction_fn)\n return self.standard_group_eval(\n metric,\n self._eval_grouper,\n y_pred, y_true, metadata)\n"
] |
[
[
"numpy.max",
"torch.LongTensor"
]
] |
darrenudaiyan/TensorFlowExperiments
|
[
"32af9ee0679c5844a383cb8edafb4dab81d894e3"
] |
[
"data/trained_model.py"
] |
[
"import numpy as np\r\n\r\nclass TrainedModel:\r\n def __init__(self, monkey_magic,monkey_factor_log):\r\n self.monkey_magic = monkey_magic\r\n self.monkey_factor = np.exp(monkey_factor_log)"
] |
[
[
"numpy.exp"
]
] |
vvanirudh/imitation-learning-gym
|
[
"94dc4f3eb4222112fdb735bd3894338a03a75f5b"
] |
[
"gym/envs/mujoco/pusher.py"
] |
[
"import numpy as np\nfrom gym import utils\nfrom gym.envs.mujoco import mujoco_env\n\nimport mujoco_py\n\nclass PusherEnv(mujoco_env.MujocoEnv, utils.EzPickle):\n def __init__(self):\n utils.EzPickle.__init__(self)\n mujoco_env.MujocoEnv.__init__(self, 'pusher.xml', 5)\n\n def step(self, a):\n vec_1 = self.get_body_com(\"object\") - self.get_body_com(\"tips_arm\")\n vec_2 = self.get_body_com(\"object\") - self.get_body_com(\"goal\")\n\n reward_near = - np.linalg.norm(vec_1)\n reward_dist = - np.linalg.norm(vec_2)\n reward_ctrl = - np.square(a).sum()\n reward = reward_dist + 0.1 * reward_ctrl + 0.5 * reward_near\n\n self.do_simulation(a, self.frame_skip)\n ob = self._get_obs()\n done = False\n return ob, reward, done, dict(reward_dist=reward_dist,\n reward_ctrl=reward_ctrl)\n\n def viewer_setup(self):\n self.viewer.cam.trackbodyid = -1\n self.viewer.cam.distance = 4.0\n\n def reset_model(self):\n qpos = self.init_qpos\n\n self.goal_pos = np.asarray([0, 0])\n while True:\n self.cylinder_pos = np.concatenate([\n self.np_random.uniform(low=-0.3, high=0, size=1),\n self.np_random.uniform(low=-0.2, high=0.2, size=1)])\n if np.linalg.norm(self.cylinder_pos - self.goal_pos) > 0.17:\n break\n\n qpos[-4:-2] = self.cylinder_pos\n qpos[-2:] = self.goal_pos\n qvel = self.init_qvel + self.np_random.uniform(low=-0.005,\n high=0.005, size=self.model.nv)\n qvel[-4:] = 0\n self.set_state(qpos, qvel)\n return self._get_obs()\n\n def _get_obs(self):\n return np.concatenate([\n self.sim.data.qpos.flat[:7],\n self.sim.data.qvel.flat[:7],\n self.get_body_com(\"tips_arm\"),\n self.get_body_com(\"object\"),\n self.get_body_com(\"goal\"),\n ])\n\n def compute_state_action_reward(self, ob, a):\n '''\n Custom function to compute reward given current observation and action executed\n '''\n tips_arm = ob[14:17]\n object = ob[17:20]\n goal = ob[20:23]\n\n vec_1 = object - tips_arm\n vec_2 = object - goal\n\n reward_near = - np.linalg.norm(vec_1)\n reward_dist = - np.linalg.norm(vec_2)\n reward_ctrl = - np.square(a).sum()\n reward = reward_dist + 0.1 * reward_ctrl + 0.5 * reward_near\n\n return reward\n"
] |
[
[
"numpy.asarray",
"numpy.square",
"numpy.linalg.norm"
]
] |
luweishuang/AdelaiDet
|
[
"514f20b23ea664b682b065979e36f2289aee5763"
] |
[
"demo/predictor.py"
] |
[
"import numpy as np\nimport atexit\nimport bisect\nimport multiprocessing as mp\nfrom collections import deque\nimport cv2\nimport torch\n# import matplotlib.pyplot as plt\n\nfrom detectron2.data import MetadataCatalog\nfrom detectron2.engine.defaults import DefaultPredictor\nfrom detectron2.utils.video_visualizer import VideoVisualizer\nfrom detectron2.utils.visualizer import ColorMode, Visualizer\n\nfrom adet.utils.visualizer import TextVisualizer\n\n\nclass VisualizationDemo(object):\n def __init__(self, cfg, instance_mode=ColorMode.IMAGE, parallel=False):\n \"\"\"\n Args:\n cfg (CfgNode):\n instance_mode (ColorMode):\n parallel (bool): whether to run the model in different processes from visualization.\n Useful since the visualization logic can be slow.\n \"\"\"\n self.metadata = MetadataCatalog.get(\n cfg.DATASETS.TEST[0] if len(cfg.DATASETS.TEST) else \"__unused\"\n )\n self.cfg = cfg\n self.cpu_device = torch.device(\"cpu\")\n self.instance_mode = instance_mode\n self.vis_text = cfg.MODEL.ROI_HEADS.NAME == \"TextHead\"\n\n self.parallel = parallel\n if parallel:\n num_gpu = torch.cuda.device_count()\n self.predictor = AsyncPredictor(cfg, num_gpus=num_gpu)\n else:\n self.predictor = DefaultPredictor(cfg)\n\n def run_on_image(self, image):\n \"\"\"\n Args:\n image (np.ndarray): an image of shape (H, W, C) (in BGR order).\n This is the format used by OpenCV.\n\n Returns:\n predictions (dict): the output of the model.\n vis_output (VisImage): the visualized image output.\n \"\"\"\n vis_output = None\n predictions = self.predictor(image)\n # Convert image from OpenCV BGR format to Matplotlib RGB format.\n image = image[:, :, ::-1]\n if self.vis_text:\n visualizer = TextVisualizer(image, self.metadata, instance_mode=self.instance_mode, cfg=self.cfg)\n else:\n visualizer = Visualizer(image, self.metadata, instance_mode=self.instance_mode)\n\n if \"bases\" in predictions:\n print(\"func vis_base has been removed!!!!!!!!!!!\")\n # self.vis_bases(predictions[\"bases\"])\n if \"panoptic_seg\" in predictions:\n panoptic_seg, segments_info = predictions[\"panoptic_seg\"]\n vis_output = visualizer.draw_panoptic_seg_predictions(\n panoptic_seg.to(self.cpu_device), segments_info\n )\n else:\n if \"sem_seg\" in predictions:\n vis_output = visualizer.draw_sem_seg(\n predictions[\"sem_seg\"].argmax(dim=0).to(self.cpu_device))\n if \"instances\" in predictions:\n instances = predictions[\"instances\"].to(self.cpu_device)\n vis_output = visualizer.draw_instance_predictions(predictions=instances)\n\n return predictions, vis_output\n\n def _frame_from_video(self, video):\n while video.isOpened():\n success, frame = video.read()\n if success:\n yield frame\n else:\n break\n\n # def vis_bases(self, bases):\n # basis_colors = [[2, 200, 255], [107, 220, 255], [30, 200, 255], [60, 220, 255]]\n # bases = bases[0].squeeze()\n # bases = (bases / 8).tanh().cpu().numpy()\n # num_bases = len(bases)\n # fig, axes = plt.subplots(nrows=num_bases // 2, ncols=2)\n # for i, basis in enumerate(bases):\n # basis = (basis + 1) / 2\n # basis = basis / basis.max()\n # basis_viz = np.zeros((basis.shape[0], basis.shape[1], 3), dtype=np.uint8)\n # basis_viz[:, :, 0] = basis_colors[i][0]\n # basis_viz[:, :, 1] = basis_colors[i][1]\n # basis_viz[:, :, 2] = np.uint8(basis * 255)\n # basis_viz = cv2.cvtColor(basis_viz, cv2.COLOR_HSV2RGB)\n # axes[i // 2][i % 2].imshow(basis_viz)\n # plt.show()\n\n def run_on_video(self, video):\n \"\"\"\n Visualizes predictions on frames of the input video.\n\n Args:\n video (cv2.VideoCapture): a :class:`VideoCapture` object, whose source can be\n either a webcam or a video file.\n\n Yields:\n ndarray: BGR visualizations of each video frame.\n \"\"\"\n video_visualizer = VideoVisualizer(self.metadata, self.instance_mode)\n\n def process_predictions(frame, predictions):\n frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n if \"panoptic_seg\" in predictions:\n panoptic_seg, segments_info = predictions[\"panoptic_seg\"]\n vis_frame = video_visualizer.draw_panoptic_seg_predictions(\n frame, panoptic_seg.to(self.cpu_device), segments_info\n )\n elif \"instances\" in predictions:\n predictions = predictions[\"instances\"].to(self.cpu_device)\n vis_frame = video_visualizer.draw_instance_predictions(frame, predictions)\n elif \"sem_seg\" in predictions:\n vis_frame = video_visualizer.draw_sem_seg(\n frame, predictions[\"sem_seg\"].argmax(dim=0).to(self.cpu_device)\n )\n\n # Converts Matplotlib RGB format to OpenCV BGR format\n vis_frame = cv2.cvtColor(vis_frame.get_image(), cv2.COLOR_RGB2BGR)\n return vis_frame\n\n frame_gen = self._frame_from_video(video)\n if self.parallel:\n buffer_size = self.predictor.default_buffer_size\n\n frame_data = deque()\n\n for cnt, frame in enumerate(frame_gen):\n frame_data.append(frame)\n self.predictor.put(frame)\n\n if cnt >= buffer_size:\n frame = frame_data.popleft()\n predictions = self.predictor.get()\n yield process_predictions(frame, predictions)\n\n while len(frame_data):\n frame = frame_data.popleft()\n predictions = self.predictor.get()\n yield process_predictions(frame, predictions)\n else:\n for frame in frame_gen:\n yield process_predictions(frame, self.predictor(frame))\n\n\nclass AsyncPredictor:\n \"\"\"\n A predictor that runs the model asynchronously, possibly on >1 GPUs.\n Because rendering the visualization takes considerably amount of time,\n this helps improve throughput when rendering videos.\n \"\"\"\n\n class _StopToken:\n pass\n\n class _PredictWorker(mp.Process):\n def __init__(self, cfg, task_queue, result_queue):\n self.cfg = cfg\n self.task_queue = task_queue\n self.result_queue = result_queue\n super().__init__()\n\n def run(self):\n predictor = DefaultPredictor(self.cfg)\n\n while True:\n task = self.task_queue.get()\n if isinstance(task, AsyncPredictor._StopToken):\n break\n idx, data = task\n result = predictor(data)\n self.result_queue.put((idx, result))\n\n def __init__(self, cfg, num_gpus: int = 1):\n \"\"\"\n Args:\n cfg (CfgNode):\n num_gpus (int): if 0, will run on CPU\n \"\"\"\n num_workers = max(num_gpus, 1)\n self.task_queue = mp.Queue(maxsize=num_workers * 3)\n self.result_queue = mp.Queue(maxsize=num_workers * 3)\n self.procs = []\n for gpuid in range(max(num_gpus, 1)):\n cfg = cfg.clone()\n cfg.defrost()\n cfg.MODEL.DEVICE = \"cuda:{}\".format(gpuid) if num_gpus > 0 else \"cpu\"\n self.procs.append(\n AsyncPredictor._PredictWorker(cfg, self.task_queue, self.result_queue)\n )\n\n self.put_idx = 0\n self.get_idx = 0\n self.result_rank = []\n self.result_data = []\n\n for p in self.procs:\n p.start()\n atexit.register(self.shutdown)\n\n def put(self, image):\n self.put_idx += 1\n self.task_queue.put((self.put_idx, image))\n\n def get(self):\n self.get_idx += 1 # the index needed for this request\n if len(self.result_rank) and self.result_rank[0] == self.get_idx:\n res = self.result_data[0]\n del self.result_data[0], self.result_rank[0]\n return res\n\n while True:\n # make sure the results are returned in the correct order\n idx, res = self.result_queue.get()\n if idx == self.get_idx:\n return res\n insert = bisect.bisect(self.result_rank, idx)\n self.result_rank.insert(insert, idx)\n self.result_data.insert(insert, res)\n\n def __len__(self):\n return self.put_idx - self.get_idx\n\n def __call__(self, image):\n self.put(image)\n return self.get()\n\n def shutdown(self):\n for _ in self.procs:\n self.task_queue.put(AsyncPredictor._StopToken())\n\n @property\n def default_buffer_size(self):\n return len(self.procs) * 5\n"
] |
[
[
"torch.device",
"torch.cuda.device_count"
]
] |
WindQAQ/tensorflow-wavenet
|
[
"3a751b66bfa563da7911e24f58597742799e9f9c"
] |
[
"utils/kaldi_io.py"
] |
[
"#!/usr/bin/env python\n# Copyright 2014-2016 Brno University of Technology (author: Karel Vesely)\n# Licensed under the Apache License, Version 2.0 (the \"License\")\n\nimport numpy as np\nimport os\nimport re\nimport gzip\nimport struct\n\n#################################################\n# Adding kaldi tools to shell path,\n\n# Select kaldi,\nif not 'KALDI_ROOT' in os.environ:\n # Default! To change run python with 'export KALDI_ROOT=/some_dir python'\n os.environ['KALDI_ROOT'] = '/mnt/matylda5/iveselyk/Tools/kaldi-trunk'\n\n# Add kaldi tools to path,\nos.environ['PATH'] = os.popen('echo $KALDI_ROOT/src/bin:$KALDI_ROOT/tools/openfst/bin:$KALDI_ROOT/src/fstbin/:$KALDI_ROOT/src/gmmbin/:$KALDI_ROOT/src/featbin/:$KALDI_ROOT/src/lm/:$KALDI_ROOT/src/sgmmbin/:$KALDI_ROOT/src/sgmm2bin/:$KALDI_ROOT/src/fgmmbin/:$KALDI_ROOT/src/latbin/:$KALDI_ROOT/src/nnetbin:$KALDI_ROOT/src/nnet2bin:$KALDI_ROOT/src/nnet3bin:$KALDI_ROOT/src/online2bin/:$KALDI_ROOT/src/ivectorbin/:$KALDI_ROOT/src/lmbin/').readline().strip() + ':' + os.environ['PATH']\n\n\n#################################################\n# Define all custom exceptions,\nclass UnsupportedDataType(Exception):\n pass\n\n\nclass UnknownVectorHeader(Exception):\n pass\n\n\nclass UnknownMatrixHeader(Exception):\n pass\n\n\nclass BadSampleSize(Exception):\n pass\n\n\nclass BadInputFormat(Exception):\n pass\n\n\n#################################################\n# Data-type independent helper functions,\n\ndef open_or_fd(file, mode='rb'):\n \"\"\" fd = open_or_fd(file)\n Open file, gzipped file, pipe, or forward the file-descriptor.\n Eventually seeks in the 'file' argument contains ':offset' suffix.\n \"\"\"\n offset = None\n try:\n # strip 'ark:' prefix from r{x,w}filename (optional),\n if re.search('^(ark|scp)(,scp|,b|,t|,n?f|,n?p|,b?o|,n?s|,n?cs)*:', file):\n (prefix, file) = file.split(':', 1)\n # separate offset from filename (optional),\n if re.search(':[0-9]+$', file):\n (file, offset) = file.rsplit(':', 1)\n # input pipe?\n if file[-1] == '|':\n fd = os.popen(file[:-1], 'rb')\n # output pipe?\n elif file[0] == '|':\n fd = os.popen(file[1:], 'wb')\n # is it gzipped?\n elif file.split('.')[-1] == 'gz':\n fd = gzip.open(file, mode)\n # a normal file...\n else:\n fd = open(file, mode)\n except TypeError:\n # 'file' is opened file descriptor,\n fd = file\n # Eventually seek to offset,\n if offset != None:\n fd.seek(int(offset))\n return fd\n\n\ndef read_key(fd):\n \"\"\" [str] = read_key(fd)\n Read the utterance-key from the opened ark/stream descriptor 'fd'.\n \"\"\"\n str = ''\n while 1:\n char = fd.read(1)\n if char == '':\n break\n if char == ' ':\n break\n str += char\n str = str.strip()\n if str == '':\n return None # end of file,\n assert(re.match('^[\\.a-zA-Z0-9_-]+$', str) != None) # check format,\n return str\n\n\n#################################################\n# Integer vectors (alignments, ...),\n\ndef read_ali_ark(file_or_fd):\n \"\"\" Alias to 'read_vec_int_ark()' \"\"\"\n return read_vec_int_ark(file_or_fd)\n\n\ndef read_vec_int_ark(file_or_fd):\n \"\"\" generator(key,vec) = read_vec_int_ark(file_or_fd)\n Create generator of (key,vector<int>) tuples, which reads from the ark file/stream.\n file_or_fd : ark, gzipped ark, pipe or opened file descriptor.\n\n Read ark to a 'dictionary':\n d = { u:d for u,d in kaldi_io.read_vec_int_ark(file) }\n \"\"\"\n fd = open_or_fd(file_or_fd)\n try:\n key = read_key(fd)\n while key:\n ali = read_vec_int(fd)\n yield key, ali\n key = read_key(fd)\n finally:\n if fd is not file_or_fd:\n fd.close()\n\n\ndef read_vec_int(file_or_fd):\n \"\"\" [int-vec] = read_vec_int(file_or_fd)\n Read kaldi integer vector, ascii or binary input,\n \"\"\"\n fd = open_or_fd(file_or_fd)\n binary = fd.read(2)\n if binary == '\\0B': # binary flag\n assert(fd.read(1) == '\\4') # int-size\n vec_size = np.fromfile(fd, dtype='int32', count=1)[0] # vector dim\n # Elements from int32 vector are sored in tuples: (sizeof(int32), value),\n vec = np.fromfile(\n fd, dtype=[('size', 'int8'), ('value', 'int32')], count=vec_size)\n assert(vec[0]['size'] == 4) # int32 size,\n ans = vec[:]['value'] # values are in 2nd column,\n else: # ascii,\n arr = (binary + fd.readline()).strip().split()\n try:\n arr.remove('[')\n arr.remove(']') # optionally\n except ValueError:\n pass\n ans = np.array(arr, dtype=int)\n if fd is not file_or_fd:\n fd.close() # cleanup\n return ans\n\n# Writing,\n\n\ndef write_vec_int(file_or_fd, v, key=''):\n \"\"\" write_vec_int(f, v, key='')\n Write a binary kaldi integer vector to filename or stream.\n Arguments:\n file_or_fd : filename or opened file descriptor for writing,\n v : the vector to be stored,\n key (optional) : used for writing ark-file, the utterance-id gets written before the vector.\n\n Example of writing single vector:\n kaldi_io.write_vec_int(filename, vec)\n\n Example of writing arkfile:\n with open(ark_file,'w') as f:\n for key,vec in dict.iteritems():\n kaldi_io.write_vec_flt(f, vec, key=key)\n \"\"\"\n fd = open_or_fd(file_or_fd, mode='wb')\n try:\n if key != '':\n fd.write(key + ' ') # ark-files have keys (utterance-id),\n fd.write('\\0B') # we write binary!\n # dim,\n fd.write('\\4') # int32 type,\n fd.write(struct.pack(np.dtype('int32').char, v.shape[0]))\n # data,\n for i in range(len(v)):\n fd.write('\\4') # int32 type,\n fd.write(struct.pack(np.dtype('int32').char, v[i])) # binary,\n finally:\n if fd is not file_or_fd:\n fd.close()\n\n\n#################################################\n# Float vectors (confidences, ivectors, ...),\n\n# Reading,\ndef read_vec_flt_scp(file_or_fd):\n \"\"\" generator(key,mat) = read_vec_flt_scp(file_or_fd)\n Returns generator of (key,vector) tuples, read according to kaldi scp.\n file_or_fd : scp, gzipped scp, pipe or opened file descriptor.\n\n Iterate the scp:\n for key,vec in kaldi_io.read_vec_flt_scp(file):\n ...\n\n Read scp to a 'dictionary':\n d = { key:mat for key,mat in kaldi_io.read_mat_scp(file) }\n \"\"\"\n fd = open_or_fd(file_or_fd)\n try:\n for line in fd:\n (key, rxfile) = line.split(' ')\n vec = read_vec_flt(rxfile)\n yield key, vec\n finally:\n if fd is not file_or_fd:\n fd.close()\n\n\ndef read_vec_flt_ark(file_or_fd):\n \"\"\" generator(key,vec) = read_vec_flt_ark(file_or_fd)\n Create generator of (key,vector<float>) tuples, reading from an ark file/stream.\n file_or_fd : ark, gzipped ark, pipe or opened file descriptor.\n\n Read ark to a 'dictionary':\n d = { u:d for u,d in kaldi_io.read_vec_flt_ark(file) }\n \"\"\"\n fd = open_or_fd(file_or_fd)\n try:\n key = read_key(fd)\n while key:\n ali = read_vec_flt(fd)\n yield key, ali\n key = read_key(fd)\n finally:\n if fd is not file_or_fd:\n fd.close()\n\n\ndef read_vec_flt(file_or_fd):\n \"\"\" [flt-vec] = read_vec_flt(file_or_fd)\n Read kaldi float vector, ascii or binary input,\n \"\"\"\n fd = open_or_fd(file_or_fd)\n binary = fd.read(2)\n if binary == '\\0B': # binary flag\n # Data type,\n header = fd.read(3)\n if header == 'FV ':\n sample_size = 4 # floats\n elif header == 'DV ':\n sample_size = 8 # doubles\n else:\n raise UnknownVectorHeader(\"The header contained '%s'\" % header)\n assert(sample_size > 0)\n # Dimension,\n assert(fd.read(1) == '\\4') # int-size\n vec_size = np.fromfile(fd, dtype='int32', count=1)[0] # vector dim\n # Read whole vector,\n buf = fd.read(vec_size * sample_size)\n if sample_size == 4:\n ans = np.frombuffer(buf, dtype='float32')\n elif sample_size == 8:\n ans = np.frombuffer(buf, dtype='float64')\n else:\n raise BadSampleSize\n return ans\n else: # ascii,\n arr = (binary + fd.readline()).strip().split()\n try:\n arr.remove('[')\n arr.remove(']') # optionally\n except ValueError:\n pass\n ans = np.array(arr, dtype=float)\n if fd is not file_or_fd:\n fd.close() # cleanup\n return ans\n\n# Writing,\n\n\ndef write_vec_flt(file_or_fd, v, key=''):\n \"\"\" write_vec_flt(f, v, key='')\n Write a binary kaldi vector to filename or stream. Supports 32bit and 64bit floats.\n Arguments:\n file_or_fd : filename or opened file descriptor for writing,\n v : the vector to be stored,\n key (optional) : used for writing ark-file, the utterance-id gets written before the vector.\n\n Example of writing single vector:\n kaldi_io.write_vec_flt(filename, vec)\n\n Example of writing arkfile:\n with open(ark_file,'w') as f:\n for key,vec in dict.iteritems():\n kaldi_io.write_vec_flt(f, vec, key=key)\n \"\"\"\n fd = open_or_fd(file_or_fd, mode='wb')\n try:\n if key != '':\n fd.write(key + ' ') # ark-files have keys (utterance-id),\n fd.write('\\0B') # we write binary!\n # Data-type,\n if v.dtype == 'float32':\n fd.write('FV ')\n elif v.dtype == 'float64':\n fd.write('DV ')\n else:\n raise UnsupportedDataType(\n \"'%s', please use 'float32' or 'float64'\" % v.dtype)\n # Dim,\n fd.write('\\04')\n fd.write(struct.pack(np.dtype('uint32').char, v.shape[0])) # dim\n # Data,\n v.tofile(fd, sep=\"\") # binary\n finally:\n if fd is not file_or_fd:\n fd.close()\n\n\n#################################################\n# Float matrices (features, transformations, ...),\n\n# Reading,\ndef read_mat_scp(file_or_fd):\n \"\"\" generator(key,mat) = read_mat_scp(file_or_fd)\n Returns generator of (key,matrix) tuples, read according to kaldi scp.\n file_or_fd : scp, gzipped scp, pipe or opened file descriptor.\n\n Iterate the scp:\n for key,mat in kaldi_io.read_mat_scp(file):\n ...\n\n Read scp to a 'dictionary':\n d = { key:mat for key,mat in kaldi_io.read_mat_scp(file) }\n \"\"\"\n fd = open_or_fd(file_or_fd)\n try:\n for line in fd:\n (key, rxfile) = line.decode().strip('\\r\\n').split(' ')\n mat = read_mat(rxfile)\n yield key, mat\n finally:\n if fd is not file_or_fd:\n fd.close()\n\n\ndef read_mat_ark(file_or_fd):\n \"\"\" generator(key,mat) = read_mat_ark(file_or_fd)\n Returns generator of (key,matrix) tuples, read from ark file/stream.\n file_or_fd : scp, gzipped scp, pipe or opened file descriptor.\n\n Iterate the ark:\n for key,mat in kaldi_io.read_mat_ark(file):\n ...\n\n Read ark to a 'dictionary':\n d = { key:mat for key,mat in kaldi_io.read_mat_ark(file) }\n \"\"\"\n fd = open_or_fd(file_or_fd)\n try:\n key = read_key(fd)\n while key:\n mat = read_mat(fd)\n yield key, mat\n key = read_key(fd)\n finally:\n if fd is not file_or_fd:\n fd.close()\n\n\ndef read_mat(file_or_fd):\n \"\"\" [mat] = read_mat(file_or_fd)\n Reads single kaldi matrix, supports ascii and binary.\n file_or_fd : file, gzipped file, pipe or opened file descriptor.\n \"\"\"\n fd = open_or_fd(file_or_fd)\n try:\n binary = fd.read(2)\n if binary == '\\0B':\n mat = _read_mat_binary(fd)\n else:\n assert(binary == b' [')\n mat = _read_mat_ascii(fd)\n finally:\n if fd is not file_or_fd:\n fd.close()\n return mat\n\n\ndef _read_mat_binary(fd):\n # Data type\n header = fd.read(3)\n # 'CM', 'CM2', 'CM3' are possible values,\n if header.startswith('CM'):\n return _read_compressed_mat(fd, header)\n elif header == 'FM ':\n sample_size = 4 # floats\n elif header == 'DM ':\n sample_size = 8 # doubles\n else:\n raise UnknownMatrixHeader(\"The header contained '%s'\" % header)\n assert(sample_size > 0)\n # Dimensions\n s1, rows, s2, cols = np.fromfile(\n fd, dtype='int8,int32,int8,int32', count=1)[0]\n # Read whole matrix\n buf = fd.read(rows * cols * sample_size)\n if sample_size == 4:\n vec = np.frombuffer(buf, dtype='float32')\n elif sample_size == 8:\n vec = np.frombuffer(buf, dtype='float64')\n else:\n raise BadSampleSize\n mat = np.reshape(vec, (rows, cols))\n return mat\n\n\ndef _read_mat_ascii(fd):\n rows = []\n while 1:\n line = fd.readline()\n if (len(line) == 0):\n raise BadInputFormat # eof, should not happen!\n if len(line.strip()) == 0:\n continue # skip empty line\n arr = line.decode().strip().split()\n if arr[-1] != ']':\n rows.append(np.array(arr, dtype='float32')) # not last line\n else:\n rows.append(np.array(arr[:-1], dtype='float32')) # last line\n mat = np.vstack(rows)\n return mat\n\n\ndef _read_compressed_mat(fd, format):\n \"\"\" Read a compressed matrix,\n see: https://github.com/kaldi-asr/kaldi/blob/master/src/matrix/compressed-matrix.h\n methods: CompressedMatrix::Read(...), CompressedMatrix::CopyToMat(...),\n \"\"\"\n assert(format == 'CM ') # The formats CM2, CM3 are not supported...\n\n # Format of header 'struct',\n global_header = np.dtype([('minvalue', 'float32'), ('range', 'float32'), (\n 'num_rows', 'int32'), ('num_cols', 'int32')]) # member '.format' is not written,\n per_col_header = np.dtype([('percentile_0', 'uint16'), ('percentile_25',\n 'uint16'), ('percentile_75', 'uint16'), ('percentile_100', 'uint16')])\n\n # Mapping for percentiles in col-headers,\n def uint16_to_float(value, min, range):\n return np.float32(min + range * 1.52590218966964e-05 * value)\n\n # Mapping for matrix elements,\n def uint8_to_float_v2(vec, p0, p25, p75, p100):\n # Split the vector by masks,\n mask_0_64 = (vec <= 64)\n mask_65_192 = np.all([vec > 64, vec <= 192], axis=0)\n mask_193_255 = (vec > 192)\n # Sanity check (useful but slow...),\n # assert(len(vec) == np.sum(np.hstack([mask_0_64,mask_65_192,mask_193_255])))\n # assert(len(vec) == np.sum(np.any([mask_0_64,mask_65_192,mask_193_255], axis=0)))\n # Build the float vector,\n ans = np.empty(len(vec), dtype='float32')\n ans[mask_0_64] = p0 + (p25 - p0) / 64. * vec[mask_0_64]\n ans[mask_65_192] = p25 + (p75 - p25) / 128. * (vec[mask_65_192] - 64)\n ans[mask_193_255] = p75 + (p100 - p75) / \\\n 63. * (vec[mask_193_255] - 192)\n return ans\n\n # Read global header,\n globmin, globrange, rows, cols = np.fromfile(\n fd, dtype=global_header, count=1)[0]\n\n # The data is structed as [Colheader, ... , Colheader, Data, Data , .... ]\n # { cols }{ size }\n col_headers = np.fromfile(fd, dtype=per_col_header, count=cols)\n data = np.reshape(np.fromfile(fd, dtype='uint8', count=cols * rows),\n newshape=(cols, rows)) # stored as col-major,\n\n mat = np.empty((cols, rows), dtype='float32')\n for i, col_header in enumerate(col_headers):\n col_header_flt = [uint16_to_float(\n percentile, globmin, globrange) for percentile in col_header]\n mat[i] = uint8_to_float_v2(data[i], *col_header_flt)\n\n return mat.T # transpose! col-major -> row-major,\n\n\n# Writing,\ndef write_mat(file_or_fd, m, key=''):\n \"\"\" write_mat(f, m, key='')\n Write a binary kaldi matrix to filename or stream. Supports 32bit and 64bit floats.\n Arguments:\n file_or_fd : filename of opened file descriptor for writing,\n m : the matrix to be stored,\n key (optional) : used for writing ark-file, the utterance-id gets written before the matrix.\n\n Example of writing single matrix:\n kaldi_io.write_mat(filename, mat)\n\n Example of writing arkfile:\n with open(ark_file,'w') as f:\n for key,mat in dict.iteritems():\n kaldi_io.write_mat(f, mat, key=key)\n \"\"\"\n fd = open_or_fd(file_or_fd, mode='wb')\n try:\n if key != '':\n fd.write(key + ' ') # ark-files have keys (utterance-id),\n fd.write('\\0B') # we write binary!\n # Data-type,\n if m.dtype == 'float32':\n fd.write('FM ')\n elif m.dtype == 'float64':\n fd.write('DM ')\n else:\n raise UnsupportedDataType(\n \"'%s', please use 'float32' or 'float64'\" % v.dtype)\n # Dims,\n fd.write('\\04')\n fd.write(struct.pack(np.dtype('uint32').char, m.shape[0])) # rows\n fd.write('\\04')\n fd.write(struct.pack(np.dtype('uint32').char, m.shape[1])) # cols\n # Data,\n m.tofile(fd, sep=\"\") # binary\n finally:\n if fd is not file_or_fd:\n fd.close()\n\n\n#################################################\n# 'Posterior' kaldi type (posteriors, confusion network, nnet1 training targets, ...)\n# Corresponds to: vector<vector<tuple<int,float> > >\n# - outer vector: time axis\n# - inner vector: records at the time\n# - tuple: int = index, float = value\n#\n\ndef read_cnet_ark(file_or_fd):\n \"\"\" Alias of function 'read_post_ark()', 'cnet' = confusion network \"\"\"\n return read_post_ark(file_or_fd)\n\n\ndef read_post_ark(file_or_fd):\n \"\"\" generator(key,vec<vec<int,float>>) = read_post_ark(file)\n Returns generator of (key,posterior) tuples, read from ark file.\n file_or_fd : ark, gzipped ark, pipe or opened file descriptor.\n\n Iterate the ark:\n for key,post in kaldi_io.read_post_ark(file):\n ...\n\n Read ark to a 'dictionary':\n d = { key:post for key,post in kaldi_io.read_post_ark(file) }\n \"\"\"\n fd = open_or_fd(file_or_fd)\n try:\n key = read_key(fd)\n while key:\n post = read_post(fd)\n yield key, post\n key = read_key(fd)\n finally:\n if fd is not file_or_fd:\n fd.close()\n\n\ndef read_post(file_or_fd):\n \"\"\" [post] = read_post(file_or_fd)\n Reads single kaldi 'Posterior' in binary format.\n\n The 'Posterior' is C++ type 'vector<vector<tuple<int,float> > >',\n the outer-vector is usually time axis, inner-vector are the records\n at given time, and the tuple is composed of an 'index' (integer)\n and a 'float-value'. The 'float-value' can represent a probability\n or any other numeric value.\n\n Returns vector of vectors of tuples.\n \"\"\"\n fd = open_or_fd(file_or_fd)\n ans = []\n binary = fd.read(2)\n assert(binary == '\\0B') # binary flag\n assert(fd.read(1) == '\\4') # int-size\n outer_vec_size = np.fromfile(fd, dtype='int32', count=1)[\n 0] # number of frames (or bins)\n\n # Loop over 'outer-vector',\n for i in range(outer_vec_size):\n assert(fd.read(1) == '\\4') # int-size\n inner_vec_size = np.fromfile(fd, dtype='int32', count=1)[\n 0] # number of records for frame (or bin)\n data = np.fromfile(fd, dtype=[('size_idx', 'int8'), ('idx', 'int32'), (\n 'size_post', 'int8'), ('post', 'float32')], count=inner_vec_size)\n assert(data[0]['size_idx'] == 4)\n assert(data[0]['size_post'] == 4)\n ans.append(data[['idx', 'post']].tolist())\n\n if fd is not file_or_fd:\n fd.close()\n return ans\n\n\n#################################################\n# Kaldi Confusion Network bin begin/end times,\n# (kaldi stores CNs time info separately from the Posterior).\n#\n\ndef read_cntime_ark(file_or_fd):\n \"\"\" generator(key,vec<tuple<float,float>>) = read_cntime_ark(file_or_fd)\n Returns generator of (key,cntime) tuples, read from ark file.\n file_or_fd : file, gzipped file, pipe or opened file descriptor.\n\n Iterate the ark:\n for key,time in kaldi_io.read_cntime_ark(file):\n ...\n\n Read ark to a 'dictionary':\n d = { key:time for key,time in kaldi_io.read_post_ark(file) }\n \"\"\"\n fd = open_or_fd(file_or_fd)\n try:\n key = read_key(fd)\n while key:\n cntime = read_cntime(fd)\n yield key, cntime\n key = read_key(fd)\n finally:\n if fd is not file_or_fd:\n fd.close()\n\n\ndef read_cntime(file_or_fd):\n \"\"\" [cntime] = read_cntime(file_or_fd)\n Reads single kaldi 'Confusion Network time info', in binary format:\n C++ type: vector<tuple<float,float> >.\n (begin/end times of bins at the confusion network).\n\n Binary layout is '<num-bins> <beg1> <end1> <beg2> <end2> ...'\n\n file_or_fd : file, gzipped file, pipe or opened file descriptor.\n\n Returns vector of tuples.\n \"\"\"\n fd = open_or_fd(file_or_fd)\n binary = fd.read(2)\n assert(binary == '\\0B') # assuming it's binary\n\n assert(fd.read(1) == '\\4') # int-size\n vec_size = np.fromfile(fd, dtype='int32', count=1)[\n 0] # number of frames (or bins)\n\n data = np.fromfile(fd, dtype=[('size_beg', 'int8'), ('t_beg', 'float32'), (\n 'size_end', 'int8'), ('t_end', 'float32')], count=vec_size)\n assert(data[0]['size_beg'] == 4)\n assert(data[0]['size_end'] == 4)\n # Return vector of tuples (t_beg,t_end),\n ans = data[['t_beg', 't_end']].tolist()\n\n if fd is not file_or_fd:\n fd.close()\n return ans\n\n\n#################################################\n# Segments related,\n#\n\n# Segments as 'Bool vectors' can be handy,\n# - for 'superposing' the segmentations,\n# - for frame-selection in Speaker-ID experiments,\ndef read_segments_as_bool_vec(segments_file):\n \"\"\" [ bool_vec ] = read_segments_as_bool_vec(segments_file)\n using kaldi 'segments' file for 1 wav, format : '<utt> <rec> <t-beg> <t-end>'\n - t-beg, t-end is in seconds,\n - assumed 100 frames/second,\n \"\"\"\n segs = np.loadtxt(segments_file, dtype='object,object,f,f', ndmin=1)\n # Sanity checks,\n assert(len(segs) > 0) # empty segmentation is an error,\n # segments with only 1 wav-file,\n assert(len(np.unique([rec[1] for rec in segs])) == 1)\n # Convert time to frame-indexes,\n start = np.rint([100 * rec[2] for rec in segs]).astype(int)\n end = np.rint([100 * rec[3] for rec in segs]).astype(int)\n # Taken from 'read_lab_to_bool_vec', htk.py,\n frms = np.repeat(np.r_[np.tile([False, True], len(end)), False],\n np.r_[np.c_[start - np.r_[0, end[:-1]], end - start].flat, 0])\n assert np.sum(end - start) == np.sum(frms)\n return frms\n"
] |
[
[
"numpy.fromfile",
"numpy.unique",
"numpy.reshape",
"numpy.vstack",
"numpy.rint",
"numpy.empty",
"numpy.dtype",
"numpy.all",
"numpy.frombuffer",
"numpy.float32",
"numpy.array",
"numpy.sum",
"numpy.loadtxt"
]
] |
flyudvik/ray
|
[
"4888d7c9af6a62ea5b1bedd8a56ed95529408bb4"
] |
[
"python/ray/tests/test_reference_counting_2.py"
] |
[
"# coding: utf-8\nimport logging\nimport os\nimport platform\nimport random\nimport signal\nimport sys\nimport time\n\nimport numpy as np\n\nimport pytest\n\nimport ray\nimport ray.cluster_utils\nfrom ray.internal.internal_api import memory_summary\nfrom ray._private.test_utils import SignalActor, put_object, wait_for_condition\n\nSIGKILL = signal.SIGKILL if sys.platform != \"win32\" else signal.SIGTERM\n\nlogger = logging.getLogger(__name__)\n\n\[email protected]\ndef one_worker_100MiB(request):\n config = {\n \"task_retry_delay_ms\": 0,\n \"object_timeout_milliseconds\": 1000,\n \"automatic_object_spilling_enabled\": False\n }\n yield ray.init(\n num_cpus=1,\n object_store_memory=100 * 1024 * 1024,\n _system_config=config)\n ray.shutdown()\n\n\ndef _fill_object_store_and_get(obj, succeed=True, object_MiB=20,\n num_objects=5):\n for _ in range(num_objects):\n ray.put(np.zeros(object_MiB * 1024 * 1024, dtype=np.uint8))\n\n if type(obj) is bytes:\n obj = ray.ObjectRef(obj)\n\n if succeed:\n wait_for_condition(\n lambda: ray.worker.global_worker.core_worker.object_exists(obj))\n else:\n wait_for_condition(\n lambda: not ray.worker.global_worker.core_worker.object_exists(obj)\n )\n\n\n# Test that an object containing object refs within it pins the inner IDs\n# recursively and for submitted tasks.\[email protected](\"use_ray_put,failure\", [(False, False), (False, True),\n (True, False), (True, True)])\ndef test_recursively_nest_ids(one_worker_100MiB, use_ray_put, failure):\n @ray.remote(max_retries=1)\n def recursive(ref, signal, max_depth, depth=0):\n unwrapped = ray.get(ref[0])\n if depth == max_depth:\n ray.get(signal.wait.remote())\n if failure:\n os._exit(0)\n return\n else:\n return recursive.remote(unwrapped, signal, max_depth, depth + 1)\n\n signal = SignalActor.remote()\n\n max_depth = 5\n array_oid = put_object(\n np.zeros(20 * 1024 * 1024, dtype=np.uint8), use_ray_put)\n nested_oid = array_oid\n for _ in range(max_depth):\n nested_oid = ray.put([nested_oid])\n head_oid = recursive.remote([nested_oid], signal, max_depth)\n\n # Remove the local reference.\n array_oid_bytes = array_oid.binary()\n del array_oid, nested_oid\n\n tail_oid = head_oid\n for _ in range(max_depth):\n tail_oid = ray.get(tail_oid)\n\n # Check that the remote reference pins the object.\n _fill_object_store_and_get(array_oid_bytes)\n\n # Fulfill the dependency, causing the tail task to finish.\n ray.get(signal.send.remote())\n try:\n ray.get(tail_oid)\n assert not failure\n # TODO(edoakes): this should raise WorkerError.\n except ray.exceptions.ObjectLostError:\n assert failure\n\n # Reference should be gone, check that array gets evicted.\n _fill_object_store_and_get(array_oid_bytes, succeed=False)\n\n\n# Test that serialized ObjectRefs returned from remote tasks are pinned until\n# they go out of scope on the caller side.\[email protected](sys.platform == \"win32\", reason=\"Failing on Windows.\")\[email protected](\"use_ray_put,failure\", [(False, False), (False, True),\n (True, False), (True, True)])\ndef test_return_object_ref(one_worker_100MiB, use_ray_put, failure):\n @ray.remote\n def return_an_id():\n return [\n put_object(\n np.zeros(20 * 1024 * 1024, dtype=np.uint8), use_ray_put)\n ]\n\n @ray.remote(max_retries=1)\n def exit():\n os._exit(0)\n\n outer_oid = return_an_id.remote()\n inner_oid_binary = ray.get(outer_oid)[0].binary()\n\n # Check that taking a reference to the inner ID and removing the outer ID\n # doesn't unpin the object.\n inner_oid = ray.get(outer_oid)[0] # noqa: F841\n del outer_oid\n _fill_object_store_and_get(inner_oid_binary)\n\n if failure:\n # Check that the owner dying unpins the object. This should execute on\n # the same worker because there is only one started and the other tasks\n # have finished.\n with pytest.raises(ray.exceptions.WorkerCrashedError):\n ray.get(exit.remote())\n else:\n # Check that removing the inner ID unpins the object.\n del inner_oid\n _fill_object_store_and_get(inner_oid_binary, succeed=False)\n\n\n# Test that serialized ObjectRefs returned from remote tasks are pinned if\n# passed into another remote task by the caller.\[email protected](\"use_ray_put,failure\", [(False, False), (False, True),\n (True, False), (True, True)])\ndef test_pass_returned_object_ref(one_worker_100MiB, use_ray_put, failure):\n @ray.remote\n def return_an_id():\n return [\n put_object(\n np.zeros(20 * 1024 * 1024, dtype=np.uint8), use_ray_put)\n ]\n\n # TODO(edoakes): this fails with an ActorError with max_retries=1.\n @ray.remote(max_retries=0)\n def pending(ref, signal):\n ray.get(signal.wait.remote())\n ray.get(ref[0])\n if failure:\n os._exit(0)\n\n signal = SignalActor.remote()\n outer_oid = return_an_id.remote()\n inner_oid_binary = ray.get(outer_oid)[0].binary()\n pending_oid = pending.remote([outer_oid], signal)\n\n # Remove the local reference to the returned ID.\n del outer_oid\n\n # Check that the inner ID is pinned by the remote task ID and finishing\n # the task unpins the object.\n ray.get(signal.send.remote())\n try:\n # Should succeed because inner_oid is pinned if no failure.\n ray.get(pending_oid)\n assert not failure\n except ray.exceptions.WorkerCrashedError:\n assert failure\n\n def ref_not_exists():\n worker = ray.worker.global_worker\n inner_oid = ray.ObjectRef(inner_oid_binary)\n return not worker.core_worker.object_exists(inner_oid)\n\n wait_for_condition(ref_not_exists)\n\n\n# Call a recursive chain of tasks that pass a serialized reference that was\n# returned by another task to the end of the chain. The reference should still\n# exist while the final task in the chain is running and should be removed once\n# it finishes.\[email protected](\"use_ray_put,failure\", [(False, False), (False, True),\n (True, False), (True, True)])\ndef test_recursively_pass_returned_object_ref(one_worker_100MiB, use_ray_put,\n failure):\n @ray.remote\n def return_an_id():\n return put_object(\n np.zeros(20 * 1024 * 1024, dtype=np.uint8), use_ray_put)\n\n @ray.remote(max_retries=1)\n def recursive(ref, signal, max_depth, depth=0):\n inner_id = ray.get(ref[0])\n if depth == max_depth:\n ray.get(signal.wait.remote())\n if failure:\n os._exit(0)\n return inner_id\n else:\n return inner_id, recursive.remote(ref, signal, max_depth,\n depth + 1)\n\n max_depth = 5\n outer_oid = return_an_id.remote()\n signal = SignalActor.remote()\n head_oid = recursive.remote([outer_oid], signal, max_depth)\n\n # Remove the local reference.\n inner_oid = None\n outer_oid = head_oid\n for i in range(max_depth):\n inner_oid, outer_oid = ray.get(outer_oid)\n\n # Check that the remote reference pins the object.\n _fill_object_store_and_get(outer_oid, succeed=False)\n\n # Fulfill the dependency, causing the tail task to finish.\n ray.get(signal.send.remote())\n\n try:\n # Check that the remote reference pins the object.\n ray.get(outer_oid)\n _fill_object_store_and_get(inner_oid)\n assert not failure\n # TODO(edoakes): this should raise WorkerError.\n except ray.exceptions.ObjectLostError:\n assert failure\n\n inner_oid_bytes = inner_oid.binary()\n del inner_oid\n del head_oid\n del outer_oid\n\n # Reference should be gone, check that returned ID gets evicted.\n _fill_object_store_and_get(inner_oid_bytes, succeed=False)\n\n\n# Call a recursive chain of tasks. The final task in the chain returns an\n# ObjectRef returned by a task that it submitted. Every other task in the chain\n# returns the same ObjectRef by calling ray.get() on its submitted task and\n# returning the result. The reference should still exist while the driver has a\n# reference to the final task's ObjectRef.\[email protected](sys.platform == \"win32\", reason=\"Failing on Windows.\")\[email protected](\"use_ray_put,failure\", [(False, False), (False, True),\n (True, False), (True, True)])\ndef test_recursively_return_borrowed_object_ref(one_worker_100MiB, use_ray_put,\n failure):\n @ray.remote\n def recursive(num_tasks_left):\n if num_tasks_left == 0:\n return put_object(\n np.zeros(20 * 1024 * 1024, dtype=np.uint8),\n use_ray_put), os.getpid()\n\n return ray.get(recursive.remote(num_tasks_left - 1))\n\n max_depth = 5\n head_oid = recursive.remote(max_depth)\n final_oid, owner_pid = ray.get(head_oid)\n final_oid_bytes = final_oid.binary()\n\n # Check that the driver's reference pins the object.\n _fill_object_store_and_get(final_oid_bytes)\n\n # Remove the local reference and try it again.\n _fill_object_store_and_get(final_oid_bytes)\n\n if failure:\n os.kill(owner_pid, SIGKILL)\n else:\n # Remove all references.\n del head_oid\n del final_oid\n\n # Reference should be gone, check that returned ID gets evicted.\n _fill_object_store_and_get(final_oid_bytes, succeed=False)\n\n\[email protected](\"failure\", [False, True])\ndef test_borrowed_id_failure(one_worker_100MiB, failure):\n @ray.remote\n class Parent:\n def __init__(self):\n pass\n\n def pass_ref(self, ref, borrower):\n self.ref = ref[0]\n ray.get(borrower.receive_ref.remote(ref))\n if failure:\n sys.exit(-1)\n\n def ping(self):\n return\n\n @ray.remote\n class Borrower:\n def __init__(self):\n self.ref = None\n\n def receive_ref(self, ref):\n self.ref = ref[0]\n\n def resolve_ref(self):\n assert self.ref is not None\n if failure:\n with pytest.raises(ray.exceptions.ObjectLostError):\n ray.get(self.ref)\n else:\n ray.get(self.ref)\n\n def ping(self):\n return\n\n parent = Parent.remote()\n borrower = Borrower.remote()\n ray.get(borrower.ping.remote())\n\n obj = ray.put(np.zeros(20 * 1024 * 1024, dtype=np.uint8))\n if failure:\n with pytest.raises(ray.exceptions.RayActorError):\n ray.get(parent.pass_ref.remote([obj], borrower))\n else:\n ray.get(parent.pass_ref.remote([obj], borrower))\n obj_bytes = obj.binary()\n del obj\n\n _fill_object_store_and_get(obj_bytes, succeed=not failure)\n # The borrower should not hang when trying to get the object's value.\n ray.get(borrower.resolve_ref.remote())\n\n\[email protected](\n platform.system() in [\"Windows\"], reason=\"Failing on Windows.\")\ndef test_object_unpin(ray_start_cluster):\n nodes = []\n cluster = ray_start_cluster\n head_node = cluster.add_node(\n num_cpus=0,\n object_store_memory=100 * 1024 * 1024,\n _system_config={\n \"num_heartbeats_timeout\": 10,\n \"subscriber_timeout_ms\": 100\n })\n ray.init(address=cluster.address)\n\n # Add worker nodes.\n for i in range(2):\n nodes.append(\n cluster.add_node(\n num_cpus=1,\n resources={f\"node_{i}\": 1},\n object_store_memory=100 * 1024 * 1024))\n cluster.wait_for_nodes()\n\n one_mb_array = np.ones(1 * 1024 * 1024, dtype=np.uint8)\n ten_mb_array = np.ones(10 * 1024 * 1024, dtype=np.uint8)\n\n @ray.remote\n class ObjectsHolder:\n def __init__(self):\n self.ten_mb_objs = []\n self.one_mb_objs = []\n\n def put_10_mb(self):\n self.ten_mb_objs.append(ray.put(ten_mb_array))\n\n def put_1_mb(self):\n self.one_mb_objs.append(ray.put(one_mb_array))\n\n def pop_10_mb(self):\n if len(self.ten_mb_objs) == 0:\n return False\n self.ten_mb_objs.pop()\n return True\n\n def pop_1_mb(self):\n if len(self.one_mb_objs) == 0:\n return False\n self.one_mb_objs.pop()\n return True\n\n # Head node contains 11MB of data.\n one_mb_arrays = []\n ten_mb_arrays = []\n\n one_mb_arrays.append(ray.put(one_mb_array))\n ten_mb_arrays.append(ray.put(ten_mb_array))\n\n def check_memory(mb):\n return ((f\"Plasma memory usage {mb} \"\n \"MiB\" in memory_summary(\n address=head_node.address, stats_only=True)))\n\n def wait_until_node_dead(node):\n for n in ray.nodes():\n if (n[\"ObjectStoreSocketName\"] == node.address_info[\n \"object_store_address\"]):\n return not n[\"Alive\"]\n return False\n\n wait_for_condition(lambda: check_memory(11))\n\n # Pop one mb array and see if it works.\n one_mb_arrays.pop()\n wait_for_condition(lambda: check_memory(10))\n\n # Pop 10 MB.\n ten_mb_arrays.pop()\n wait_for_condition(lambda: check_memory(0))\n\n # Put 11 MB for each actor.\n # actor 1: 1MB + 10MB\n # actor 2: 1MB + 10MB\n actor_on_node_1 = ObjectsHolder.options(resources={\"node_0\": 1}).remote()\n actor_on_node_2 = ObjectsHolder.options(resources={\"node_1\": 1}).remote()\n ray.get(actor_on_node_1.put_1_mb.remote())\n ray.get(actor_on_node_1.put_10_mb.remote())\n ray.get(actor_on_node_2.put_1_mb.remote())\n ray.get(actor_on_node_2.put_10_mb.remote())\n wait_for_condition(lambda: check_memory(22))\n\n # actor 1: 10MB\n # actor 2: 1MB\n ray.get(actor_on_node_1.pop_1_mb.remote())\n ray.get(actor_on_node_2.pop_10_mb.remote())\n wait_for_condition(lambda: check_memory(11))\n\n # The second node is dead, and actor 2 is dead.\n cluster.remove_node(nodes[1], allow_graceful=False)\n wait_for_condition(lambda: wait_until_node_dead(nodes[1]))\n wait_for_condition(lambda: check_memory(10))\n\n # The first actor is dead, so object should be GC'ed.\n ray.kill(actor_on_node_1)\n wait_for_condition(lambda: check_memory(0))\n\n\[email protected](\n platform.system() in [\"Windows\"], reason=\"Failing on Windows.\")\ndef test_object_unpin_stress(ray_start_cluster):\n nodes = []\n cluster = ray_start_cluster\n cluster.add_node(\n num_cpus=1,\n resources={\"head\": 1},\n object_store_memory=1000 * 1024 * 1024)\n ray.init(address=cluster.address)\n\n # Add worker nodes.\n for i in range(2):\n nodes.append(\n cluster.add_node(\n num_cpus=1,\n resources={f\"node_{i}\": 1},\n object_store_memory=1000 * 1024 * 1024))\n cluster.wait_for_nodes()\n\n one_mb_array = np.ones(1 * 1024 * 1024, dtype=np.uint8)\n ten_mb_array = np.ones(10 * 1024 * 1024, dtype=np.uint8)\n\n @ray.remote\n class ObjectsHolder:\n def __init__(self):\n self.ten_mb_objs = []\n self.one_mb_objs = []\n\n def put_10_mb(self):\n self.ten_mb_objs.append(ray.put(ten_mb_array))\n\n def put_1_mb(self):\n self.one_mb_objs.append(ray.put(one_mb_array))\n\n def pop_10_mb(self):\n if len(self.ten_mb_objs) == 0:\n return False\n self.ten_mb_objs.pop()\n return True\n\n def pop_1_mb(self):\n if len(self.one_mb_objs) == 0:\n return False\n self.one_mb_objs.pop()\n return True\n\n def get_obj_size(self):\n return len(self.ten_mb_objs) * 10 + len(self.one_mb_objs)\n\n actor_on_node_1 = ObjectsHolder.options(resources={\"node_0\": 1}).remote()\n actor_on_node_2 = ObjectsHolder.options(resources={\"node_1\": 1}).remote()\n actor_on_head_node = ObjectsHolder.options(resources={\"head\": 1}).remote()\n\n ray.get(actor_on_node_1.get_obj_size.remote())\n ray.get(actor_on_node_2.get_obj_size.remote())\n ray.get(actor_on_head_node.get_obj_size.remote())\n\n def random_ops(actors):\n r = random.random()\n for actor in actors:\n if r <= .25:\n actor.put_10_mb.remote()\n elif r <= .5:\n actor.put_1_mb.remote()\n elif r <= .75:\n actor.pop_10_mb.remote()\n else:\n actor.pop_1_mb.remote()\n\n total_iter = 15\n for _ in range(total_iter):\n random_ops([actor_on_node_1, actor_on_node_2, actor_on_head_node])\n\n # Simulate node dead.\n cluster.remove_node(nodes[1])\n for _ in range(total_iter):\n random_ops([actor_on_node_1, actor_on_head_node])\n\n total_size = sum([\n ray.get(actor_on_node_1.get_obj_size.remote()),\n ray.get(actor_on_head_node.get_obj_size.remote())\n ])\n\n wait_for_condition(lambda: ((f\"Plasma memory usage {total_size}\"\n \" MiB\") in memory_summary(stats_only=True)))\n\n\[email protected](\"inline_args\", [True, False])\ndef test_inlined_nested_refs(ray_start_cluster, inline_args):\n cluster = ray_start_cluster\n config = {}\n if not inline_args:\n config[\"max_direct_call_object_size\"] = 0\n cluster.add_node(\n num_cpus=2,\n object_store_memory=100 * 1024 * 1024,\n _system_config=config)\n ray.init(address=cluster.address)\n\n @ray.remote\n class Actor:\n def __init__(self):\n return\n\n def nested(self):\n return ray.put(\"x\")\n\n @ray.remote\n def nested_nested(a):\n return a.nested.remote()\n\n @ray.remote\n def foo(ref):\n time.sleep(1)\n return ray.get(ref)\n\n a = Actor.remote()\n nested_nested_ref = nested_nested.remote(a)\n # We get nested_ref's value directly from its owner.\n nested_ref = ray.get(nested_nested_ref)\n\n del nested_nested_ref\n x = foo.remote(nested_ref)\n del nested_ref\n ray.get(x)\n\n\n# https://github.com/ray-project/ray/issues/17553\[email protected](\"inline_args\", [True, False])\ndef test_return_nested_ids(shutdown_only, inline_args):\n config = dict()\n if inline_args:\n config[\"max_direct_call_object_size\"] = 100 * 1024 * 1024\n else:\n config[\"max_direct_call_object_size\"] = 0\n ray.init(object_store_memory=100 * 1024 * 1024, _system_config=config)\n\n class Nested:\n def __init__(self, blocks):\n self._blocks = blocks\n\n @ray.remote\n def echo(fn):\n return fn()\n\n @ray.remote\n def create_nested():\n refs = [ray.put(np.random.random(1024 * 1024)) for _ in range(10)]\n return Nested(refs)\n\n @ray.remote\n def test():\n ref = create_nested.remote()\n result1 = ray.get(ref)\n del ref\n result = echo.remote(lambda: result1) # noqa\n del result1\n\n time.sleep(5)\n block = ray.get(result)._blocks[0]\n print(ray.get(block))\n\n ray.get(test.remote())\n\n\nif __name__ == \"__main__\":\n import sys\n sys.exit(pytest.main([\"-v\", __file__]))\n"
] |
[
[
"numpy.random.random",
"numpy.zeros",
"numpy.ones"
]
] |
jattenberg/datascience-utilities
|
[
"b2b543696af6ea8c5731970d15f3ddd2b3c2985a"
] |
[
"datascience_utilities/describe.py"
] |
[
"#!/usr/local/bin/python\n\"\"\"\nCopyright (c) 2013 Josh Attenberg\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\n\n\nfrom scipy.stats import stats, normaltest, sem, bayes_mvs\nimport sys\nfrom optparse import OptionParser\nimport numpy as np\nimport pandas as pd\nfrom math import log\n\nfrom .utils import select_columns\n\n\ndef get_nonnumeric(column, np_values):\n\n data = np_values.describe()\n output = [present(\"Column\", column)]\n for id in data.index:\n output.append(present(id.capitalize(), data[id]))\n return output\n\n\ndef get_data(column, np_values, options):\n\n alpha = float(options.alpha)\n mvs = bayes_mvs(np_values, alpha)\n\n # report these metrics\n output = [\n present(\"Column\", column),\n present(\"Length\", len(np_values)),\n present(\"Unique\", len(np.unique(np_values))),\n present(\"Min\", np_values.min()),\n present(\"Max\", np_values.max()),\n present(\"Sum\", np_values.sum()),\n present(\"Mid-Range\", (np_values.max() - np_values.min()) / 2),\n present(\"Range\", np_values.max() - np_values.min()),\n present(\"Mean\", np_values.mean()),\n present(\"Mean-%s-CI\" % alpha, tupleToString(mvs[0][1])),\n present(\"Variance\", mvs[1][0]),\n present(\"Var-%s-CI\" % alpha, tupleToString(mvs[1][1])),\n present(\"StdDev\", mvs[2][0]),\n present(\"Std-%s-CI\" % alpha, tupleToString(mvs[2][1])),\n present(\"Mode\", stats.mode(np_values)[0][0]),\n present(\"Q1\", stats.scoreatpercentile(np_values, 25)),\n present(\"Q2\", stats.scoreatpercentile(np_values, 50)),\n present(\"Q3\", stats.scoreatpercentile(np_values, 75)),\n present(\"Trimean\", trimean(np_values)),\n present(\"Minhinge\", midhinge(np_values)),\n present(\"Skewness\", stats.skew(np_values)),\n present(\"Kurtosis\", stats.kurtosis(np_values)),\n present(\"StdErr\", sem(np_values)),\n present(\"Normal-P-value\", normaltest(np_values)[1]),\n ]\n return output\n\n\n# this prints a bit nicer than tuples standard toString\ndef tupleToString(tuple):\n return \"(%s, %s)\" % tuple\n\n\ndef present(key, value):\n return key + \" : \" + str(value)\n\n\ndef trimean(values):\n return (\n stats.scoreatpercentile(values, 25)\n + 2.0 * stats.scoreatpercentile(values, 50)\n + stats.scoreatpercentile(values, 75)\n ) / 4.0\n\n\ndef midhinge(values):\n return (\n stats.scoreatpercentile(values, 25) + stats.scoreatpercentile(values, 75)\n ) / 2.0\n\n\ndef relations(df, num_columns):\n return [\n \"\\nCovariances:\",\n str(df[num_columns].cov()),\n \"\\nCorrelations:\",\n str(df[num_columns].corr()),\n ]\n\n\ndef gather_descriptions(df, options):\n def _is_numeric(col):\n return df[col].dtype.kind == \"i\" or df[col].dtype.kind == \"f\"\n\n def _describe_column(col):\n if _is_numeric(col):\n return get_data(col, df[col], options)\n else:\n return get_nonnumeric(col, df[col])\n\n description = [\"\\n\".join(_describe_column(c)) for c in df.columns]\n num_columns = list(filter(_is_numeric, df.columns))\n\n if not options.simple and df.shape[1] > 1 and len(num_columns) > 1:\n return description + relations(df, num_columns)\n else:\n return description\n\n\ndef get_parser():\n parser = OptionParser(\n usage=\"\"\"presents a range of standard descriptive statistics\n on columns of numerical data\n perl -e 'for($i = 0; $i < 20; $i++){print rand(), \"\\\\t\", rand(), \"\\\\t\", rand(), \"\\\\n\"}' | python describe.py\n Usage %prog [options] \n \"\"\"\n )\n\n parser.add_option(\n \"-f\",\n \"--file\",\n action=\"store\",\n dest=\"filename\",\n default=False,\n help=\"[optional] use a specified file instead of reading from stdin\",\n )\n parser.add_option(\n \"-o\",\n \"--out\",\n action=\"store\",\n dest=\"out\",\n default=False,\n help=\"[optional] write to a specified file instead of stdout\",\n )\n parser.add_option(\n \"-H\",\n \"--header\",\n action=\"store_true\",\n dest=\"header\",\n default=None,\n help=\"treat the first row as column headers\",\n )\n parser.add_option(\n \"-d\",\n \"--delim\",\n action=\"store\",\n dest=\"delim\",\n default=\"\\t\",\n help=\"delimiter seperating columns in input\",\n )\n parser.add_option(\n \"-a\",\n \"--alpha\",\n action=\"store\",\n dest=\"alpha\",\n default=0.9,\n help=\"confidence value used in interval estimation\",\n )\n parser.add_option(\n \"-s\",\n \"--simple\",\n action=\"store_true\",\n dest=\"simple\",\n default=False,\n help=\"abbreviated, simplified output\",\n )\n parser.add_option(\n \"-i\",\n \"--ignore\",\n dest=\"ignore\",\n action=\"store\",\n help=\"ignore the specified colums. can be a column name or column index (from 0). specifiy multiple values separated by commas\",\n )\n parser.add_option(\n \"-C\",\n \"--columns\",\n dest=\"columns\",\n action=\"store\",\n help=\"include _only_ these columns. can be a column name or column index (from 0). specifiy multiple values separated by commas\",\n )\n\n return parser\n\n\ndef main():\n\n (options, args) = get_parser().parse_args()\n\n input = open(options.filename, \"r\") if options.filename else sys.stdin\n\n out = open(options.out, \"w\") if options.out else sys.stdout\n\n df = pd.read_csv(input, sep=options.delim, header=0 if options.header else None)\n\n df = select_columns(df, options.ignore, options.columns)\n\n description = gather_descriptions(df, options)\n\n out.write(\"\\n\\n\".join(description) + \"\\n\")\n out.flush()\n out.close()\n input.close()\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"pandas.read_csv",
"scipy.stats.normaltest",
"numpy.unique",
"scipy.stats.bayes_mvs",
"scipy.stats.stats.kurtosis",
"scipy.stats.stats.mode",
"scipy.stats.stats.scoreatpercentile",
"scipy.stats.stats.skew",
"scipy.stats.sem"
]
] |
OrkunAvci/Document-Clustering
|
[
"a91389cefb78d8dbe559870689450610a7bceba8"
] |
[
"main.py"
] |
[
"import numpy as np\nfrom sklearn.cluster._kmeans import KMeans\n\nimport file_manager as fm\n\nall_links = fm.get(\"_all_links\")\nguide = fm.get(\"_guide\")\n\ntrain = fm.get(\"_train_gft\")\ntest = fm.get(\"_test_gft\")\n\nclusters = 3\nout = KMeans(n_clusters=clusters, random_state=0).fit(train)\n\ntest = np.reshape(np.array(test), (-1, len(guide.keys())))\npredictions = out.predict(test)\n\nfor cluster in range(clusters):\n\tprint(\"Trained: \", list(out.labels_).count(cluster), \" - \", \"Predicted: \", list(predictions).count(cluster))"
] |
[
[
"numpy.array",
"sklearn.cluster._kmeans.KMeans"
]
] |
nticea/superhawkes
|
[
"cbaec7c4aae7ced71ec68f6d69cc516bc19ace5a"
] |
[
"test/cython_parallel_parent_test.py"
] |
[
"import numpy as np\n\nfrom pyhawkes.internals.parent_updates import mf_update_Z\n\ndef test_parallel_parent_updates():\n \"\"\"\n Just run the parent updates in a parallel loop and watch htop\n to make sure that all the cores are being used.\n :return:\n \"\"\"\n\n T = 10000\n K = 100\n B = 3\n S = np.random.poisson(2.0, size=((T,K))).astype(np.int)\n\n EZ0 = np.zeros((T,K))\n EZ = np.zeros((T,K,K,B))\n\n exp_E_log_lambda0 = np.random.gamma(1.0, 1.0, size=(K))\n exp_E_log_W = np.random.gamma(1.0, 1.0, size=(K,K))\n exp_E_log_g = np.random.gamma(1.0, 1.0, size=(K,K,B))\n F = np.random.gamma(1.0, 1.0, size=(T,K,B))\n\n for itr in range(1000):\n if itr % 10 == 0:\n print(\"Iteration\\t\", itr)\n\n mf_update_Z(EZ0,\n EZ,\n S,\n exp_E_log_lambda0,\n exp_E_log_W,\n exp_E_log_g,\n F)\n\n # It looks like the big problem is that check_EZ\n # is done on a single core (slow!)\n # check_EZ(EZ0, EZ, S)\n\ndef check_EZ(EZ0, EZ, S):\n \"\"\"\n Check that Z adds up to the correct amount\n :return:\n \"\"\"\n EZsum = EZ0 + EZ.sum(axis=(1,3))\n # assert np.allclose(self.S, Zsum), \"_check_Z failed. Zsum does not add up to S!\"\n if not np.allclose(S, EZsum):\n print(\"_check_Z failed. Zsum does not add up to S!\")\n import pdb; pdb.set_trace()\n\ntest_parallel_parent_updates()"
] |
[
[
"numpy.random.poisson",
"numpy.zeros",
"numpy.allclose",
"numpy.random.gamma"
]
] |
LuizHuang/AI-LearnNote
|
[
"e6c7dd1ee7ae4208a72f297d645fcdbc5b23a01c"
] |
[
"3_Feature/MinMaxScaler.py"
] |
[
"# 不属于同一量纲:即特征的规格不一样,不能够放在一起比较。无量纲化可以解决这一问题。\n# 和stanardscaler比,适合对存在极端大和小的点的数据。\n# 除了上述介绍的方法之外,另一种常用的方法是将属性缩放到一个指定的最大值和最小值(通常是1-0)之间,这可以通过preprocessing.MinMaxScaler类来实现。\n# X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0))\n# X_scaled = X_std * (max - min) + min\n\nfrom sklearn.preprocessing import MinMaxScaler\ndata = [[-1, 2], [-0.5, 6], [0, 10], [1, 18]]\nscaler = MinMaxScaler()\nprint(scaler.fit(data))\nprint(scaler.transform(data))\nprint(scaler.transform([[2, 2]]))\n"
] |
[
[
"sklearn.preprocessing.MinMaxScaler"
]
] |
Gyfis/kohonen-nn-implementation-II
|
[
"9e60f33ab4166e095f56ab891e17444ac976e824"
] |
[
"kohonen.py"
] |
[
"import numpy as np\nfrom itertools import product\nfrom operator import sub\nimport lateral_inhibitions\nfrom enum import Enum\n\n\nclass Layout(Enum):\n square = 1,\n hex = 2\n\n\ndef dist(neuron1, neuron2):\n return sum(abs(neuron1 - neuron2))\n\n\ndef id_dist(id1, id2):\n return sum(map(abs, map(sub, id1, id2)))\n\n\nclass Kohonen(object):\n def __init__(self, dims=(15, 15), layout=Layout.square, init_type=None, init_range=(0.4, 0.6),\n use_alt_update=False, fixed_neuron_number=0, fixed_neuron_pos=None):\n size = dims + (len(dims), )\n self.neurons = np.random.uniform(init_range[0], init_range[1], size) if init_type else np.zeros(size)\n\n for i in range(fixed_neuron_number):\n self.neurons[(i, 0, 0)] = np.array(fixed_neuron_pos[i]) / 255.0\n\n self.lateral_inhibition = {\n Layout.square: lateral_inhibitions.gauss,\n Layout.hex: lateral_inhibitions.gauss_hex\n }[layout]\n self.use_alt_update = use_alt_update\n self.fixed_neuron_number = fixed_neuron_number\n\n def neuron_id_iterator(self):\n return product(*map(range, self.neurons.shape[:-1]))\n\n def dims(self):\n return self.neurons.shape\n\n def get_sorted_neuron_ids(self, weights):\n return sorted(list(self.neuron_id_iterator()), key=lambda n_id: dist(weights, self.neurons[n_id]))\n\n def update(self, weights, diameter=1, alpha=0.05):\n if self.use_alt_update:\n self.update_alt(weights, diameter, alpha)\n return\n\n min_neuron_id = min((neuron_id for neuron_id in self.neuron_id_iterator()),\n key=lambda x: dist(weights, self.neurons[x]))\n\n for neuron_id in self.neuron_id_iterator():\n neuron = self.neurons[neuron_id]\n neuron += self.lateral_inhibition(neuron_id, min_neuron_id, diameter) * (weights - neuron) * alpha\n\n def update_alt(self, weights, diameter=5, alpha=0.05):\n sorted_neuron_ids = self.get_sorted_neuron_ids(weights)\n for neuron_id in sorted_neuron_ids[:round(diameter)]:\n if neuron_id[0] < self.fixed_neuron_number:\n continue\n neuron = self.neurons[neuron_id]\n neuron += (weights - neuron) * alpha\n"
] |
[
[
"numpy.random.uniform",
"numpy.array",
"numpy.zeros"
]
] |
cycleuser/imagepy
|
[
"5dc1a9a8137280c5215287392ba1b23d368bd7e9"
] |
[
"imagepy/core/app/imagepy.py"
] |
[
"import wx, os, sys\nimport time, threading\nsys.path.append('../../../')\nimport wx.lib.agw.aui as aui\nfrom sciwx.widgets import MenuBar, ToolBar, ChoiceBook, ParaDialog, WorkFlowPanel, ProgressBar\nfrom sciwx.canvas import CanvasNoteBook\nfrom sciwx.grid import GridNoteBook\nfrom sciwx.mesh import Canvas3DNoteBook\nfrom sciwx.text import MDNoteBook, TextNoteFrame\nfrom sciwx.plot import PlotFrame\nfrom skimage.data import camera\nfrom sciapp import App, Source\nfrom sciapp.object import Image\nfrom imagepy import root_dir\n\nclass ImagePy(wx.Frame, App):\n def __init__( self, parent ):\n wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = 'ImagePy', \n size = wx.Size(-1,-1), pos = wx.DefaultPosition, \n style = wx.RESIZE_BORDER|wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )\n App.__init__(self)\n self.auimgr = aui.AuiManager()\n self.auimgr.SetManagedWindow( self )\n self.SetSizeHints( wx.Size(1024,768) )\n \n logopath = os.path.join(root_dir, 'data/logo.ico')\n self.SetIcon(wx.Icon(logopath, wx.BITMAP_TYPE_ICO))\n\n self.init_menu()\n self.init_tool()\n self.init_canvas()\n self.init_table()\n self.init_mesh()\n self.init_widgets()\n self.init_text()\n self.init_status()\n\n self.Layout()\n self.auimgr.Update()\n self.Fit()\n self.Centre( wx.BOTH )\n\n self.Bind(wx.EVT_CLOSE, self.on_close)\n self.Bind(aui.EVT_AUI_PANE_CLOSE, self.on_pan_close)\n self.source()\n\n def source(self):\n self.manager('color').add('front', (255, 255, 255))\n self.manager('color').add('back', (0, 0, 0))\n\n def init_status(self):\n self.stapanel = stapanel = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )\n sizersta = wx.BoxSizer( wx.HORIZONTAL )\n self.txt_info = wx.StaticText( stapanel, wx.ID_ANY, \"ImagePy v0.2\", wx.DefaultPosition, wx.DefaultSize, 0 )\n self.txt_info.Wrap( -1 )\n sizersta.Add( self.txt_info, 1, wx.ALIGN_BOTTOM|wx.BOTTOM|wx.LEFT|wx.RIGHT, 2 )\n #self.pro_bar = wx.Gauge( stapanel, wx.ID_ANY, 100, wx.DefaultPosition, wx.Size( 100,15 ), wx.GA_HORIZONTAL )\n self.pro_bar = ProgressBar(stapanel)\n sizersta.Add( self.pro_bar, 0, wx.ALL, 2 )\n stapanel.SetSizer(sizersta)\n class OpenDrop(wx.FileDropTarget):\n def __init__(self, app): \n wx.FileDropTarget.__init__(self)\n self.app = app\n def OnDropFiles(self, x, y, path):\n self.app.run_macros([\"Open>{'path':'%s'}\"%i.replace('\\\\', '/') for i in path])\n stapanel.SetDropTarget(OpenDrop(self))\n self.auimgr.AddPane( stapanel, aui.AuiPaneInfo() .Bottom() .CaptionVisible( False ).PinButton( True )\n .PaneBorder( False ).Dock().Resizable().FloatingSize( wx.DefaultSize ).DockFixed( True )\n . MinSize(wx.Size(-1, 20)). MaxSize(wx.Size(-1, 20)).Layer( 10 ) )\n \n def load_menu(self, data):\n self.menubar.load(data)\n\n def load_tool(self, data, default=None):\n for i, (name, tols) in enumerate(data[1]):\n self.toolbar.add_tools(name, tols, i==0)\n if not default is None: self.toolbar.add_pop(os.path.join(root_dir, 'tools/drop.gif'), default)\n self.toolbar.Layout()\n\n def load_widget(self, data):\n print(self.widgets, '============')\n self.widgets.load(data)\n \n def init_menu(self):\n self.menubar = MenuBar(self)\n \n def init_tool(self):\n sizer = wx.BoxSizer(wx.VERTICAL)\n self.toolbar = ToolBar(self, True)\n self.toolbar.Fit()\n\n self.auimgr.AddPane(self.toolbar, aui.AuiPaneInfo() .Left() .PinButton( True )\n .CaptionVisible( True ).Dock().Resizable().FloatingSize( wx.DefaultSize ).MaxSize(wx.Size( 32,-1 ))\n . BottomDockable( True ).TopDockable( False ).Layer( 10 ) )\n\n def set_background(self, img):\n class ImgArtProvider(aui.AuiDefaultDockArt):\n def __init__(self, img):\n aui.AuiDefaultDockArt.__init__(self)\n self.bitmap = wx.Bitmap(img, wx.BITMAP_TYPE_PNG)\n\n def DrawBackground(self, dc, window, orient, rect):\n aui.AuiDefaultDockArt.DrawBackground(self, dc, window, orient, rect)\n \n memDC = wx.MemoryDC()\n memDC.SelectObject(self.bitmap)\n w, h = self.bitmap.GetWidth(), self.bitmap.GetHeight()\n dc.Blit((rect[2]-w)//2, (rect[3]-h)//2, w, h, memDC, 0, 0, wx.COPY, True)\n self.canvasnb.GetAuiManager().SetArtProvider(ImgArtProvider(img))\n\n def init_canvas(self):\n self.canvasnbwrap = wx.Panel(self)\n sizer = wx.BoxSizer( wx.VERTICAL )\n self.canvasnb = CanvasNoteBook(self.canvasnbwrap)\n self.set_background(root_dir+'/data/watermark.png')\n\n sizer.Add( self.canvasnb, 1, wx.EXPAND |wx.ALL, 0 )\n self.canvasnbwrap.SetSizer( sizer )\n self.canvasnbwrap.Layout()\n self.auimgr.AddPane( self.canvasnbwrap, aui.AuiPaneInfo() .Center() .CaptionVisible( False ).PinButton( True ).Dock()\n .PaneBorder( False ).Resizable().FloatingSize( wx.DefaultSize ). BottomDockable( True ).TopDockable( False )\n .LeftDockable( True ).RightDockable( True ) )\n self.canvasnb.Bind( wx.lib.agw.aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self.on_new_img)\n self.canvasnb.Bind( wx.lib.agw.aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.on_close_img)\n\n def init_table(self):\n self.tablenbwrap = wx.Panel(self)\n sizer = wx.BoxSizer( wx.VERTICAL )\n self.tablenb = GridNoteBook( self.tablenbwrap)\n sizer.Add( self.tablenb, 1, wx.EXPAND |wx.ALL, 0 )\n self.tablenbwrap.SetSizer( sizer )\n self.tablenbwrap.Layout()\n\n self.auimgr.AddPane( self.tablenbwrap, aui.AuiPaneInfo() .Bottom() .CaptionVisible( True ).PinButton( True ).Dock().Hide()\n .MaximizeButton( True ).Resizable().FloatingSize((800, 600)).BestSize(( 120,120 )). Caption('Tables') . \n BottomDockable( True ).TopDockable( False ).LeftDockable( True ).RightDockable( True ) )\n self.tablenb.Bind( wx.lib.agw.aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self.on_new_tab)\n self.tablenb.Bind( wx.lib.agw.aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.on_close_tab)\n\n def init_mesh(self):\n self.meshnbwrap = wx.Panel(self)\n sizer = wx.BoxSizer( wx.VERTICAL )\n self.meshnb = Canvas3DNoteBook( self.meshnbwrap)\n sizer.Add( self.meshnb, 1, wx.EXPAND |wx.ALL, 0 )\n self.meshnbwrap.SetSizer( sizer )\n self.meshnbwrap.Layout()\n\n self.auimgr.AddPane( self.meshnbwrap, aui.AuiPaneInfo() .Bottom() .CaptionVisible( True ).PinButton( True ).Float().Hide()\n .MaximizeButton( True ).Resizable().FloatingSize((800, 600)).BestSize(( 120,120 )). Caption('Meshes') . \n BottomDockable( True ).TopDockable( False ).LeftDockable( True ).RightDockable( True ) )\n self.meshnb.Bind( wx.lib.agw.aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self.on_new_mesh)\n self.meshnb.Bind( wx.lib.agw.aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.on_close_mesh)\n\n def add_task(self, task):\n self.task_manager.add(task.title, task)\n tasks = self.task_manager.gets()\n tasks = [(p.title, lambda t=p:p.prgs) for n,p,t in tasks]\n self.pro_bar.SetValue(tasks)\n\n def remove_task(self, task):\n self.task_manager.remove(obj=task)\n tasks = self.task_manager.gets()\n tasks = [(p.title, lambda t=p:p.prgs) for n,p,t in tasks]\n self.pro_bar.SetValue(tasks)\n\n def init_widgets(self):\n self.widgets = ChoiceBook(self)\n self.auimgr.AddPane( self.widgets, aui.AuiPaneInfo() .Right().Caption('Widgets') .PinButton( True )\n .Dock().Resizable().FloatingSize( wx.DefaultSize ).MinSize( wx.Size( 266,-1 ) ).Layer( 10 ) )\n\n def init_text(self):\n self.mdwarp = wx.Panel(self)\n sizer = wx.BoxSizer( wx.VERTICAL )\n self.mdnb = MDNoteBook( self.mdwarp)\n sizer.Add( self.mdnb, 1, wx.EXPAND |wx.ALL, 0 )\n self.mdwarp.SetSizer( sizer )\n self.mdwarp.Layout()\n\n self.auimgr.AddPane( self.mdwarp, aui.AuiPaneInfo() .Bottom() .CaptionVisible( True ).PinButton( True ).Float().Hide()\n .MaximizeButton( True ).Resizable().FloatingSize((400, 400)).BestSize(( 120,120 )). Caption('MarkDown') . \n BottomDockable( True ).TopDockable( False ).LeftDockable( True ).RightDockable( True ) )\n\n self.txtframe = TextNoteFrame(self, 'Sci Text')\n\n def on_pan_close(self, event):\n if event.GetPane().window in [self.toolbar, self.widgets]:\n event.Veto()\n if hasattr(event.GetPane().window, 'close'):\n event.GetPane().window.close()\n\n def on_new_img(self, event):\n self.add_img(self.canvasnb.canvas().image)\n self.add_img_win(self.canvasnb.canvas())\n\n def on_close_img(self, event):\n canvas = event.GetEventObject().GetPage(event.GetSelection())\n self.remove_img_win(canvas)\n self.remove_img(canvas.image)\n\n def on_new_tab(self, event):\n self.add_tab(self.tablenb.grid().table)\n self.add_tab_win(self.tablenb.grid())\n\n def on_close_tab(self, event):\n grid = event.GetEventObject().GetPage(event.GetSelection())\n self.remove_tab_win(grid)\n self.remove_tab(grid.table)\n \n def on_new_mesh(self, event):\n self.add_mesh(self.meshnb.canvas().mesh)\n self.add_mesh_win(self.meshnb.canvas())\n\n def on_close_mesh(self, event):\n canvas3d = event.GetEventObject().GetPage(event.GetSelection())\n self.remove_mesh(canvas3d.mesh)\n self.remove_mesh_win(canvas3d)\n \n def set_info(self, value):\n self.txt_info.SetLabel(value)\n\n def set_progress(self, value):\n v = max(min(value, 100), 0)\n self.pro_bar.SetValue(v)\n if value==-1:\n self.pro_bar.Hide()\n elif not self.pro_bar.IsShown():\n self.pro_bar.Show()\n self.stapanel.GetSizer().Layout()\n self.pro_bar.Update()\n\n def on_close(self, event):\n print('close')\n #ConfigManager.write()\n self.auimgr.UnInit()\n del self.auimgr\n self.Destroy()\n Source.manager('config').write()\n sys.exit()\n\n def _show_img(self, img, title=None):\n canvas = self.canvasnb.add_canvas()\n self.remove_img(canvas.image)\n self.remove_img_win(canvas)\n if not title is None:\n canvas.set_imgs(img)\n canvas.image.name = title\n else: canvas.set_img(img)\n self.add_img(canvas.image)\n self.add_img_win(canvas)\n\n def show_img(self, img, title=None):\n wx.CallAfter(self._show_img, img, title)\n\n def _show_table(self, tab, title):\n grid = self.tablenb.add_grid()\n self.remove_tab(grid.table)\n self.remove_tab_win(grid)\n grid.set_data(tab)\n grid.table.name = title\n info = self.auimgr.GetPane(self.tablenbwrap)\n info.Show(True)\n self.auimgr.Update()\n self.add_tab(grid.table)\n self.add_tab_win(grid)\n\n def show_table(self, tab, title=None):\n wx.CallAfter(self._show_table, tab, title)\n\n def show_plot(self, title):\n fig = PlotFrame(self)\n fig.figure.title = title\n return fig\n\n def _show_md(self, cont, title='ImagePy'):\n page = self.mdnb.add_page()\n page.set_cont(cont)\n page.title = title\n info = self.auimgr.GetPane(self.mdwarp)\n info.Show(True)\n self.auimgr.Update()\n\n def show_md(self, cont, title='ImagePy'):\n wx.CallAfter(self._show_md, cont, title)\n \n def _show_workflow(self, cont, title='ImagePy'):\n pan = WorkFlowPanel(self)\n pan.SetValue(cont)\n info = aui.AuiPaneInfo(). DestroyOnClose(True). Left(). Caption(title) .PinButton( True ) \\\n .Resizable().FloatingSize( wx.DefaultSize ).Dockable(True).Dock().Top().Layer( 5 ) \n pan.Bind(None, pan.Bind(None, lambda x:self.run_macros(['%s>None'%x])))\n self.auimgr.AddPane(pan, info)\n self.auimgr.Update()\n\n def show_workflow(self, cont, title='ImagePy'):\n wx.CallAfter(self._show_workflow, cont, title)\n\n def _show_txt(self, cont, title='ImagePy'):\n page = self.txtframe.add_notepad()\n page.append(cont)\n self.txtframe.Show()\n\n def show_txt(self, cont, title='ImagePy'):\n wx.CallAfter(self._show_txt, cont, title)\n\n def _show_mesh(self, mesh=None, title=None):\n if mesh is None:\n canvas = self.meshnb.add_canvas()\n canvas.mesh.name = 'Surface'\n elif hasattr(mesh, 'vts'):\n canvas = self.get_mesh_win()\n if canvas is None:\n canvas = self.meshnb.add_canvas()\n canvas.mesh.name = 'Surface'\n canvas.add_surf(title, mesh)\n else:\n canvas = self.meshnb.add_canvas()\n canvas.set_mesh(mesh)\n self.add_mesh(canvas.mesh)\n self.add_mesh_win(canvas)\n\n info = self.auimgr.GetPane(self.meshnbwrap)\n info.Show(True)\n self.auimgr.Update()\n\n def show_mesh(self, mesh=None, title=None):\n wx.CallAfter(self._show_mesh, mesh, title)\n\n def show_widget(self, panel, title='Widgets'):\n obj = self.manager('widget').get(panel.title)\n if obj is None:\n pan = panel(self, self)\n self.manager('widget').add(obj=pan, name=panel.title)\n self.auimgr.AddPane(pan, aui.AuiPaneInfo().Caption(panel.title).Left().Layer( 15 ).PinButton( True )\n .Float().Resizable().FloatingSize( wx.DefaultSize ).Dockable(True)) #.DestroyOnClose())\n else: \n info = self.auimgr.GetPane(obj)\n info.Show(True)\n self.Layout()\n self.auimgr.Update()\n\n def switch_widget(self, visible=None): \n info = self.auimgr.GetPane(self.widgets)\n info.Show(not info.IsShown() if visible is None else visible)\n self.auimgr.Update()\n\n def switch_toolbar(self, visible=None): \n info = self.auimgr.GetPane(self.toolbar)\n info.Show(not info.IsShown() if visible is None else visible)\n self.auimgr.Update()\n\n def switch_table(self, visible=None): \n info = self.auimgr.GetPane(self.tablenbwrap)\n info.Show(not info.IsShown() if visible is None else visible)\n self.auimgr.Update()\n\n def close_img(self, name=None):\n names = self.get_img_name() if name is None else [name]\n for name in names:\n idx = self.canvasnb.GetPageIndex(self.get_img_win(name))\n self.remove_img(self.get_img_win(name).image)\n self.remove_img_win(self.get_img_win(name))\n self.canvasnb.DeletePage(idx)\n\n def close_table(self, name=None):\n names = self.get_tab_name() if name is None else [name]\n for name in names:\n idx = self.tablenb.GetPageIndex(self.get_tab_win(name))\n self.remove_tab(self.get_tab_win(name).table)\n self.remove_tab_win(self.get_tab_win(name))\n self.tablenb.DeletePage(idx)\n\n def record_macros(self, cmd):\n obj = self.manager('widget').get(name='Macros Recorder')\n if obj is None or not obj.IsShown(): return\n wx.CallAfter(obj.write, cmd)\n\n def run_macros(self, cmd, callafter=None):\n cmds = [i for i in cmd]\n def one(cmds, after): \n cmd = cmds.pop(0)\n title, para = cmd.split('>')\n plg = Source.manager('plugin').get(name=title)()\n after = lambda cmds=cmds: one(cmds, one)\n if len(cmds)==0: after = callafter\n wx.CallAfter(plg.start, self, eval(para), after)\n one(cmds, None)\n\n def show(self, tag, cont, title):\n tag = tag or 'img'\n if tag=='img':\n self.show_img([cont], title)\n elif tag=='imgs':\n self.show_img(cont, title)\n elif tag=='tab':\n self.show_table(cont, title)\n elif tag=='mc':\n self.run_macros(cont)\n elif tag=='md':\n self.show_md(cont, title)\n elif tag=='wf':\n self.show_workflow(cont, title)\n else: self.alert('no view for %s!'%tag)\n\n def info(self, cont): \n wx.CallAfter(self.txt_info.SetLabel, cont)\n\n def _alert(self, info, title='ImagePy'):\n dialog=wx.MessageDialog(self, info, title, wx.OK)\n dialog.ShowModal() == wx.ID_OK\n dialog.Destroy()\n\n def alert(self, info, title='ImagePy'):\n wx.CallAfter(self._alert, info, title)\n\n def yes_no(self, info, title='ImagePy'):\n dialog = wx.MessageDialog(self, info, title, wx.YES_NO | wx.CANCEL)\n rst = dialog.ShowModal()\n dialog.Destroy()\n dic = {wx.ID_YES:'yes', wx.ID_NO:'no', wx.ID_CANCEL:'cancel'}\n return dic[rst]\n\n def getpath(self, title, filt, io, name=''):\n filt = '|'.join(['%s files (*.%s)|*.%s'%(i.upper(),i,i) for i in filt])\n dic = {'open':wx.FD_OPEN, 'save':wx.FD_SAVE}\n dialog = wx.FileDialog(self, title, '', name, filt, dic[io])\n rst = dialog.ShowModal()\n path = dialog.GetPath() if rst == wx.ID_OK else None\n dialog.Destroy()\n return path\n\n def show_para(self, title, view, para, on_handle=None, on_ok=None, on_cancel=None, preview=False, modal=True):\n dialog = ParaDialog(self, title)\n dialog.init_view(view, para, preview, modal=modal, app=self)\n dialog.Bind('cancel', on_cancel)\n dialog.Bind('parameter', on_handle)\n dialog.Bind('commit', on_ok)\n return dialog.show()\n\nif __name__ == '__main__':\n import numpy as np\n import pandas as pd\n\n app = wx.App(False)\n frame = ImagePy(None)\n frame.Show()\n frame.show_img([np.zeros((512, 512), dtype=np.uint8)], 'zeros')\n #frame.show_img(None)\n frame.show_table(pd.DataFrame(np.arange(100).reshape((10,10))), 'title')\n '''\n frame.show_md('abcdefg', 'md')\n frame.show_md('ddddddd', 'md')\n frame.show_txt('abcdefg', 'txt')\n frame.show_txt('ddddddd', 'txt')\n '''\n app.MainLoop()"
] |
[
[
"numpy.arange",
"numpy.zeros"
]
] |
robingong/imgaug
|
[
"702a257d5a89252ec0aab597f2cc42cfe82fd42b"
] |
[
"test/augmentables/test_batches.py"
] |
[
"from __future__ import print_function, division, absolute_import\n\nimport time\nimport warnings\nimport sys\n# unittest only added in 3.4 self.subTest()\nif sys.version_info[0] < 3 or sys.version_info[1] < 4:\n import unittest2 as unittest\nelse:\n import unittest\n# unittest.mock is not available in 2.7 (though unittest2 might contain it?)\ntry:\n import unittest.mock as mock\nexcept ImportError:\n import mock\n\nimport matplotlib\nmatplotlib.use('Agg') # fix execution of tests involving matplotlib on travis\nimport numpy as np\n\nimport imgaug as ia\nfrom imgaug.testutils import reseed\n\n\ndef main():\n time_start = time.time()\n\n # test_Batch()\n\n time_end = time.time()\n print(\"<%s> Finished without errors in %.4fs.\" % (__file__, time_end - time_start,))\n\n\nclass TestBatch(unittest.TestCase):\n def setUp(self):\n reseed()\n\n def test_init(self):\n attr_names = [\"images\", \"heatmaps\", \"segmentation_maps\", \"keypoints\",\n \"bounding_boxes\", \"polygons\", \"line_strings\"]\n batch = ia.Batch()\n for attr_name in attr_names:\n assert getattr(batch, \"%s_unaug\" % (attr_name,)) is None\n assert getattr(batch, \"%s_aug\" % (attr_name,)) is None\n assert batch.data is None\n\n # we exploit here that Batch() init does not verify its inputs\n batch = ia.Batch(\n images=0,\n heatmaps=1,\n segmentation_maps=2,\n keypoints=3,\n bounding_boxes=4,\n polygons=5,\n line_strings=6,\n data=7\n )\n for i, attr_name in enumerate(attr_names):\n assert getattr(batch, \"%s_unaug\" % (attr_name,)) == i\n assert getattr(batch, \"%s_aug\" % (attr_name,)) is None\n assert batch.data == 7\n\n def test_property_warnings(self):\n batch = ia.Batch()\n # self.assertWarns does not exist in py2.7\n with warnings.catch_warnings(record=True) as caught_warnings:\n warnings.simplefilter(\"always\")\n\n _ = batch.images\n assert len(caught_warnings) == 1\n assert \"is deprecated\" in str(caught_warnings[-1].message)\n\n _ = batch.heatmaps\n assert len(caught_warnings) == 2\n assert \"is deprecated\" in str(caught_warnings[-1].message)\n\n _ = batch.segmentation_maps\n assert len(caught_warnings) == 3\n assert \"is deprecated\" in str(caught_warnings[-1].message)\n\n _ = batch.keypoints\n assert len(caught_warnings) == 4\n assert \"is deprecated\" in str(caught_warnings[-1].message)\n\n _ = batch.bounding_boxes\n assert len(caught_warnings) == 5\n assert \"is deprecated\" in str(caught_warnings[-1].message)\n\n def test_deepcopy(self):\n batch = ia.Batch()\n observed = batch.deepcopy()\n keys = list(observed.__dict__.keys())\n assert len(keys) >= 14\n for attr_name in keys:\n assert getattr(observed, attr_name) is None\n\n batch = ia.Batch(images=np.zeros((1, 1, 3), dtype=np.uint8))\n observed = batch.deepcopy()\n for attr_name in observed.__dict__.keys():\n if attr_name != \"images_unaug\":\n assert getattr(observed, attr_name) is None\n assert ia.is_np_array(observed.images_unaug)\n\n batch = ia.Batch(\n images=np.zeros((1, 1, 3), dtype=np.uint8),\n heatmaps=[\n ia.HeatmapsOnImage(np.zeros((1, 1, 1), dtype=np.float32),\n shape=(4, 4, 3))\n ],\n segmentation_maps=[\n ia.SegmentationMapOnImage(np.zeros((1, 1), dtype=np.int32),\n shape=(5, 5, 3),\n nb_classes=20)\n ],\n keypoints=[\n ia.KeypointsOnImage([ia.Keypoint(x=1, y=2)], shape=(6, 6, 3))\n ],\n bounding_boxes=[\n ia.BoundingBoxesOnImage([\n ia.BoundingBox(x1=1, y1=2, x2=3, y2=4)],\n shape=(7, 7, 3))\n ],\n polygons=[\n ia.PolygonsOnImage([\n ia.Polygon([(0, 0), (10, 0), (10, 10)])\n ], shape=(100, 100, 3))\n ],\n line_strings=[\n ia.LineStringsOnImage([\n ia.LineString([(1, 1), (11, 1), (11, 11)])\n ], shape=(101, 101, 3))\n ],\n data={\"test\": 123, \"foo\": \"bar\", \"test2\": [1, 2, 3]}\n )\n observed = batch.deepcopy()\n for attr_name in observed.__dict__.keys():\n if \"_unaug\" not in attr_name and attr_name != \"data\":\n assert getattr(observed, attr_name) is None\n\n assert ia.is_np_array(observed.images_unaug)\n assert observed.images_unaug.shape == (1, 1, 3)\n assert isinstance(observed.heatmaps_unaug[0], ia.HeatmapsOnImage)\n assert isinstance(observed.segmentation_maps_unaug[0],\n ia.SegmentationMapOnImage)\n assert isinstance(observed.keypoints_unaug[0], ia.KeypointsOnImage)\n assert isinstance(observed.bounding_boxes_unaug[0],\n ia.BoundingBoxesOnImage)\n assert isinstance(observed.polygons_unaug[0], ia.PolygonsOnImage)\n assert isinstance(observed.line_strings_unaug[0], ia.LineStringsOnImage)\n assert isinstance(observed.data, dict)\n\n assert observed.heatmaps_unaug[0].shape == (4, 4, 3)\n assert observed.segmentation_maps_unaug[0].shape == (5, 5, 3)\n assert observed.keypoints_unaug[0].shape == (6, 6, 3)\n assert observed.bounding_boxes_unaug[0].shape == (7, 7, 3)\n assert observed.polygons_unaug[0].shape == (100, 100, 3)\n assert observed.line_strings_unaug[0].shape == (101, 101, 3)\n\n assert observed.heatmaps_unaug[0].arr_0to1.shape == (1, 1, 1)\n assert observed.segmentation_maps_unaug[0].arr.shape == (1, 1, 20)\n assert observed.keypoints_unaug[0].keypoints[0].x == 1\n assert observed.keypoints_unaug[0].keypoints[0].y == 2\n assert observed.bounding_boxes_unaug[0].bounding_boxes[0].x1 == 1\n assert observed.bounding_boxes_unaug[0].bounding_boxes[0].y1 == 2\n assert observed.bounding_boxes_unaug[0].bounding_boxes[0].x2 == 3\n assert observed.bounding_boxes_unaug[0].bounding_boxes[0].y2 == 4\n assert observed.polygons_unaug[0].polygons[0].exterior[0, 0] == 0\n assert observed.polygons_unaug[0].polygons[0].exterior[0, 1] == 0\n assert observed.polygons_unaug[0].polygons[0].exterior[1, 0] == 10\n assert observed.polygons_unaug[0].polygons[0].exterior[1, 1] == 0\n assert observed.polygons_unaug[0].polygons[0].exterior[2, 0] == 10\n assert observed.polygons_unaug[0].polygons[0].exterior[2, 1] == 10\n assert observed.line_strings_unaug[0].line_strings[0].coords[0, 0] == 1\n assert observed.line_strings_unaug[0].line_strings[0].coords[0, 1] == 1\n assert observed.line_strings_unaug[0].line_strings[0].coords[1, 0] == 11\n assert observed.line_strings_unaug[0].line_strings[0].coords[1, 1] == 1\n assert observed.line_strings_unaug[0].line_strings[0].coords[2, 0] == 11\n assert observed.line_strings_unaug[0].line_strings[0].coords[2, 1] == 11\n\n assert observed.data[\"test\"] == 123\n assert observed.data[\"foo\"] == \"bar\"\n assert observed.data[\"test2\"] == [1, 2, 3]\n"
] |
[
[
"matplotlib.use",
"numpy.zeros"
]
] |
manuelmarschall/CompressedFTIR
|
[
"40cb621943cc926789e55870a01c32e2434763b6"
] |
[
"compressedftir/lcurve.py"
] |
[
"'''\r\nLicense\r\n\r\n copyright Manuel Marschall (PTB) 2020\r\n\r\n This software is licensed under the BSD-like license:\r\n\r\n Redistribution and use in source and binary forms, with or without\r\n modification, are permitted provided that the following conditions are met:\r\n\r\n 1. Redistributions of source code must retain the above copyright notice,\r\n this list of conditions and the following disclaimer.\r\n 2. Redistributions in binary form must reproduce the above copyright\r\n notice, this list of conditions and the following disclaimer in\r\n the documentation and/or other materials provided with the distribution.\r\n\r\n DISCLAIMER\r\n ==========\r\n This software was developed at Physikalisch-Technische Bundesanstalt\r\n (PTB). The software is made available \"as is\" free of cost. PTB assumes\r\n no responsibility whatsoever for its use by other parties, and makes no\r\n guarantees, expressed or implied, about its quality, reliability, safety,\r\n suitability or any other characteristic. In no event will PTB be liable\r\n for any direct, indirect or consequential damage arising in connection\r\n\r\nUsing this software in publications requires citing the following paper\r\n\r\nCompressed FTIR spectroscopy using low-rank matrix reconstruction (to appear in Optics Express)\r\nDOI: https://doi.org/10.1364/OE.404959\r\n'''\r\nimport numpy as np\r\nfrom compressedftir.utils import sum_sq_nnz\r\n\r\ntry:\r\n import matlab\r\n\r\n # This is actually `matlab._internal`, but matlab/__init__.py\r\n # mangles the path making it appear as `_internal`.\r\n # Importing it under a different name would be a bad idea.\r\n from _internal.mlarray_utils import _get_strides, _get_mlsize\r\n\r\n def _wrapper__init__(self, arr):\r\n assert arr.dtype == type(self)._numpy_type\r\n self._python_type = type(arr.dtype.type().item())\r\n self._is_complex = np.issubdtype(arr.dtype, np.complexfloating)\r\n self._size = _get_mlsize(arr.shape)\r\n self._strides = _get_strides(self._size)[:-1]\r\n self._start = 0\r\n\r\n if self._is_complex:\r\n self._real = arr.real.ravel(order='F')\r\n self._imag = arr.imag.ravel(order='F')\r\n else:\r\n self._data = arr.ravel(order='F')\r\n\r\n _wrappers = {}\r\n\r\n def _define_wrapper(matlab_type, numpy_type):\r\n t = type(matlab_type.__name__, (matlab_type,), dict(\r\n __init__=_wrapper__init__,\r\n _numpy_type=numpy_type\r\n ))\r\n # this tricks matlab into accepting our new type\r\n t.__module__ = matlab_type.__module__\r\n _wrappers[numpy_type] = t\r\n\r\n _define_wrapper(matlab.double, np.double)\r\n _define_wrapper(matlab.single, np.single)\r\n _define_wrapper(matlab.uint8, np.uint8)\r\n _define_wrapper(matlab.int8, np.int8)\r\n _define_wrapper(matlab.uint16, np.uint16)\r\n _define_wrapper(matlab.int16, np.int16)\r\n _define_wrapper(matlab.uint32, np.uint32)\r\n _define_wrapper(matlab.int32, np.int32)\r\n _define_wrapper(matlab.uint64, np.uint64)\r\n _define_wrapper(matlab.int64, np.int64)\r\n _define_wrapper(matlab.logical, np.bool_)\r\n\r\n def as_matlab(arr):\r\n try:\r\n cls = _wrappers[arr.dtype.type]\r\n except KeyError:\r\n raise TypeError(\"Unsupported data type\")\r\n return cls(arr)\r\nexcept Exception:\r\n pass\r\n\r\n\r\ndef lcurve_value_gmrf(Z0, U, V, lapU, lapV):\r\n \"\"\"\r\n computes the argument and values of an lcurve result,\r\n having the proposed regularized low-rank model\r\n\r\n Arguments:\r\n Z0 {array like} -- sub-sampled data\r\n U {array like} -- first model component\r\n V {array like} -- second model component\r\n lapU {array like} -- regularizer for U\r\n lapV {array like} -- regularizer for V\r\n\r\n Returns:\r\n list -- [||Z0 - UV||_Omega / ||Z0||_Omega , ||lapU U|| + ||lapV V||]\r\n \"\"\"\r\n nnz = np.nonzero(Z0)\r\n Xh = U.dot(V)\r\n dd = Xh - Z0\r\n # TODO: This is really an issue. In 2D this does not work. Is it ok in 3D?\r\n # order=\"C\" due to the kronecker structure of the regularization matrices\r\n return [sum_sq_nnz(nnz, dd)/sum_sq_nnz(nnz, Z0),\r\n np.conj(U).reshape(-1, order=\"C\").dot(lapU.dot(U.reshape(-1, order=\"C\")))\r\n + np.conj(V).reshape(-1, order=\"C\").dot(lapV.dot(V.reshape(-1, order=\"C\")))]\r\n # return [sum_sq_nnz(nnz, dd)/sum_sq_nnz(nnz, Z0),\r\n # U.reshape(-1, order=\"F\").dot(lapU.dot(U.reshape(-1, order=\"F\")))\r\n # + V.reshape(-1, order=\"F\").dot(lapV.dot(V.reshape(-1, order=\"F\")))]\r\n\r\n\r\ndef get_corner_node_matlab(lcurve, debug=False):\r\n \"\"\"\r\n Computes the optimal argument of a given l-curve.\r\n Note: Only approximately and discrete.\r\n TODO: More elaborate using interpolation/extrapolation and\r\n analytical differentiation.\r\n Or implement https://arxiv.org/abs/1608.04571\r\n\r\n Arguments:\r\n lcurve {list} -- l-curve [[x1, y1], [x2, y2], ...]\r\n\r\n Returns:\r\n int -- Optimal argument that maximizes curvature\r\n \"\"\"\r\n lx, ly = np.zeros(len(lcurve)), np.zeros(len(lcurve))\r\n for lia in range(len(lcurve)):\r\n lx[lia] = lcurve[lia][0]\r\n ly[lia] = lcurve[lia][1]\r\n\r\n import matlab.engine\r\n eng = matlab.engine.start_matlab()\r\n eng.addpath(eng.genpath('../dfg_lowrank/simulation-200820/'))\r\n import io\r\n out = io.StringIO()\r\n err = io.StringIO()\r\n l_opt, info = eng.L_corner(as_matlab(lx), as_matlab(ly), nargout=2, stdout=out, stderr=err)\r\n # print(l_opt)\r\n # print(info)\r\n # print(out.getvalue())\r\n l_opt = int(l_opt)\r\n # k = curvature_lcurve(lx, ly)\r\n # l_opt = np.argmax(k)\r\n # print(l_opt)\r\n if False:\r\n import matplotlib\r\n matplotlib.use(\"Qt4Agg\")\r\n import matplotlib.pyplot as plt\r\n plt.figure()\r\n plt.title(\"L-curve\")\r\n plt.plot([np.log10(lcurve[lia][0]) for lia in range(len(lcurve))],\r\n [np.log10(lcurve[lia][1]) for lia in range(len(lcurve))], '-xb', label=\"L-curve\")\r\n plt.plot(np.log10(lcurve[l_opt][0]), np.log10(lcurve[l_opt][1]), 'or', label=\"optimal value\")\r\n plt.xlabel(\"log(|| Y - UV ||)\")\r\n plt.ylabel(\"log(|| L_U U || + || L_V V ||)\")\r\n plt.show()\r\n\r\n return l_opt\r\n\r\n\r\ndef get_corner_node_prune(lcurve):\r\n \"\"\"\r\n Computes the optimal argument for a given L-curve.\r\n Implements the python version of the matlab corner method of\r\n % Per Christian Hansen and Toke Koldborg Jensen, DTU Compute, DTU;\r\n % Giuseppe Rodriguez, University of Cagliari, Italy; Sept. 2, 2011.\r\n motivated by the Reference: P. C. Hansen, T. K. Jensen and G. Rodriguez,\r\n \"An adaptive pruning algorithm for the discrete L-curve criterion,\"\r\n J. Comp. Appl. Math., 198 (2007), 483-492.\r\n\r\n Arguments:\r\n lcurve {list} -- L-curve [[x1, y1], [x2, y2], ...]\r\n\r\n Raises:\r\n ValueError: Input list contains not equal length lists\r\n ValueError: Invalid data given\r\n\r\n Returns:\r\n int -- index of lcurve list that is \"optimal\"\r\n \"\"\"\r\n rho, eta = np.zeros(len(lcurve)), np.zeros(len(lcurve))\r\n for lia in range(len(lcurve)):\r\n rho[lia] = lcurve[lia][0]\r\n eta[lia] = lcurve[lia][1]\r\n\r\n if len(rho) != len(eta):\r\n raise ValueError(\"both arrays must have the same size\")\r\n fin = np.isfinite(rho + eta)\r\n nzr = np.array([False]*len(rho))\r\n nzr[np.nonzero(rho*eta)[0]] = True\r\n keep = fin & nzr\r\n if len(keep) < 1:\r\n raise ValueError(\"To few accepted data found\")\r\n if len(keep) < len(rho):\r\n print(\"I had to trim the data due to NaN/Inf or zero values\")\r\n rho = rho[keep]\r\n eta = eta[keep]\r\n if np.any(rho[:-1] < rho[1:]) or np.any(eta[:-1] > eta[1:]):\r\n print(\"Warning: L-curve lacks monotonicity\")\r\n nP = len(rho) # number of points\r\n P = np.log10(np.array([rho, eta])).T # Coordinates of the loglog L-curve\r\n V = P[1:, :] - P[:-1, :] # The vectors defined by these coord\r\n v = np.sqrt(np.sum(V**2, axis=1)) # length of the vectors\r\n # W = V/np.tile(v, (1, 2)); # Normalized vectors.\r\n W = np.zeros(V.shape)\r\n W[:, 0] = V[:, 0]/v\r\n W[:, 1] = V[:, 1]/v\r\n clist = [] # list of condidates\r\n p = np.min([5, nP]) # number of vectors in pruned L-curve\r\n # convex = 0 # Are the pruned L-curves convex\r\n Ind = np.argsort(v)[::-1] # Sort lengths decending\r\n while p < (nP-1)*2:\r\n elmts = np.sort(Ind[:np.min([p, nP-1])])\r\n candidate = Angles(W[elmts, :], elmts)\r\n # print(\"candidate p={}, {}\".format(p, candidate))\r\n if candidate not in clist:\r\n clist.append(candidate)\r\n candidate = Global_Behaviour(P, W[elmts, :], elmts)\r\n if candidate not in clist:\r\n clist.append(candidate)\r\n p = p*2\r\n # print(clist)\r\n if 0 not in clist:\r\n clist.insert(0, 0)\r\n clist = np.sort(clist)\r\n\r\n vz = np.argwhere(np.diff(P[clist, 1]) >= np.abs(np.diff(P[clist, 0])))\r\n if len(vz) > 1:\r\n if vz[0] == 0:\r\n vz = vz[1:]\r\n elif len(vz) == 1:\r\n if vz[0] == 0:\r\n vz = []\r\n if vz == [] or len(vz) == 0:\r\n # if vz.size <= 0:\r\n index = clist[-1]\r\n else:\r\n vects = np.array([P[clist[1:], 0] - P[clist[:-1], 0], P[clist[1:], 1] - P[clist[:-1], 1]]).T\r\n vects = np.dot(np.diag(1/np.sqrt(np.sum(vects**2, 1))), vects)\r\n delta = vects[:-1, 0] * vects[1:, 1] - vects[1:, 0] * vects[:-1, 1]\r\n vv = np.argwhere(delta[vz-1] <= 0)\r\n # print(vv)\r\n # print(vz)\r\n if vv == [] or len(vv) == 0:\r\n # if vv.size <= 0:\r\n index = clist[vz[-1]]\r\n else:\r\n index = clist[vz[vv[0]]]\r\n\r\n try:\r\n retval = int(index)\r\n except TypeError:\r\n print(\"index!!!!: {}\".format(index))\r\n retval = int(index[0])\r\n return retval\r\n\r\n\r\ndef Angles(W, kv):\r\n delta = W[:-1, 0]*W[1:, 1] - W[1:, 0]*W[:-1, 1]\r\n # print(\"delta: \\n {}\".format(delta))\r\n mm = np.min(delta)\r\n kk = np.argmin(delta)\r\n # print(\"mm {}, kk {}, kv(kk)= {}\".format(mm, kk, kv[kk]))\r\n if mm < 0: # is it really a corner\r\n index = kv[kk] + 1\r\n else: # if there is no corner: 0\r\n index = 0\r\n return index\r\n\r\n\r\ndef Global_Behaviour(P, vects, elmts):\r\n hwedge = np.abs(vects[:, 1])\r\n In = np.argsort(hwedge)\r\n count = 0\r\n ln = len(In)-1\r\n mn = In[0]\r\n mx = In[-1]\r\n while mn >= mx:\r\n mx = np.max([mx, In[ln-count]])\r\n count = count + 1\r\n mn = np.min([mn, In[count]])\r\n if count > 1:\r\n Ind = 0\r\n J = 0\r\n for i in range(count):\r\n for j in range(ln, ln-count, -1):\r\n if In[i] < In[j]:\r\n Ind = In[i]\r\n J = In[j]\r\n break\r\n if Ind > 0:\r\n break\r\n else:\r\n Ind = In[0]\r\n J = In[ln]\r\n\r\n x3 = P[elmts[J]+1, 0] + (P[elmts[Ind], 1] - P[elmts[J]+1, 1]) / \\\r\n (P[elmts[J]+1, 1]-P[elmts[J], 1])*(P[elmts[J]+1, 0]-P[elmts[J], 0])\r\n origin = np.array([x3, P[elmts[Ind], 1]]).T\r\n dists = (origin[0] - P[:, 0])**2 + (origin[1]-P[:, 1])**2\r\n return np.argmin(dists)\r\n"
] |
[
[
"numpy.issubdtype",
"numpy.max",
"numpy.argmin",
"numpy.any",
"numpy.diff",
"numpy.zeros",
"matplotlib.pyplot.figure",
"numpy.nonzero",
"numpy.min",
"matplotlib.pyplot.title",
"numpy.log10",
"numpy.argsort",
"matplotlib.pyplot.show",
"numpy.array",
"numpy.sum",
"matplotlib.pyplot.ylabel",
"numpy.abs",
"numpy.isfinite",
"numpy.conj",
"matplotlib.use",
"numpy.sort",
"numpy.argwhere",
"matplotlib.pyplot.xlabel"
]
] |
foamliu/Look-Into-Person-v2
|
[
"ca524bac51e3b54a0d723e746ee400905567adcb"
] |
[
"data_gen.py"
] |
[
"import os\nimport random\n\nimport cv2 as cv\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms\n\nfrom config import im_size, color_map, num_classes\n\ntrain_images_folder = 'data/instance-level_human_parsing/Training/Images'\ntrain_categories_folder = 'data/instance-level_human_parsing/Training/Category_ids'\nvalid_images_folder = 'data/instance-level_human_parsing/Validation/Images'\nvalid_categories_folder = 'data/instance-level_human_parsing/Validation/Category_ids'\n\n# Data augmentation and normalization for training\n# Just normalization for validation\ndata_transforms = {\n 'train': transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),\n ]),\n 'valid': transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ]),\n}\n\n\ndef get_category(categories_folder, name):\n filename = os.path.join(categories_folder, name + '.png')\n semantic = cv.imread(filename, 0)\n return semantic\n\n\ndef to_bgr(y_pred):\n ret = np.zeros((im_size, im_size, 3), np.float32)\n for r in range(320):\n for c in range(320):\n color_id = y_pred[r, c]\n # print(\"color_id: \" + str(color_id))\n ret[r, c, :] = color_map[color_id]\n ret = ret.astype(np.uint8)\n return ret\n\n\ndef random_choice(image_size):\n height, width = image_size\n crop_height, crop_width = 320, 320\n x = random.randint(0, max(0, width - crop_width))\n y = random.randint(0, max(0, height - crop_height))\n return x, y\n\n\ndef safe_crop(mat, x, y):\n crop_height, crop_width = 320, 320\n if len(mat.shape) == 2:\n ret = np.zeros((crop_height, crop_width), np.uint8)\n else:\n ret = np.zeros((crop_height, crop_width, 3), np.uint8)\n crop = mat[y:y + crop_height, x:x + crop_width]\n h, w = crop.shape[:2]\n ret[0:h, 0:w] = crop\n return ret\n\n\nclass LIPDataset(Dataset):\n def __init__(self, split):\n self.usage = split\n\n if split == 'train':\n id_file = 'data/instance-level_human_parsing/Training/train_id.txt'\n self.images_folder = train_images_folder\n self.categories_folder = train_categories_folder\n else:\n id_file = 'data/instance-level_human_parsing/Validation/val_id.txt'\n self.images_folder = valid_images_folder\n self.categories_folder = valid_categories_folder\n\n with open(id_file, 'r') as f:\n self.names = f.read().splitlines()\n\n self.transformer = data_transforms[split]\n\n def __getitem__(self, i):\n name = self.names[i]\n filename = os.path.join(self.images_folder, name + '.jpg')\n img = cv.imread(filename)\n image_size = img.shape[:2]\n category = get_category(self.categories_folder, name)\n\n x, y = random_choice(image_size)\n img = safe_crop(img, x, y)\n category = safe_crop(category, x, y)\n category = np.clip(category, 0, num_classes - 1)\n\n if np.random.random_sample() > 0.5:\n img = np.fliplr(img)\n category = np.fliplr(category)\n\n img = img[..., ::-1] # RGB\n img = transforms.ToPILImage()(img)\n img = self.transformer(img)\n\n y = category\n\n return img, torch.from_numpy(y.copy())\n\n def __len__(self):\n return len(self.names)\n\n\nif __name__ == \"__main__\":\n dataset = LIPDataset('train')\n print(dataset[0])\n"
] |
[
[
"numpy.fliplr",
"numpy.zeros",
"numpy.random.random_sample",
"numpy.clip"
]
] |
aborodya/AlphaPy
|
[
"b24de414b89a74d0ef1a6249e0bc4f96fb508a1e"
] |
[
"alphapy/transforms.py"
] |
[
"################################################################################\n#\n# Package : AlphaPy\n# Module : transforms\n# Created : March 14, 2020\n#\n# Copyright 2020 ScottFree Analytics LLC\n# Mark Conway & Robert D. Scott II\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n################################################################################\n\n\n#\n# Imports\n#\n\nfrom alphapy.calendrical import biz_day_month\nfrom alphapy.calendrical import biz_day_week\nfrom alphapy.globals import NULLTEXT\nfrom alphapy.globals import BSEP, PSEP, USEP\nfrom alphapy.variables import vexec\n\nimport itertools\nimport logging\nimport math\nimport numpy as np\nimport pandas as pd\n\n\n#\n# Initialize logger\n#\n\nlogger = logging.getLogger(__name__)\n\n\n#\n# Function abovema\n#\n\ndef abovema(f, c, p = 50):\n r\"\"\"Determine those values of the dataframe that are above the\n moving average.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str\n Name of the column in the dataframe ``f``.\n p : int\n The period of the moving average.\n\n Returns\n -------\n new_column : pandas.Series (bool)\n The array containing the new feature.\n\n \"\"\"\n new_column = f[c] > ma(f, c, p)\n return new_column\n\n\n#\n# Function adx\n#\n\ndef adx(f, p = 14):\n r\"\"\"Calculate the Average Directional Index (ADX).\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe with all columns required for calculation. If you\n are applying ADX through ``vapply``, then these columns are\n calculated automatically.\n p : int\n The period over which to calculate the ADX.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n References\n ----------\n The Average Directional Movement Index (ADX) was invented by J. Welles\n Wilder in 1978 [WIKI_ADX]_. Its value reflects the strength of trend in any\n given instrument.\n\n .. [WIKI_ADX] https://en.wikipedia.org/wiki/Average_directional_movement_index\n\n \"\"\"\n c1 = 'diplus'\n vexec(f, c1)\n c2 = 'diminus'\n vexec(f, c2)\n # calculations\n dip = f[c1]\n dim = f[c2]\n didiff = abs(dip - dim)\n disum = dip + dim\n new_column = 100 * didiff.ewm(span=p).mean() / disum\n return new_column\n\n\n#\n# Function belowma\n#\n\ndef belowma(f, c, p = 50):\n r\"\"\"Determine those values of the dataframe that are below the\n moving average.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str\n Name of the column in the dataframe ``f``.\n p : int\n The period of the moving average.\n\n Returns\n -------\n new_column : pandas.Series (bool)\n The array containing the new feature.\n\n \"\"\"\n new_column = f[c] < ma(f, c, p)\n return new_column\n\n\n#\n# Function c2max\n#\n \ndef c2max(f, c1, c2):\n r\"\"\"Take the maximum value between two columns in a dataframe.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the two columns ``c1`` and ``c2``.\n c1 : str\n Name of the first column in the dataframe ``f``.\n c2 : str\n Name of the second column in the dataframe ``f``.\n\n Returns\n -------\n max_val : float\n The maximum value of the two columns.\n\n \"\"\"\n max_val = max(f[c1], f[c2])\n return max_val\n\n\n#\n# Function c2min\n#\n \ndef c2min(f, c1, c2):\n r\"\"\"Take the minimum value between two columns in a dataframe.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the two columns ``c1`` and ``c2``.\n c1 : str\n Name of the first column in the dataframe ``f``.\n c2 : str\n Name of the second column in the dataframe ``f``.\n\n Returns\n -------\n min_val : float\n The minimum value of the two columns.\n\n \"\"\"\n min_val = min(f[c1], f[c2])\n return min_val\n\n\n#\n# Function diff\n#\n\ndef diff(f, c, n = 1):\n r\"\"\"Calculate the n-th order difference for the given variable.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str\n Name of the column in the dataframe ``f``.\n n : int\n The number of times that the values are differenced.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n \"\"\"\n new_column = np.diff(f[c], n)\n return new_column\n\n\n#\n# Function diminus\n#\n\ndef diminus(f, p = 14):\n r\"\"\"Calculate the Minus Directional Indicator (-DI).\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe with columns ``high`` and ``low``.\n p : int\n The period over which to calculate the -DI.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n References\n ----------\n *A component of the average directional index (ADX) that is used to\n measure the presence of a downtrend. When the -DI is sloping downward,\n it is a signal that the downtrend is getting stronger* [IP_NDI]_.\n\n .. [IP_NDI] http://www.investopedia.com/terms/n/negativedirectionalindicator.asp\n\n \"\"\"\n tr = 'truerange'\n vexec(f, tr)\n atr = USEP.join(['atr', str(p)])\n vexec(f, atr)\n dmm = 'dmminus'\n f[dmm] = dminus(f)\n new_column = 100 * dminus(f).ewm(span=p).mean() / f[atr]\n return new_column\n\n\n#\n# Function diplus\n#\n\ndef diplus(f, p = 14):\n r\"\"\"Calculate the Plus Directional Indicator (+DI).\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe with columns ``high`` and ``low``.\n p : int\n The period over which to calculate the +DI.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n References\n ----------\n *A component of the average directional index (ADX) that is used to\n measure the presence of an uptrend. When the +DI is sloping upward,\n it is a signal that the uptrend is getting stronger* [IP_PDI]_.\n\n .. [IP_PDI] http://www.investopedia.com/terms/p/positivedirectionalindicator.asp\n\n \"\"\"\n tr = 'truerange'\n vexec(f, tr)\n atr = USEP.join(['atr', str(p)])\n vexec(f, atr)\n dmp = 'dmplus'\n vexec(f, dmp)\n new_column = 100 * f[dmp].ewm(span=p).mean() / f[atr]\n return new_column\n\n\n#\n# Function dminus\n#\n\ndef dminus(f):\n r\"\"\"Calculate the Minus Directional Movement (-DM).\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe with columns ``high`` and ``low``.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n References\n ----------\n *Directional movement is negative (minus) when the prior low minus\n the current low is greater than the current high minus the prior high.\n This so-called Minus Directional Movement (-DM) equals the prior low\n minus the current low, provided it is positive. A negative value\n would simply be entered as zero* [SC_ADX]_.\n\n \"\"\"\n c1 = 'downmove'\n f[c1] = -net(f, 'low')\n c2 = 'upmove'\n f[c2] = net(f, 'high')\n new_column = f.apply(gtval0, axis=1, args=[c1, c2])\n return new_column\n\n\n#\n# Function dmplus\n#\n\ndef dmplus(f):\n r\"\"\"Calculate the Plus Directional Movement (+DM).\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe with columns ``high`` and ``low``.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n References\n ----------\n *Directional movement is positive (plus) when the current high minus\n the prior high is greater than the prior low minus the current low.\n This so-called Plus Directional Movement (+DM) then equals the current\n high minus the prior high, provided it is positive. A negative value\n would simply be entered as zero* [SC_ADX]_.\n\n .. [SC_ADX] http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:average_directional_index_adx\n\n \"\"\"\n c1 = 'upmove'\n f[c1] = net(f, 'high')\n c2 = 'downmove'\n f[c2] = -net(f, 'low')\n new_column = f.apply(gtval0, axis=1, args=[c1, c2])\n return new_column\n\n\n#\n# Function down\n#\n\ndef down(f, c):\n r\"\"\"Find the negative values in the series.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str\n Name of the column in the dataframe ``f``.\n\n Returns\n -------\n new_column : pandas.Series (bool)\n The array containing the new feature.\n\n \"\"\"\n new_column = f[c] < 0\n return new_column\n\n\n#\n# Function dpc\n#\n\ndef dpc(f, c):\n r\"\"\"Get the negative values, with positive values zeroed.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe with column ``c``.\n c : str\n Name of the column.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n \"\"\"\n new_column = f.apply(mval, axis=1, args=[c])\n return new_column\n\n\n#\n# Function ema\n#\n\ndef ema(f, c, p = 20):\n r\"\"\"Calculate the mean on a rolling basis.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str\n Name of the column in the dataframe ``f``.\n p : int\n The period over which to calculate the rolling mean.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n References\n ----------\n *An exponential moving average (EMA) is a type of moving average\n that is similar to a simple moving average, except that more weight\n is given to the latest data* [IP_EMA]_.\n\n .. [IP_EMA] http://www.investopedia.com/terms/e/ema.asp\n\n \"\"\"\n new_column = pd.ewma(f[c], span=p)\n return new_column\n\n\n#\n# Function extract_bizday\n#\n\ndef extract_bizday(f, c):\n r\"\"\"Extract business day of month and week.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the date column ``c``.\n c : str\n Name of the date column in the dataframe ``f``.\n\n Returns\n -------\n date_features : pandas.DataFrame\n The dataframe containing the date features.\n \"\"\"\n\n date_features = pd.DataFrame()\n try:\n date_features = extract_date(f, c)\n rdate = date_features.apply(get_rdate, axis=1)\n bdm = pd.Series(rdate.apply(biz_day_month), name='bizday_month')\n bdw = pd.Series(rdate.apply(biz_day_week), name='bizday_week')\n frames = [date_features, bdm, bdw]\n date_features = pd.concat(frames, axis=1)\n except:\n logger.info(\"Could not extract business date information from %s column\", c)\n return date_features\n\n\n#\n# Function extract_date\n#\n\ndef extract_date(f, c):\n r\"\"\"Extract date into its components: year, month, day, dayofweek.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the date column ``c``.\n c : str\n Name of the date column in the dataframe ``f``.\n\n Returns\n -------\n date_features : pandas.DataFrame\n The dataframe containing the date features.\n \"\"\"\n\n fc = pd.to_datetime(f[c])\n date_features = pd.DataFrame()\n try:\n fyear = pd.Series(fc.dt.year, name='year')\n fmonth = pd.Series(fc.dt.month, name='month')\n fday = pd.Series(fc.dt.day, name='day')\n fdow = pd.Series(fc.dt.dayofweek, name='day_of_week')\n frames = [fyear, fmonth, fday, fdow]\n date_features = pd.concat(frames, axis=1)\n except:\n logger.info(\"Could not extract date information from %s column\", c)\n return date_features\n\n\n#\n# Function extract_time\n#\n\ndef extract_time(f, c):\n r\"\"\"Extract time into its components: hour, minute, second.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the time column ``c``.\n c : str\n Name of the time column in the dataframe ``f``.\n\n Returns\n -------\n time_features : pandas.DataFrame\n The dataframe containing the time features.\n \"\"\"\n\n fc = pd.to_datetime(f[c])\n time_features = pd.DataFrame()\n try:\n fhour = pd.Series(fc.dt.hour, name='year')\n fminute = pd.Series(fc.dt.minute, name='month')\n fsecond = pd.Series(fc.dt.second, name='day')\n frames = [fhour, fminute, fsecond]\n time_features = pd.concat(frames, axis=1)\n except:\n logger.info(\"Could not extract time information from %s column\", c)\n return time_features\n\n\n#\n# Function gap\n#\n\ndef gap(f):\n r\"\"\"Calculate the gap percentage between the current open and\n the previous close.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe with columns ``open`` and ``close``.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n References\n ----------\n *A gap is a break between prices on a chart that occurs when the\n price of a stock makes a sharp move up or down with no trading\n occurring in between* [IP_GAP]_.\n\n .. [IP_GAP] http://www.investopedia.com/terms/g/gap.asp\n\n \"\"\"\n c1 = 'open'\n c2 = 'close[1]'\n vexec(f, c2)\n new_column = 100 * pchange2(f, c1, c2)\n return new_column\n\n\n#\n# Function gapbadown\n#\n\ndef gapbadown(f):\n r\"\"\"Determine whether or not there has been a breakaway gap down.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe with columns ``open`` and ``low``.\n\n Returns\n -------\n new_column : pandas.Series (bool)\n The array containing the new feature.\n\n References\n ----------\n *A breakaway gap represents a gap in the movement of a stock price\n supported by levels of high volume* [IP_BAGAP]_.\n\n .. [IP_BAGAP] http://www.investopedia.com/terms/b/breakawaygap.asp\n\n \"\"\"\n new_column = f['open'] < f['low'].shift(1)\n return new_column\n\n\n#\n# Function gapbaup\n#\n\ndef gapbaup(f):\n r\"\"\"Determine whether or not there has been a breakaway gap up.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe with columns ``open`` and ``high``.\n\n Returns\n -------\n new_column : pandas.Series (bool)\n The array containing the new feature.\n\n References\n ----------\n *A breakaway gap represents a gap in the movement of a stock price\n supported by levels of high volume* [IP_BAGAP]_.\n\n \"\"\"\n new_column = f['open'] > f['high'].shift(1)\n return new_column\n\n\n#\n# Function gapdown\n#\n\ndef gapdown(f):\n r\"\"\"Determine whether or not there has been a gap down.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe with columns ``open`` and ``close``.\n\n Returns\n -------\n new_column : pandas.Series (bool)\n The array containing the new feature.\n\n References\n ----------\n *A gap is a break between prices on a chart that occurs when the\n price of a stock makes a sharp move up or down with no trading\n occurring in between* [IP_GAP]_.\n\n \"\"\"\n new_column = f['open'] < f['close'].shift(1)\n return new_column\n\n\n#\n# Function gapup\n#\n\ndef gapup(f):\n r\"\"\"Determine whether or not there has been a gap up.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe with columns ``open`` and ``close``.\n\n Returns\n -------\n new_column : pandas.Series (bool)\n The array containing the new feature.\n\n References\n ----------\n *A gap is a break between prices on a chart that occurs when the\n price of a stock makes a sharp move up or down with no trading\n occurring in between* [IP_GAP]_.\n\n \"\"\"\n new_column = f['open'] > f['close'].shift(1)\n return new_column\n\n\n#\n# Function gtval\n#\n\ndef gtval(f, c1, c2):\n r\"\"\"Determine whether or not the first column of a dataframe\n is greater than the second.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the two columns ``c1`` and ``c2``.\n c1 : str\n Name of the first column in the dataframe ``f``.\n c2 : str\n Name of the second column in the dataframe ``f``.\n\n Returns\n -------\n new_column : pandas.Series (bool)\n The array containing the new feature.\n\n \"\"\"\n new_column = f[c1] > f[c2]\n return new_column\n\n\n#\n# Function gtval0\n#\n\ndef gtval0(f, c1, c2):\n r\"\"\"For positive values in the first column of the dataframe\n that are greater than the second column, get the value in\n the first column, otherwise return zero. \n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the two columns ``c1`` and ``c2``.\n c1 : str\n Name of the first column in the dataframe ``f``.\n c2 : str\n Name of the second column in the dataframe ``f``.\n\n Returns\n -------\n new_val : float\n A positive value or zero.\n\n \"\"\"\n if f[c1] > f[c2] and f[c1] > 0:\n new_val = f[c1]\n else:\n new_val = 0\n return new_val\n\n\n#\n# Function higher\n#\n\ndef higher(f, c, o = 1):\n r\"\"\"Determine whether or not a series value is higher than\n the value ``o`` periods back.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str\n Name of the column in the dataframe ``f``.\n o : int, optional\n Offset value for shifting the series.\n\n Returns\n -------\n new_column : pandas.Series (bool)\n The array containing the new feature.\n\n \"\"\"\n new_column = f[c] > f[c].shift(o)\n return new_column\n\n\n#\n# Function highest\n#\n\ndef highest(f, c, p = 20):\n r\"\"\"Calculate the highest value on a rolling basis.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str\n Name of the column in the dataframe ``f``.\n p : int\n The period over which to calculate the rolling maximum.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n \"\"\"\n new_column = f[c].rolling(p).max()\n return new_column\n\n\n#\n# Function hlrange\n#\n\ndef hlrange(f, p = 1):\n r\"\"\"Calculate the Range, the difference between High and Low.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe with columns ``high`` and ``low``.\n p : int\n The period over which the range is calculated.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n \"\"\"\n new_column = highest(f, 'high', p) - lowest(f, 'low', p)\n return new_column\n\n\n#\n# Function lower\n#\n\ndef lower(f, c, o = 1):\n r\"\"\"Determine whether or not a series value is lower than\n the value ``o`` periods back.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str\n Name of the column in the dataframe ``f``.\n o : int, optional\n Offset value for shifting the series.\n\n Returns\n -------\n new_column : pandas.Series (bool)\n The array containing the new feature.\n\n \"\"\"\n new_column = f[c] < f[c].shift(o)\n return new_column\n\n\n#\n# Function lowest\n#\n\ndef lowest(f, c, p = 20):\n r\"\"\"Calculate the lowest value on a rolling basis.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str\n Name of the column in the dataframe ``f``.\n p : int\n The period over which to calculate the rolling minimum.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n \"\"\"\n return f[c].rolling(p).min()\n\n\n#\n# Function ma\n#\n\ndef ma(f, c, p = 20):\n r\"\"\"Calculate the mean on a rolling basis.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str\n Name of the column in the dataframe ``f``.\n p : int\n The period over which to calculate the rolling mean.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n References\n ----------\n *In statistics, a moving average (rolling average or running average)\n is a calculation to analyze data points by creating series of averages\n of different subsets of the full data set* [WIKI_MA]_.\n\n .. [WIKI_MA] https://en.wikipedia.org/wiki/Moving_average\n\n \"\"\"\n new_column = f[c].rolling(p).mean()\n return new_column\n\n\n#\n# Function maratio\n#\n\ndef maratio(f, c, p1 = 1, p2 = 10):\n r\"\"\"Calculate the ratio of two moving averages.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str\n Name of the column in the dataframe ``f``.\n p1 : int\n The period of the first moving average.\n p2 : int\n The period of the second moving average.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n \"\"\"\n new_column = ma(f, c, p1) / ma(f, c, p2)\n return new_column\n\n\n#\n# Function mval\n#\n \ndef mval(f, c):\n r\"\"\"Get the negative value, otherwise zero.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str\n Name of the column in the dataframe ``f``.\n\n Returns\n -------\n new_val : float\n Negative value or zero.\n\n \"\"\"\n new_val = -f[c] if f[c] < 0 else 0\n return new_val\n\n\n#\n# Function net\n#\n\ndef net(f, c='close', o = 1):\n r\"\"\"Calculate the net change of a given column.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str\n Name of the column in the dataframe ``f``.\n o : int, optional\n Offset value for shifting the series.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n References\n ----------\n *Net change is the difference between the closing price of a security\n on the day's trading and the previous day's closing price. Net change\n can be positive or negative and is quoted in terms of dollars* [IP_NET]_.\n\n .. [IP_NET] http://www.investopedia.com/terms/n/netchange.asp\n\n \"\"\"\n new_column = f[c] - f[c].shift(o)\n return new_column\n\n\n#\n# Function netreturn\n#\n\ndef netreturn(f, c, o = 1):\n r\"\"\"Calculate the net return, or Return On Invesment (ROI)\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str\n Name of the column in the dataframe ``f``.\n o : int, optional\n Offset value for shifting the series.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n References\n ----------\n *ROI measures the amount of return on an investment relative to the\n original cost. To calculate ROI, the benefit (or return) of an\n investment is divided by the cost of the investment, and the result\n is expressed as a percentage or a ratio* [IP_ROI]_.\n\n .. [IP_ROI] http://www.investopedia.com/terms/r/returnoninvestment.asp\n\n \"\"\"\n new_column = 100 * pchange1(f, c, o)\n return new_column\n\n\n#\n# Function pchange1\n#\n \ndef pchange1(f, c, o = 1):\n r\"\"\"Calculate the percentage change within the same variable.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str\n Name of the column in the dataframe ``f``.\n o : int\n Offset to the previous value.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n \"\"\"\n new_column = f[c] / f[c].shift(o) - 1.0\n return new_column\n\n\n#\n# Function pchange2\n#\n\ndef pchange2(f, c1, c2):\n r\"\"\"Calculate the percentage change between two variables.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the two columns ``c1`` and ``c2``.\n c1 : str\n Name of the first column in the dataframe ``f``.\n c2 : str\n Name of the second column in the dataframe ``f``.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n \"\"\"\n new_column = f[c1] / f[c2] - 1.0\n return new_column\n\n\n#\n# Function pval\n#\n \ndef pval(f, c):\n r\"\"\"Get the positive value, otherwise zero.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str\n Name of the column in the dataframe ``f``.\n\n Returns\n -------\n new_val : float\n Positive value or zero.\n\n \"\"\"\n new_val = f[c] if f[c] > 0 else 0\n return new_val\n\n\n#\n# Function rindex\n#\n\ndef rindex(f, ci, ch, cl, p = 1):\n r\"\"\"Calculate the *range index* spanning a given period ``p``.\n\n The **range index** is a number between 0 and 100 that\n relates the value of the index column ``ci`` to the\n high column ``ch`` and the low column ``cl``. For example,\n if the low value of the range is 10 and the high value\n is 20, then the range index for a value of 15 would be 50%.\n The range index for 18 would be 80%.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the columns ``ci``, ``ch``, and ``cl``.\n ci : str\n Name of the index column in the dataframe ``f``.\n ch : str\n Name of the high column in the dataframe ``f``.\n cl : str\n Name of the low column in the dataframe ``f``.\n p : int\n The period over which the range index of column ``ci``\n is calculated.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n \"\"\"\n o = p-1 if f[ci].name == 'open' else 0\n hh = highest(f, ch, p)\n ll = lowest(f, cl, p)\n fn = f[ci].shift(o) - ll\n fd = hh - ll\n new_column = 100 * fn / fd\n return new_column\n\n\n#\n# Function rsi\n#\n\ndef rsi(f, c, p = 14):\n r\"\"\"Calculate the Relative Strength Index (RSI).\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``net``.\n c : str\n Name of the column in the dataframe ``f``.\n p : int\n The period over which to calculate the RSI.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n References\n ----------\n *Developed by J. Welles Wilder, the Relative Strength Index (RSI) is a momentum\n oscillator that measures the speed and change of price movements* [SC_RSI]_.\n\n .. [SC_RSI] http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:relative_strength_index_rsi\n\n \"\"\"\n cdiff = 'net'\n vexec(f, cdiff)\n f['pval'] = upc(f, cdiff)\n f['mval'] = dpc(f, cdiff)\n upcs = ma(f, 'pval', p)\n dpcs = ma(f, 'mval', p)\n new_column = 100 - (100 / (1 + (upcs / dpcs)))\n return new_column\n\n\n#\n# Function rtotal\n#\n\ndef rtotal(vec):\n r\"\"\"Calculate the running total.\n\n Parameters\n ----------\n vec : pandas.Series\n The input array for calculating the running total.\n\n Returns\n -------\n running_total : int\n The final running total.\n\n Example\n -------\n\n >>> vec.rolling(window=20).apply(rtotal)\n\n \"\"\"\n tcount = np.count_nonzero(vec)\n fcount = len(vec) - tcount\n running_total = tcount - fcount\n return running_total\n\n\n#\n# Function runs\n#\n\ndef runs(vec):\n r\"\"\"Calculate the total number of runs.\n\n Parameters\n ----------\n vec : pandas.Series\n The input array for calculating the number of runs.\n\n Returns\n -------\n runs_value : int\n The total number of runs.\n\n Example\n -------\n\n >>> vec.rolling(window=20).apply(runs)\n\n \"\"\"\n runs_value = len(list(itertools.groupby(vec)))\n return runs_value\n\n\n#\n# Function runs_test\n#\n\ndef runs_test(f, c, wfuncs, window):\n r\"\"\"Perform a runs test on binary series.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str\n Name of the column in the dataframe ``f``.\n wfuncs : list\n The set of runs test functions to apply to the column:\n\n ``'all'``:\n Run all of the functions below.\n ``'rtotal'``:\n The running total over the ``window`` period.\n ``'runs'``:\n Total number of runs in ``window``.\n ``'streak'``:\n The length of the latest streak.\n ``'zscore'``:\n The Z-Score over the ``window`` period.\n window : int\n The rolling period.\n\n Returns\n -------\n new_features : pandas.DataFrame\n The dataframe containing the runs test features.\n\n References\n ----------\n For more information about runs tests for detecting non-randomness,\n refer to [RUNS]_.\n\n .. [RUNS] http://www.itl.nist.gov/div898/handbook/eda/section3/eda35d.htm\n\n \"\"\"\n\n fc = f[c]\n all_funcs = {'runs' : runs,\n 'streak' : streak,\n 'rtotal' : rtotal,\n 'zscore' : zscore}\n # use all functions\n if 'all' in wfuncs:\n wfuncs = list(all_funcs.keys())\n # apply each of the runs functions\n new_features = pd.DataFrame()\n for w in wfuncs:\n if w in all_funcs:\n new_feature = fc.rolling(window=window).apply(all_funcs[w])\n new_feature.fillna(0, inplace=True)\n new_column_name = PSEP.join([c, w])\n new_feature = new_feature.rename(new_column_name)\n frames = [new_features, new_feature]\n new_features = pd.concat(frames, axis=1)\n else:\n logger.info(\"Runs Function %s not found\", w)\n return new_features\n\n\n#\n# Function split_to_letters\n#\n\ndef split_to_letters(f, c):\n r\"\"\"Separate text into distinct characters.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str\n Name of the text column in the dataframe ``f``.\n\n Returns\n -------\n new_feature : pandas.Series\n The array containing the new feature.\n\n Example\n -------\n The value 'abc' becomes 'a b c'.\n\n \"\"\"\n fc = f[c]\n new_feature = None\n dtype = fc.dtypes\n if dtype == 'object':\n fc.fillna(NULLTEXT, inplace=True)\n maxlen = fc.astype(str).str.len().max()\n if maxlen > 1:\n new_feature = fc.apply(lambda x: BSEP.join(list(x)))\n return new_feature\n\n\n#\n# Function streak\n#\n\ndef streak(vec):\n r\"\"\"Determine the length of the latest streak.\n\n Parameters\n ----------\n vec : pandas.Series\n The input array for calculating the latest streak.\n\n Returns\n -------\n latest_streak : int\n The length of the latest streak.\n\n Example\n -------\n\n >>> vec.rolling(window=20).apply(streak)\n\n \"\"\"\n latest_streak = [len(list(g)) for k, g in itertools.groupby(vec)][-1]\n return latest_streak\n\n\n#\n# Function texplode\n#\n\ndef texplode(f, c):\n r\"\"\"Get dummy values for a text column.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str\n Name of the text column in the dataframe ``f``.\n\n Returns\n -------\n dummies : pandas.DataFrame\n The dataframe containing the dummy variables.\n\n Example\n -------\n\n This function is useful for columns that appear to\n have separate character codes but are consolidated\n into a single column. Here, the column ``c`` is\n transformed into five dummy variables.\n\n === === === === === ===\n c 0_a 1_x 1_b 2_x 2_z\n === === === === === ===\n abz 1 0 1 0 1\n abz 1 0 1 0 1\n axx 1 1 0 1 0\n abz 1 0 1 0 1\n axz 1 1 0 0 1\n === === === === === ===\n\n \"\"\"\n fc = f[c]\n maxlen = fc.astype(str).str.len().max()\n fc.fillna(maxlen * BSEP, inplace=True)\n fpad = str().join(['{:', BSEP, '>', str(maxlen), '}'])\n fcpad = fc.apply(fpad.format)\n fcex = fcpad.apply(lambda x: pd.Series(list(x)))\n dummies = pd.get_dummies(fcex)\n return dummies\n\n\n#\n# Function truehigh\n#\n\ndef truehigh(f):\n r\"\"\"Calculate the *True High* value.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe with columns ``high`` and ``low``.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n References\n ----------\n *Today's high, or the previous close, whichever is higher* [TS_TR]_.\n\n .. [TS_TR] http://help.tradestation.com/09_01/tradestationhelp/charting_definitions/true_range.htm\n\n \"\"\"\n c1 = 'low[1]'\n vexec(f, c1)\n c2 = 'high'\n new_column = f.apply(c2max, axis=1, args=[c1, c2])\n return new_column\n\n\n#\n# Function truelow\n#\n\ndef truelow(f):\n r\"\"\"Calculate the *True Low* value.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe with columns ``high`` and ``low``.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n References\n ----------\n *Today's low, or the previous close, whichever is lower* [TS_TR]_.\n\n \"\"\"\n c1 = 'high[1]'\n vexec(f, c1)\n c2 = 'low'\n new_column = f.apply(c2min, axis=1, args=[c1, c2])\n return new_column\n\n\n#\n# Function truerange\n#\n\ndef truerange(f):\n r\"\"\"Calculate the *True Range* value.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe with columns ``high`` and ``low``.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n References\n ----------\n *True High - True Low* [TS_TR]_.\n\n \"\"\"\n new_column = truehigh(f) - truelow(f)\n return new_column\n\n\n#\n# Function up\n#\n\ndef up(f, c):\n r\"\"\"Find the positive values in the series.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str\n Name of the column in the dataframe ``f``.\n\n Returns\n -------\n new_column : pandas.Series (bool)\n The array containing the new feature.\n\n \"\"\"\n new_column = f[c] > 0\n return new_column\n\n\n#\n# Function upc\n#\n\ndef upc(f, c):\n r\"\"\"Get the positive values, with negative values zeroed.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe with column ``c``.\n c : str\n Name of the column.\n\n Returns\n -------\n new_column : pandas.Series (float)\n The array containing the new feature.\n\n \"\"\"\n new_column = f.apply(pval, axis=1, args=[c])\n return new_column\n\n\n#\n# Function xmadown\n#\n\ndef xmadown(f, c='close', pfast = 20, pslow = 50):\n r\"\"\"Determine those values of the dataframe that are below the\n moving average.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str, optional\n Name of the column in the dataframe ``f``.\n pfast : int, optional\n The period of the fast moving average.\n pslow : int, optional\n The period of the slow moving average.\n\n Returns\n -------\n new_column : pandas.Series (bool)\n The array containing the new feature.\n\n References\n ----------\n *In the statistics of time series, and in particular the analysis\n of financial time series for stock trading purposes, a moving-average\n crossover occurs when, on plotting two moving averages each based\n on different degrees of smoothing, the traces of these moving averages\n cross* [WIKI_XMA]_.\n\n .. [WIKI_XMA] https://en.wikipedia.org/wiki/Moving_average_crossover\n\n \"\"\"\n sma = ma(f, c, pfast)\n sma_prev = sma.shift(1)\n lma = ma(f, c, pslow)\n lma_prev = lma.shift(1)\n new_column = (sma < lma) & (sma_prev > lma_prev)\n return new_column\n\n\n#\n# Function xmaup\n#\n\ndef xmaup(f, c='close', pfast = 20, pslow = 50):\n r\"\"\"Determine those values of the dataframe that are below the\n moving average.\n\n Parameters\n ----------\n f : pandas.DataFrame\n Dataframe containing the column ``c``.\n c : str, optional\n Name of the column in the dataframe ``f``.\n pfast : int, optional\n The period of the fast moving average.\n pslow : int, optional\n The period of the slow moving average.\n\n Returns\n -------\n new_column : pandas.Series (bool)\n The array containing the new feature.\n\n References\n ----------\n *In the statistics of time series, and in particular the analysis\n of financial time series for stock trading purposes, a moving-average\n crossover occurs when, on plotting two moving averages each based\n on different degrees of smoothing, the traces of these moving averages\n cross* [WIKI_XMA]_.\n\n \"\"\"\n sma = ma(f, c, pfast)\n sma_prev = sma.shift(1)\n lma = ma(f, c, pslow)\n lma_prev = lma.shift(1)\n new_column = (sma > lma) & (sma_prev < lma_prev)\n return new_column\n\n\n#\n# Function zscore\n#\n\ndef zscore(vec):\n r\"\"\"Calculate the Z-Score.\n\n Parameters\n ----------\n vec : pandas.Series\n The input array for calculating the Z-Score.\n\n Returns\n -------\n zscore : float\n The value of the Z-Score.\n\n References\n ----------\n To calculate the Z-Score, you can find more information here [ZSCORE]_.\n\n .. [ZSCORE] https://en.wikipedia.org/wiki/Standard_score\n\n Example\n -------\n\n >>> vec.rolling(window=20).apply(zscore)\n\n \"\"\"\n n1 = np.count_nonzero(vec)\n n2 = len(vec) - n1\n fac1 = float(2 * n1 * n2)\n fac2 = float(n1 + n2)\n rbar = fac1 / fac2 + 1\n sr2num = fac1 * (fac1 - n1 - n2)\n sr2den = math.pow(fac2, 2) * (fac2 - 1)\n sr = math.sqrt(sr2num / sr2den)\n if sr2den and sr:\n zscore = (runs(vec) - rbar) / sr\n else:\n zscore = 0\n return zscore\n"
] |
[
[
"pandas.ewma",
"pandas.concat",
"pandas.to_datetime",
"pandas.Series",
"pandas.DataFrame",
"numpy.diff",
"numpy.count_nonzero",
"pandas.get_dummies"
]
] |
bhavika/transformers
|
[
"65cf33e7e53cd46313f3655f274b3f6ca0fd679d",
"65cf33e7e53cd46313f3655f274b3f6ca0fd679d"
] |
[
"src/transformers/models/wavlm/modeling_wavlm.py",
"tests/bart/test_modeling_bart.py"
] |
[
"# coding=utf-8\n# Copyright 2021 The Fairseq Authors, Microsoft Research, and The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\" PyTorch WavLM model.\"\"\"\n\nimport math\nimport warnings\nfrom dataclasses import dataclass\nfrom typing import Optional, Tuple, Union\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport torch.utils.checkpoint\nfrom torch import nn\nfrom torch.nn import CrossEntropyLoss\n\nfrom ...activations import ACT2FN\nfrom ...deepspeed import is_deepspeed_zero3_enabled\nfrom ...file_utils import (\n ModelOutput,\n add_code_sample_docstrings,\n add_start_docstrings,\n add_start_docstrings_to_model_forward,\n)\nfrom ...modeling_outputs import BaseModelOutput, CausalLMOutput, SequenceClassifierOutput, TokenClassifierOutput\nfrom ...modeling_utils import PreTrainedModel\nfrom ...pytorch_utils import torch_int_div\nfrom ...utils import logging\nfrom .configuration_wavlm import WavLMConfig\n\n\nlogger = logging.get_logger(__name__)\n\n\n_HIDDEN_STATES_START_POSITION = 2\n\n# General docstring\n_CONFIG_FOR_DOC = \"WavLMConfig\"\n_PROCESSOR_FOR_DOC = \"Wav2Vec2Processor\"\n\n# Base docstring\n_CHECKPOINT_FOR_DOC = \"patrickvonplaten/wavlm-libri-clean-100h-base-plus\"\n_EXPECTED_OUTPUT_SHAPE = [1, 292, 768]\n\n# CTC docstring\n_CTC_EXPECTED_OUTPUT = \"'mister quilter is the aposle of the middle classes and we are glad to welcome his gospel'\"\n_CTC_EXPECTED_LOSS = 12.51\n\n# Audio class docstring\n_FEAT_EXTRACTOR_FOR_DOC = \"Wav2Vec2FeatureExtractor\"\n_SEQ_CLASS_CHECKPOINT = \"hf-internal-testing/tiny-random-wavlm\"\n_SEQ_CLASS_EXPECTED_OUTPUT = \"'no'\" # TODO(anton) - could you quickly fine-tune a KS WavLM Model\n_SEQ_CLASS_EXPECTED_LOSS = 0.7 # TODO(anton) - could you quickly fine-tune a KS WavLM Model\n\n# Frame class docstring\n_FRAME_CLASS_CHECKPOINT = \"microsoft/wavlm-base-plus-sd\"\n_FRAME_EXPECTED_OUTPUT = [0, 0]\n\n# Speaker Verification docstring\n_XVECTOR_CHECKPOINT = \"microsoft/wavlm-base-plus-sv\"\n_XVECTOR_EXPECTED_OUTPUT = 0.97\n\nWAVLM_PRETRAINED_MODEL_ARCHIVE_LIST = [\n \"microsoft/wavlm-base\",\n \"microsoft/wavlm-base-plus\",\n \"microsoft/wavlm-large\",\n # See all WavLM models at https://huggingface.co/models?filter=wavlm\n]\n\n\n@dataclass\nclass WavLMBaseModelOutput(ModelOutput):\n \"\"\"\n Output type of [`WavLMBaseModelOutput`], with potential hidden states and attentions.\n\n Args:\n last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):\n Sequence of hidden-states at the output of the last layer of the model.\n extract_features (`torch.FloatTensor` of shape `(batch_size, sequence_length, conv_dim[-1])`):\n Sequence of extracted feature vectors of the last convolutional layer of the model.\n hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):\n Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of\n shape `(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,\n sequence_length)`.\n\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention\n heads.\n \"\"\"\n\n last_hidden_state: torch.FloatTensor = None\n extract_features: torch.FloatTensor = None\n hidden_states: Optional[Tuple[torch.FloatTensor]] = None\n attentions: Optional[Tuple[torch.FloatTensor]] = None\n\n\n@dataclass\nclass XVectorOutput(ModelOutput):\n \"\"\"\n Output type of [`Wav2Vec2ForXVector`].\n\n Args:\n loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):\n Classification loss.\n logits (`torch.FloatTensor` of shape `(batch_size, config.xvector_output_dim)`):\n Classification hidden states before AMSoftmax.\n embeddings (`torch.FloatTensor` of shape `(batch_size, config.xvector_output_dim)`):\n Utterance embeddings used for vector similarity-based retrieval.\n hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):\n Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of\n shape `(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the initial embedding outputs.\n attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):\n Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,\n sequence_length)`.\n\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention\n heads.\n \"\"\"\n\n loss: Optional[torch.FloatTensor] = None\n logits: torch.FloatTensor = None\n embeddings: torch.FloatTensor = None\n hidden_states: Optional[Tuple[torch.FloatTensor]] = None\n attentions: Optional[Tuple[torch.FloatTensor]] = None\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2._compute_mask_indices\ndef _compute_mask_indices(\n shape: Tuple[int, int],\n mask_prob: float,\n mask_length: int,\n attention_mask: Optional[torch.LongTensor] = None,\n min_masks: int = 0,\n) -> np.ndarray:\n \"\"\"\n Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for\n ASR](https://arxiv.org/abs/1904.08779). Note that this method is not optimized to run on TPU and should be run on\n CPU as part of the preprocessing during training.\n\n Args:\n shape: The shape for which to compute masks. This should be of a tuple of size 2 where\n the first element is the batch size and the second element is the length of the axis to span.\n mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of\n independently generated mask spans of length `mask_length` is computed by\n `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the\n actual percentage will be smaller.\n mask_length: size of the mask\n min_masks: minimum number of masked spans\n attention_mask: A (right-padded) attention mask which independently shortens the feature axis of\n each batch dimension.\n \"\"\"\n batch_size, sequence_length = shape\n\n if mask_length < 1:\n raise ValueError(\"`mask_length` has to be bigger than 0.\")\n\n if mask_length > sequence_length:\n raise ValueError(\n f\"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}\"\n f\" and `sequence_length`: {sequence_length}`\"\n )\n\n # epsilon is used for probabilistic rounding\n epsilon = np.random.rand(1).item()\n\n def compute_num_masked_span(input_length):\n \"\"\"Given input length, compute how many spans should be masked\"\"\"\n num_masked_span = int(mask_prob * input_length / mask_length + epsilon)\n num_masked_span = max(num_masked_span, min_masks)\n\n # make sure num masked span <= sequence_length\n if num_masked_span * mask_length > sequence_length:\n num_masked_span = sequence_length // mask_length\n\n # make sure num_masked span is also <= input_length - (mask_length - 1)\n if input_length - (mask_length - 1) < num_masked_span:\n num_masked_span = max(input_length - (mask_length - 1), 0)\n\n return num_masked_span\n\n # compute number of masked spans in batch\n input_lengths = (\n attention_mask.sum(-1).detach().tolist()\n if attention_mask is not None\n else [sequence_length for _ in range(batch_size)]\n )\n\n # SpecAugment mask to fill\n spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=np.bool)\n spec_aug_mask_idxs = []\n\n max_num_masked_span = compute_num_masked_span(sequence_length)\n\n if max_num_masked_span == 0:\n return spec_aug_mask\n\n for input_length in input_lengths:\n # compute num of masked spans for this input\n num_masked_span = compute_num_masked_span(input_length)\n\n # get random indices to mask\n spec_aug_mask_idx = np.random.choice(\n np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False\n )\n\n # pick first sampled index that will serve as a dummy index to pad vector\n # to ensure same dimension for all batches due to probabilistic rounding\n # Picking first sample just pads those vectors twice.\n if len(spec_aug_mask_idx) == 0:\n # this case can only happen if `input_length` is strictly smaller then\n # `sequence_length` in which case the last token has to be a padding\n # token which we can use as a dummy mask id\n dummy_mask_idx = sequence_length - 1\n else:\n dummy_mask_idx = spec_aug_mask_idx[0]\n\n spec_aug_mask_idx = np.concatenate(\n [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx]\n )\n spec_aug_mask_idxs.append(spec_aug_mask_idx)\n\n spec_aug_mask_idxs = np.array(spec_aug_mask_idxs)\n\n # expand masked indices to masked spans\n spec_aug_mask_idxs = np.broadcast_to(\n spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length)\n )\n spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length)\n\n # add offset to the starting indexes so that that indexes now create a span\n offsets = np.arange(mask_length)[None, None, :]\n offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape(\n batch_size, max_num_masked_span * mask_length\n )\n spec_aug_mask_idxs = spec_aug_mask_idxs + offsets\n\n # ensure that we cannot have indices larger than sequence_length\n if spec_aug_mask_idxs.max() > sequence_length - 1:\n spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1\n\n # scatter indices to mask\n np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1)\n\n return spec_aug_mask\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2NoLayerNormConvLayer with Wav2Vec2->WavLM\nclass WavLMNoLayerNormConvLayer(nn.Module):\n def __init__(self, config, layer_id=0):\n super().__init__()\n self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1\n self.out_conv_dim = config.conv_dim[layer_id]\n\n self.conv = nn.Conv1d(\n self.in_conv_dim,\n self.out_conv_dim,\n kernel_size=config.conv_kernel[layer_id],\n stride=config.conv_stride[layer_id],\n bias=config.conv_bias,\n )\n self.activation = ACT2FN[config.feat_extract_activation]\n\n def forward(self, hidden_states):\n hidden_states = self.conv(hidden_states)\n hidden_states = self.activation(hidden_states)\n return hidden_states\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2LayerNormConvLayer with Wav2Vec2->WavLM\nclass WavLMLayerNormConvLayer(nn.Module):\n def __init__(self, config, layer_id=0):\n super().__init__()\n self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1\n self.out_conv_dim = config.conv_dim[layer_id]\n\n self.conv = nn.Conv1d(\n self.in_conv_dim,\n self.out_conv_dim,\n kernel_size=config.conv_kernel[layer_id],\n stride=config.conv_stride[layer_id],\n bias=config.conv_bias,\n )\n self.layer_norm = nn.LayerNorm(self.out_conv_dim, elementwise_affine=True)\n self.activation = ACT2FN[config.feat_extract_activation]\n\n def forward(self, hidden_states):\n hidden_states = self.conv(hidden_states)\n\n hidden_states = hidden_states.transpose(-2, -1)\n hidden_states = self.layer_norm(hidden_states)\n hidden_states = hidden_states.transpose(-2, -1)\n\n hidden_states = self.activation(hidden_states)\n return hidden_states\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2GroupNormConvLayer with Wav2Vec2->WavLM\nclass WavLMGroupNormConvLayer(nn.Module):\n def __init__(self, config, layer_id=0):\n super().__init__()\n self.in_conv_dim = config.conv_dim[layer_id - 1] if layer_id > 0 else 1\n self.out_conv_dim = config.conv_dim[layer_id]\n\n self.conv = nn.Conv1d(\n self.in_conv_dim,\n self.out_conv_dim,\n kernel_size=config.conv_kernel[layer_id],\n stride=config.conv_stride[layer_id],\n bias=config.conv_bias,\n )\n self.activation = ACT2FN[config.feat_extract_activation]\n\n self.layer_norm = nn.GroupNorm(num_groups=self.out_conv_dim, num_channels=self.out_conv_dim, affine=True)\n\n def forward(self, hidden_states):\n hidden_states = self.conv(hidden_states)\n hidden_states = self.layer_norm(hidden_states)\n hidden_states = self.activation(hidden_states)\n return hidden_states\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2PositionalConvEmbedding with Wav2Vec2->WavLM\nclass WavLMPositionalConvEmbedding(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.conv = nn.Conv1d(\n config.hidden_size,\n config.hidden_size,\n kernel_size=config.num_conv_pos_embeddings,\n padding=config.num_conv_pos_embeddings // 2,\n groups=config.num_conv_pos_embedding_groups,\n )\n\n if is_deepspeed_zero3_enabled():\n import deepspeed\n\n with deepspeed.zero.GatheredParameters(self.conv.weight, modifier_rank=0):\n self.conv = nn.utils.weight_norm(self.conv, name=\"weight\", dim=2)\n deepspeed.zero.register_external_parameter(self, self.conv.weight_v)\n deepspeed.zero.register_external_parameter(self, self.conv.weight_g)\n else:\n self.conv = nn.utils.weight_norm(self.conv, name=\"weight\", dim=2)\n\n self.padding = WavLMSamePadLayer(config.num_conv_pos_embeddings)\n self.activation = ACT2FN[config.feat_extract_activation]\n\n def forward(self, hidden_states):\n hidden_states = hidden_states.transpose(1, 2)\n\n hidden_states = self.conv(hidden_states)\n hidden_states = self.padding(hidden_states)\n hidden_states = self.activation(hidden_states)\n\n hidden_states = hidden_states.transpose(1, 2)\n return hidden_states\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2SamePadLayer with Wav2Vec2->WavLM\nclass WavLMSamePadLayer(nn.Module):\n def __init__(self, num_conv_pos_embeddings):\n super().__init__()\n self.num_pad_remove = 1 if num_conv_pos_embeddings % 2 == 0 else 0\n\n def forward(self, hidden_states):\n if self.num_pad_remove > 0:\n hidden_states = hidden_states[:, :, : -self.num_pad_remove]\n return hidden_states\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2FeatureEncoder with Wav2Vec2->WavLM\nclass WavLMFeatureEncoder(nn.Module):\n \"\"\"Construct the features from raw audio waveform\"\"\"\n\n def __init__(self, config):\n super().__init__()\n\n if config.feat_extract_norm == \"group\":\n conv_layers = [WavLMGroupNormConvLayer(config, layer_id=0)] + [\n WavLMNoLayerNormConvLayer(config, layer_id=i + 1) for i in range(config.num_feat_extract_layers - 1)\n ]\n elif config.feat_extract_norm == \"layer\":\n conv_layers = [WavLMLayerNormConvLayer(config, layer_id=i) for i in range(config.num_feat_extract_layers)]\n else:\n raise ValueError(\n f\"`config.feat_extract_norm` is {config.feat_extract_norm}, but has to be one of ['group', 'layer']\"\n )\n self.conv_layers = nn.ModuleList(conv_layers)\n self.gradient_checkpointing = False\n self._requires_grad = True\n\n def _freeze_parameters(self):\n for param in self.parameters():\n param.requires_grad = False\n self._requires_grad = False\n\n def forward(self, input_values):\n hidden_states = input_values[:, None]\n\n # make sure hidden_states require grad for gradient_checkpointing\n if self._requires_grad and self.training:\n hidden_states.requires_grad = True\n\n for conv_layer in self.conv_layers:\n if self._requires_grad and self.gradient_checkpointing and self.training:\n\n def create_custom_forward(module):\n def custom_forward(*inputs):\n return module(*inputs)\n\n return custom_forward\n\n hidden_states = torch.utils.checkpoint.checkpoint(\n create_custom_forward(conv_layer),\n hidden_states,\n )\n else:\n hidden_states = conv_layer(hidden_states)\n\n return hidden_states\n\n\nclass WavLMFeatureExtractor(WavLMFeatureEncoder):\n def __init__(self, config):\n super().__init__(config)\n warnings.warn(\n f\"The class `{self.__class__.__name__}` has been depreciated \"\n \"and will be removed in Transformers v5. \"\n f\"Use `{self.__class__.__bases__[0].__name__}` instead.\",\n FutureWarning,\n )\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2FeatureProjection with Wav2Vec2->WavLM\nclass WavLMFeatureProjection(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)\n self.projection = nn.Linear(config.conv_dim[-1], config.hidden_size)\n self.dropout = nn.Dropout(config.feat_proj_dropout)\n\n def forward(self, hidden_states):\n # non-projected hidden states are needed for quantization\n norm_hidden_states = self.layer_norm(hidden_states)\n hidden_states = self.projection(norm_hidden_states)\n hidden_states = self.dropout(hidden_states)\n return hidden_states, norm_hidden_states\n\n\nclass WavLMAttention(nn.Module):\n \"\"\"Multi-headed attention from 'Attention Is All You Need' paper\"\"\"\n\n def __init__(\n self,\n embed_dim: int,\n num_heads: int,\n dropout: float = 0.0,\n num_buckets: int = 320,\n max_distance: int = 800,\n has_relative_position_bias: bool = True,\n ):\n super().__init__()\n self.embed_dim = embed_dim\n self.num_heads = num_heads\n self.dropout = dropout\n self.head_dim = embed_dim // num_heads\n\n if (self.head_dim * num_heads) != self.embed_dim:\n raise ValueError(\n f\"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}\"\n f\" and `num_heads`: {num_heads}).\"\n )\n self.scaling = self.head_dim**-0.5\n\n self.k_proj = nn.Linear(embed_dim, embed_dim)\n self.v_proj = nn.Linear(embed_dim, embed_dim)\n self.q_proj = nn.Linear(embed_dim, embed_dim)\n self.out_proj = nn.Linear(embed_dim, embed_dim)\n\n self.num_buckets = num_buckets\n self.max_distance = max_distance\n\n self.gru_rel_pos_const = nn.Parameter(torch.ones(1, self.num_heads, 1, 1))\n self.gru_rel_pos_linear = nn.Linear(self.head_dim, 8)\n\n if has_relative_position_bias:\n self.rel_attn_embed = nn.Embedding(self.num_buckets, self.num_heads)\n\n def forward(\n self,\n hidden_states: torch.Tensor,\n attention_mask: Optional[torch.Tensor] = None,\n position_bias: Optional[torch.Tensor] = None,\n output_attentions: bool = False,\n index=0,\n ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:\n \"\"\"Attention layer with relative attention\"\"\"\n bsz, tgt_len, _ = hidden_states.size()\n\n # first pass of attention layer creates position bias\n if position_bias is None:\n position_bias = self.compute_bias(tgt_len, tgt_len)\n position_bias = (\n position_bias.unsqueeze(0).repeat(bsz, 1, 1, 1).view(bsz * self.num_heads, tgt_len, tgt_len)\n )\n\n # Compute relative position bias:\n # 1) get reshape hidden_states\n gated_hidden_states = hidden_states.view(hidden_states.shape[:-1] + (self.num_heads, -1))\n gated_hidden_states = gated_hidden_states.permute(0, 2, 1, 3)\n\n # 2) project hidden states\n relative_position_proj = self.gru_rel_pos_linear(gated_hidden_states)\n relative_position_proj = relative_position_proj.view(gated_hidden_states.shape[:-1] + (2, 4)).sum(-1)\n\n # 3) compute gate for position bias from projected hidden states\n gate_a, gate_b = torch.sigmoid(relative_position_proj).chunk(2, dim=-1)\n gate_output = gate_a * (gate_b * self.gru_rel_pos_const - 1.0) + 2.0\n\n # 4) apply gate to position bias to compute gated position_bias\n gated_position_bias = gate_output.view(bsz * self.num_heads, -1, 1) * position_bias\n gated_position_bias = gated_position_bias.view((-1, tgt_len, tgt_len))\n\n attn_output, attn_weights = self.torch_multi_head_self_attention(\n hidden_states, attention_mask, gated_position_bias, output_attentions\n )\n\n return attn_output, attn_weights, position_bias\n\n def torch_multi_head_self_attention(\n self,\n hidden_states: torch.FloatTensor,\n attention_mask: Union[torch.LongTensor, torch.BoolTensor],\n gated_position_bias: torch.FloatTensor,\n output_attentions: bool,\n ) -> (torch.FloatTensor, torch.FloatTensor):\n \"\"\"simple wrapper around torch's multi_head_attention_forward function\"\"\"\n # self-attention assumes q = k = v\n query = key = value = hidden_states.transpose(0, 1)\n key_padding_mask = attention_mask.ne(1) if attention_mask is not None else None\n\n # disable bias and add_zero_attn\n bias_k = bias_v = None\n add_zero_attn = False\n\n # PyTorch 1.3.0 has F.multi_head_attention_forward defined\n # so no problem with backwards compatibility\n attn_output, attn_weights = F.multi_head_attention_forward(\n query,\n key,\n value,\n self.embed_dim,\n self.num_heads,\n torch.empty([0]),\n torch.cat((self.q_proj.bias, self.k_proj.bias, self.v_proj.bias)),\n bias_k,\n bias_v,\n add_zero_attn,\n self.dropout,\n self.out_proj.weight,\n self.out_proj.bias,\n self.training,\n key_padding_mask,\n output_attentions,\n gated_position_bias,\n use_separate_proj_weight=True,\n q_proj_weight=self.q_proj.weight,\n k_proj_weight=self.k_proj.weight,\n v_proj_weight=self.v_proj.weight,\n )\n\n # [Seq_Len, Batch Size, ...] -> [Batch Size, Seq_Len, ...]\n attn_output = attn_output.transpose(0, 1)\n\n if attn_weights is not None:\n # IMPORTANT: Attention weights are averaged weights\n # here which should not be the case. This is an open issue\n # on PyTorch: https://github.com/pytorch/pytorch/issues/32590\n attn_weights = attn_weights[:, None].broadcast_to(\n attn_weights.shape[:1] + (self.num_heads,) + attn_weights.shape[1:]\n )\n\n return attn_output, attn_weights\n\n def compute_bias(self, query_length: int, key_length: int) -> torch.FloatTensor:\n context_position = torch.arange(query_length, dtype=torch.long)[:, None]\n memory_position = torch.arange(key_length, dtype=torch.long)[None, :]\n relative_position = memory_position - context_position\n relative_position_bucket = self._relative_positions_bucket(relative_position)\n relative_position_bucket = relative_position_bucket.to(self.rel_attn_embed.weight.device)\n values = self.rel_attn_embed(relative_position_bucket)\n values = values.permute([2, 0, 1])\n return values\n\n def _relative_positions_bucket(self, relative_positions: torch.FloatTensor) -> torch.FloatTensor:\n num_buckets = self.num_buckets // 2\n\n relative_buckets = (relative_positions > 0).to(torch.long) * num_buckets\n relative_positions = torch.abs(relative_positions)\n\n max_exact = num_buckets // 2\n is_small = relative_positions < max_exact\n\n relative_positions_if_large = torch.log(relative_positions.float() / max_exact)\n relative_positions_if_large = relative_positions_if_large / math.log(self.max_distance / max_exact)\n relative_positions_if_large = relative_positions_if_large * (num_buckets - max_exact)\n relative_postion_if_large = (max_exact + relative_positions_if_large).to(torch.long)\n relative_postion_if_large = torch.min(\n relative_postion_if_large, torch.full_like(relative_postion_if_large, num_buckets - 1)\n )\n\n relative_buckets += torch.where(is_small, relative_positions, relative_postion_if_large)\n return relative_buckets\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2FeedForward with Wav2Vec2->WavLM\nclass WavLMFeedForward(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.intermediate_dropout = nn.Dropout(config.activation_dropout)\n\n self.intermediate_dense = nn.Linear(config.hidden_size, config.intermediate_size)\n if isinstance(config.hidden_act, str):\n self.intermediate_act_fn = ACT2FN[config.hidden_act]\n else:\n self.intermediate_act_fn = config.hidden_act\n\n self.output_dense = nn.Linear(config.intermediate_size, config.hidden_size)\n self.output_dropout = nn.Dropout(config.hidden_dropout)\n\n def forward(self, hidden_states):\n hidden_states = self.intermediate_dense(hidden_states)\n hidden_states = self.intermediate_act_fn(hidden_states)\n hidden_states = self.intermediate_dropout(hidden_states)\n\n hidden_states = self.output_dense(hidden_states)\n hidden_states = self.output_dropout(hidden_states)\n return hidden_states\n\n\nclass WavLMEncoderLayer(nn.Module):\n def __init__(self, config: WavLMConfig, has_relative_position_bias: bool = True):\n super().__init__()\n self.attention = WavLMAttention(\n embed_dim=config.hidden_size,\n num_heads=config.num_attention_heads,\n dropout=config.attention_dropout,\n num_buckets=config.num_buckets,\n max_distance=config.max_bucket_distance,\n has_relative_position_bias=has_relative_position_bias,\n )\n self.dropout = nn.Dropout(config.hidden_dropout)\n self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.feed_forward = WavLMFeedForward(config)\n self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n\n def forward(self, hidden_states, attention_mask=None, position_bias=None, output_attentions=False, index=0):\n attn_residual = hidden_states\n hidden_states, attn_weights, position_bias = self.attention(\n hidden_states,\n attention_mask=attention_mask,\n position_bias=position_bias,\n output_attentions=output_attentions,\n index=index,\n )\n hidden_states = self.dropout(hidden_states)\n hidden_states = attn_residual + hidden_states\n\n hidden_states = self.layer_norm(hidden_states)\n\n hidden_states = hidden_states + self.feed_forward(hidden_states)\n hidden_states = self.final_layer_norm(hidden_states)\n\n outputs = (hidden_states, position_bias)\n\n if output_attentions:\n outputs += (attn_weights,)\n\n return outputs\n\n\nclass WavLMEncoderLayerStableLayerNorm(nn.Module):\n def __init__(self, config: WavLMConfig, has_relative_position_bias: bool = True):\n super().__init__()\n self.attention = WavLMAttention(\n embed_dim=config.hidden_size,\n num_heads=config.num_attention_heads,\n dropout=config.attention_dropout,\n num_buckets=config.num_buckets,\n max_distance=config.max_bucket_distance,\n has_relative_position_bias=has_relative_position_bias,\n )\n self.dropout = nn.Dropout(config.hidden_dropout)\n self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.feed_forward = WavLMFeedForward(config)\n self.final_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n\n def forward(self, hidden_states, attention_mask=None, position_bias=None, output_attentions=False):\n attn_residual = hidden_states\n hidden_states = self.layer_norm(hidden_states)\n hidden_states, attn_weights, position_bias = self.attention(\n hidden_states,\n attention_mask=attention_mask,\n position_bias=position_bias,\n output_attentions=output_attentions,\n )\n hidden_states = self.dropout(hidden_states)\n hidden_states = attn_residual + hidden_states\n hidden_states = hidden_states + self.feed_forward(self.final_layer_norm(hidden_states))\n\n outputs = (hidden_states, position_bias)\n\n if output_attentions:\n outputs += (attn_weights,)\n\n return outputs\n\n\nclass WavLMEncoder(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.config = config\n self.pos_conv_embed = WavLMPositionalConvEmbedding(config)\n self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.dropout = nn.Dropout(config.hidden_dropout)\n self.layers = nn.ModuleList(\n [WavLMEncoderLayer(config, has_relative_position_bias=(i == 0)) for i in range(config.num_hidden_layers)]\n )\n self.gradient_checkpointing = False\n\n def forward(\n self,\n hidden_states,\n attention_mask=None,\n output_attentions=False,\n output_hidden_states=False,\n return_dict=True,\n ):\n all_hidden_states = () if output_hidden_states else None\n all_self_attentions = () if output_attentions else None\n\n if attention_mask is not None:\n # make sure padded tokens output 0\n hidden_states[~attention_mask] = 0.0\n\n position_embeddings = self.pos_conv_embed(hidden_states)\n hidden_states = hidden_states + position_embeddings\n hidden_states = self.layer_norm(hidden_states)\n hidden_states = self.dropout(hidden_states)\n\n deepspeed_zero3_is_enabled = is_deepspeed_zero3_enabled()\n position_bias = None\n\n for i, layer in enumerate(self.layers):\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)\n dropout_probability = np.random.uniform(0, 1)\n\n skip_the_layer = self.training and i > 0 and (dropout_probability < self.config.layerdrop)\n if not skip_the_layer or deepspeed_zero3_is_enabled:\n # under deepspeed zero3 all gpus must run in sync\n if self.gradient_checkpointing and self.training:\n # create gradient checkpointing function\n def create_custom_forward(module):\n def custom_forward(*inputs):\n return module(*inputs, output_attentions)\n\n return custom_forward\n\n layer_outputs = torch.utils.checkpoint.checkpoint(\n create_custom_forward(layer),\n hidden_states,\n attention_mask,\n position_bias,\n )\n else:\n layer_outputs = layer(\n hidden_states,\n attention_mask=attention_mask,\n position_bias=position_bias,\n output_attentions=output_attentions,\n index=i,\n )\n\n hidden_states, position_bias = layer_outputs[:2]\n\n if skip_the_layer:\n layer_outputs = (None, None)\n\n if output_attentions:\n all_self_attentions = all_self_attentions + (layer_outputs[2],)\n\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if not return_dict:\n return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)\n return BaseModelOutput(\n last_hidden_state=hidden_states,\n hidden_states=all_hidden_states,\n attentions=all_self_attentions,\n )\n\n\nclass WavLMEncoderStableLayerNorm(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.config = config\n self.pos_conv_embed = WavLMPositionalConvEmbedding(config)\n self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)\n self.dropout = nn.Dropout(config.hidden_dropout)\n self.layers = nn.ModuleList(\n [\n WavLMEncoderLayerStableLayerNorm(config, has_relative_position_bias=(i == 0))\n for i in range(config.num_hidden_layers)\n ]\n )\n self.gradient_checkpointing = False\n\n def forward(\n self,\n hidden_states,\n attention_mask=None,\n output_attentions=False,\n output_hidden_states=False,\n return_dict=True,\n ):\n all_hidden_states = () if output_hidden_states else None\n all_self_attentions = () if output_attentions else None\n\n if attention_mask is not None:\n # make sure padded tokens are not attended to\n hidden_states[~attention_mask] = 0\n\n position_embeddings = self.pos_conv_embed(hidden_states)\n hidden_states = hidden_states + position_embeddings\n hidden_states = self.dropout(hidden_states)\n\n deepspeed_zero3_is_enabled = is_deepspeed_zero3_enabled()\n position_bias = None\n\n for i, layer in enumerate(self.layers):\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)\n dropout_probability = np.random.uniform(0, 1)\n\n skip_the_layer = self.training and i > 0 and (dropout_probability < self.config.layerdrop)\n if not skip_the_layer or deepspeed_zero3_is_enabled:\n # under deepspeed zero3 all gpus must run in sync\n # XXX: could optimize this like synced_gpus in generate_utils but not sure if it's worth the code complication\n if self.gradient_checkpointing and self.training:\n # create gradient checkpointing function\n def create_custom_forward(module):\n def custom_forward(*inputs):\n return module(*inputs, output_attentions)\n\n return custom_forward\n\n layer_outputs = torch.utils.checkpoint.checkpoint(\n create_custom_forward(layer),\n hidden_states,\n attention_mask,\n position_bias,\n )\n else:\n layer_outputs = layer(\n hidden_states,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n position_bias=position_bias,\n )\n hidden_states, position_bias = layer_outputs[:2]\n\n if skip_the_layer:\n layer_outputs = (None, None)\n\n if output_attentions:\n all_self_attentions = all_self_attentions + (layer_outputs[2],)\n\n hidden_states = self.layer_norm(hidden_states)\n\n if output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if not return_dict:\n return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)\n return BaseModelOutput(\n last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_self_attentions\n )\n\n\nclass WavLMGumbelVectorQuantizer(nn.Module):\n \"\"\"\n Vector quantization using gumbel softmax. See [CATEGORICAL REPARAMETERIZATION WITH\n GUMBEL-SOFTMAX](https://arxiv.org/pdf/1611.01144.pdf) for more information.\n \"\"\"\n\n def __init__(self, config):\n super().__init__()\n self.num_groups = config.num_codevector_groups\n self.num_vars = config.num_codevectors_per_group\n\n if config.codevector_dim % self.num_groups != 0:\n raise ValueError(\n f\"`config.codevector_dim {config.codevector_dim} must be divisible\"\n f\" by `config.num_codevector_groups` {self.num_groups} \"\n \"for concatenation.\"\n )\n\n # storage for codebook variables (codewords)\n self.codevectors = nn.Parameter(\n torch.FloatTensor(1, self.num_groups * self.num_vars, config.codevector_dim // self.num_groups)\n )\n self.weight_proj = nn.Linear(config.conv_dim[-1], self.num_groups * self.num_vars)\n\n # can be decayed for training\n self.temperature = 2\n\n @staticmethod\n def _compute_perplexity(probs):\n marginal_probs = probs.mean(dim=0)\n perplexity = torch.exp(-torch.sum(marginal_probs * torch.log(marginal_probs + 1e-7), dim=-1)).sum()\n return perplexity\n\n def forward(self, hidden_states):\n batch_size, sequence_length, hidden_size = hidden_states.shape\n\n # project to codevector dim\n hidden_states = self.weight_proj(hidden_states)\n hidden_states = hidden_states.view(batch_size * sequence_length * self.num_groups, -1)\n\n if self.training:\n # sample code vector probs via gumbel in differentiateable way\n codevector_probs = nn.functional.gumbel_softmax(hidden_states.float(), tau=self.temperature, hard=True)\n codevector_probs = codevector_probs.type_as(hidden_states)\n\n # compute perplexity\n codevector_soft_dist = torch.softmax(\n hidden_states.view(batch_size * sequence_length, self.num_groups, -1).float(), dim=-1\n )\n perplexity = self._compute_perplexity(codevector_soft_dist)\n else:\n # take argmax in non-differentiable way\n # comptute hard codevector distribution (one hot)\n codevector_idx = hidden_states.argmax(dim=-1)\n codevector_probs = hidden_states.new_zeros(*hidden_states.shape).scatter_(\n -1, codevector_idx.view(-1, 1), 1.0\n )\n codevector_probs = codevector_probs.view(batch_size * sequence_length, self.num_groups, -1)\n\n perplexity = self._compute_perplexity(codevector_probs)\n\n codevector_probs = codevector_probs.view(batch_size * sequence_length, -1)\n # use probs to retrieve codevectors\n codevectors_per_group = codevector_probs.unsqueeze(-1) * self.codevectors\n codevectors = codevectors_per_group.view(batch_size * sequence_length, self.num_groups, self.num_vars, -1)\n codevectors = codevectors.sum(-2).view(batch_size, sequence_length, -1)\n\n return codevectors, perplexity\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2Adapter with Wav2Vec2->WavLM\nclass WavLMAdapter(nn.Module):\n def __init__(self, config):\n super().__init__()\n\n # feature dim might need to be down-projected\n if config.output_hidden_size != config.hidden_size:\n self.proj = nn.Linear(config.hidden_size, config.output_hidden_size)\n self.proj_layer_norm = nn.LayerNorm(config.output_hidden_size)\n else:\n self.proj = self.proj_layer_norm = None\n\n self.layers = nn.ModuleList(WavLMAdapterLayer(config) for _ in range(config.num_adapter_layers))\n self.layerdrop = config.layerdrop\n\n def forward(self, hidden_states):\n # down project hidden_states if necessary\n if self.proj is not None and self.proj_layer_norm is not None:\n hidden_states = self.proj(hidden_states)\n hidden_states = self.proj_layer_norm(hidden_states)\n\n hidden_states = hidden_states.transpose(1, 2)\n\n for layer in self.layers:\n layerdrop_prob = np.random.random()\n if not self.training or (layerdrop_prob > self.layerdrop):\n hidden_states = layer(hidden_states)\n\n hidden_states = hidden_states.transpose(1, 2)\n return hidden_states\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2AdapterLayer with Wav2Vec2->WavLM\nclass WavLMAdapterLayer(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.conv = nn.Conv1d(\n config.output_hidden_size,\n 2 * config.output_hidden_size,\n config.adapter_kernel_size,\n stride=config.adapter_stride,\n padding=1,\n )\n\n def forward(self, hidden_states):\n hidden_states = self.conv(hidden_states)\n hidden_states = nn.functional.glu(hidden_states, dim=1)\n\n return hidden_states\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2PreTrainedModel with Wav2Vec2->WavLM, wav2vec2->wavlm\nclass WavLMPreTrainedModel(PreTrainedModel):\n \"\"\"\n An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained\n models.\n \"\"\"\n\n config_class = WavLMConfig\n base_model_prefix = \"wavlm\"\n main_input_name = \"input_values\"\n _keys_to_ignore_on_load_missing = [r\"position_ids\"]\n supports_gradient_checkpointing = True\n\n def _init_weights(self, module):\n \"\"\"Initialize the weights\"\"\"\n # gumbel softmax requires special init\n if isinstance(module, WavLMGumbelVectorQuantizer):\n module.weight_proj.weight.data.normal_(mean=0.0, std=1)\n module.weight_proj.bias.data.zero_()\n nn.init.uniform_(module.codevectors)\n elif isinstance(module, WavLMPositionalConvEmbedding):\n nn.init.normal_(\n module.conv.weight,\n mean=0,\n std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)),\n )\n nn.init.constant_(module.conv.bias, 0)\n elif isinstance(module, WavLMFeatureProjection):\n k = math.sqrt(1 / module.projection.in_features)\n nn.init.uniform_(module.projection.weight, a=-k, b=k)\n nn.init.uniform_(module.projection.bias, a=-k, b=k)\n elif isinstance(module, nn.Linear):\n module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)\n\n if module.bias is not None:\n module.bias.data.zero_()\n elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n elif isinstance(module, nn.Conv1d):\n nn.init.kaiming_normal_(module.weight)\n\n if module.bias is not None:\n k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0]))\n nn.init.uniform_(module.bias, a=-k, b=k)\n\n def _get_feat_extract_output_lengths(\n self, input_lengths: Union[torch.LongTensor, int], add_adapter: Optional[bool] = None\n ):\n \"\"\"\n Computes the output length of the convolutional layers\n \"\"\"\n\n add_adapter = self.config.add_adapter if add_adapter is None else add_adapter\n\n def _conv_out_length(input_length, kernel_size, stride):\n # 1D convolutional layer output length formula taken\n # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html\n return torch_int_div(input_length - kernel_size, stride) + 1\n\n for kernel_size, stride in zip(self.config.conv_kernel, self.config.conv_stride):\n input_lengths = _conv_out_length(input_lengths, kernel_size, stride)\n\n if add_adapter:\n for _ in range(self.config.num_adapter_layers):\n input_lengths = _conv_out_length(input_lengths, 1, self.config.adapter_stride)\n\n return input_lengths\n\n def _get_feature_vector_attention_mask(\n self, feature_vector_length: int, attention_mask: torch.LongTensor, add_adapter=None\n ):\n # Effectively attention_mask.sum(-1), but not inplace to be able to run\n # on inference mode.\n non_padded_lengths = attention_mask.cumsum(dim=-1)[:, -1]\n\n output_lengths = self._get_feat_extract_output_lengths(non_padded_lengths, add_adapter=add_adapter)\n output_lengths = output_lengths.to(torch.long)\n\n batch_size = attention_mask.shape[0]\n\n attention_mask = torch.zeros(\n (batch_size, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device\n )\n # these two operations makes sure that all values before the output lengths idxs are attended to\n attention_mask[(torch.arange(attention_mask.shape[0], device=attention_mask.device), output_lengths - 1)] = 1\n attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).bool()\n return attention_mask\n\n def _set_gradient_checkpointing(self, module, value=False):\n if isinstance(module, (WavLMEncoder, WavLMEncoderStableLayerNorm, WavLMFeatureEncoder)):\n module.gradient_checkpointing = value\n\n\nWAVLM_START_DOCSTRING = r\"\"\"\n WavLM was proposed in [WavLM: Unified Speech Representation Learning with Labeled and Unlabeled\n Data](https://arxiv.org/abs/2101.07597) by Chengyi Wang, Yu Wu, Yao Qian, Kenichi Kumatani, Shujie Liu, Furu Wei,\n Michael Zeng, Xuedong Huang.\n\n This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the\n library implements for all its model (such as downloading or saving etc.).\n\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`WavLMConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n\"\"\"\n\n\nWAVLM_INPUTS_DOCSTRING = r\"\"\"\n Args:\n input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):\n Float values of input raw speech waveform. Values can be obtained by loading a *.flac* or *.wav* audio file\n into an array of type *List[float]* or a *numpy.ndarray*, *e.g.* via the soundfile library (*pip install\n soundfile*). To prepare the array into *input_values*, the [`WavLMProcessor`] should be used for padding\n and conversion into a tensor of type *torch.FloatTensor*. See [`WavLMProcessor.__call__`] for details.\n attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):\n Mask to avoid performing convolution and attention on padding token indices. Mask values selected in `[0,\n 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n\n <Tip warning={true}>\n\n `attention_mask` should only be passed if the corresponding processor has `config.return_attention_mask ==\n True`. For all models whose processor has `config.return_attention_mask == False`, `attention_mask` should\n **not** be passed to avoid degraded performance when doing batched inference. For such models\n `input_values` should simply be padded with 0 and passed without `attention_mask`. Be aware that these\n models also yield slightly different results depending on whether `input_values` is padded or not.\n\n </Tip>\n\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned\n tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.\n\"\"\"\n\n\n@add_start_docstrings(\n \"The bare WavLM Model transformer outputting raw hidden-states without any specific head on top.\",\n WAVLM_START_DOCSTRING,\n)\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2Model with Wav2Vec2->WavLM, wav2vec2->wavlm, WAV_2_VEC_2->WAVLM\nclass WavLMModel(WavLMPreTrainedModel):\n def __init__(self, config: WavLMConfig):\n super().__init__(config)\n self.config = config\n self.feature_extractor = WavLMFeatureEncoder(config)\n self.feature_projection = WavLMFeatureProjection(config)\n\n # model only needs masking vector if mask prob is > 0.0\n if config.mask_time_prob > 0.0 or config.mask_feature_prob > 0.0:\n self.masked_spec_embed = nn.Parameter(torch.FloatTensor(config.hidden_size).uniform_())\n\n if config.do_stable_layer_norm:\n self.encoder = WavLMEncoderStableLayerNorm(config)\n else:\n self.encoder = WavLMEncoder(config)\n\n self.adapter = WavLMAdapter(config) if config.add_adapter else None\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def freeze_feature_extractor(self):\n \"\"\"\n Calling this function will disable the gradient computation for the feature encoder so that its parameters will\n not be updated during training.\n \"\"\"\n warnings.warn(\n \"The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5.\"\n \"Please use the equivalent `freeze_feature_encoder` method instead.\",\n FutureWarning,\n )\n self.freeze_feature_encoder()\n\n def freeze_feature_encoder(self):\n \"\"\"\n Calling this function will disable the gradient computation for the feature encoder so that its parameter will\n not be updated during training.\n \"\"\"\n self.feature_extractor._freeze_parameters()\n\n def _mask_hidden_states(\n self,\n hidden_states: torch.FloatTensor,\n mask_time_indices: Optional[torch.FloatTensor] = None,\n attention_mask: Optional[torch.LongTensor] = None,\n ):\n \"\"\"\n Masks extracted features along time axis and/or along feature axis according to\n [SpecAugment](https://arxiv.org/abs/1904.08779).\n \"\"\"\n\n # `config.apply_spec_augment` can set masking to False\n if not getattr(self.config, \"apply_spec_augment\", True):\n return hidden_states\n\n # generate indices & apply SpecAugment along time axis\n batch_size, sequence_length, hidden_size = hidden_states.size()\n\n if mask_time_indices is not None:\n # apply SpecAugment along time axis with given mask_time_indices\n hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)\n elif self.config.mask_time_prob > 0 and self.training:\n mask_time_indices = _compute_mask_indices(\n (batch_size, sequence_length),\n mask_prob=self.config.mask_time_prob,\n mask_length=self.config.mask_time_length,\n attention_mask=attention_mask,\n min_masks=self.config.mask_time_min_masks,\n )\n mask_time_indices = torch.tensor(mask_time_indices, device=hidden_states.device, dtype=torch.bool)\n hidden_states[mask_time_indices] = self.masked_spec_embed.to(hidden_states.dtype)\n\n if self.config.mask_feature_prob > 0 and self.training:\n # generate indices & apply SpecAugment along feature axis\n mask_feature_indices = _compute_mask_indices(\n (batch_size, hidden_size),\n mask_prob=self.config.mask_feature_prob,\n mask_length=self.config.mask_feature_length,\n min_masks=self.config.mask_feature_min_masks,\n )\n mask_feature_indices = torch.tensor(mask_feature_indices, device=hidden_states.device, dtype=torch.bool)\n mask_feature_indices = mask_feature_indices[:, None].expand(-1, sequence_length, -1)\n hidden_states[mask_feature_indices] = 0\n\n return hidden_states\n\n @add_start_docstrings_to_model_forward(WAVLM_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n processor_class=_PROCESSOR_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=WavLMBaseModelOutput,\n config_class=_CONFIG_FOR_DOC,\n modality=\"audio\",\n expected_output=_EXPECTED_OUTPUT_SHAPE,\n )\n def forward(\n self,\n input_values,\n attention_mask=None,\n mask_time_indices=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n extract_features = self.feature_extractor(input_values)\n extract_features = extract_features.transpose(1, 2)\n\n if attention_mask is not None:\n # compute reduced attention_mask corresponding to feature vectors\n attention_mask = self._get_feature_vector_attention_mask(\n extract_features.shape[1], attention_mask, add_adapter=False\n )\n\n hidden_states, extract_features = self.feature_projection(extract_features)\n hidden_states = self._mask_hidden_states(\n hidden_states, mask_time_indices=mask_time_indices, attention_mask=attention_mask\n )\n\n encoder_outputs = self.encoder(\n hidden_states,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n hidden_states = encoder_outputs[0]\n\n if self.adapter is not None:\n hidden_states = self.adapter(hidden_states)\n\n if not return_dict:\n return (hidden_states, extract_features) + encoder_outputs[1:]\n\n return WavLMBaseModelOutput(\n last_hidden_state=hidden_states,\n extract_features=extract_features,\n hidden_states=encoder_outputs.hidden_states,\n attentions=encoder_outputs.attentions,\n )\n\n\n@add_start_docstrings(\n \"\"\"WavLM Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).\"\"\",\n WAVLM_START_DOCSTRING,\n)\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForCTC with Wav2Vec2->WavLM, wav2vec2->wavlm, WAV_2_VEC_2->WAVLM\nclass WavLMForCTC(WavLMPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n\n self.wavlm = WavLMModel(config)\n self.dropout = nn.Dropout(config.final_dropout)\n\n if config.vocab_size is None:\n raise ValueError(\n f\"You are trying to instantiate {self.__class__} with a configuration that \"\n \"does not define the vocabulary size of the language model head. Please \"\n \"instantiate the model as follows: `WavLMForCTC.from_pretrained(..., vocab_size=vocab_size)`. \"\n \"or define `vocab_size` of your model's configuration.\"\n )\n output_hidden_size = (\n config.output_hidden_size if hasattr(config, \"add_adapter\") and config.add_adapter else config.hidden_size\n )\n self.lm_head = nn.Linear(output_hidden_size, config.vocab_size)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def freeze_feature_extractor(self):\n \"\"\"\n Calling this function will disable the gradient computation for the feature encoder so that its parameter will\n not be updated during training.\n \"\"\"\n warnings.warn(\n \"The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5.\"\n \"Please use the equivalent `freeze_feature_encoder` method instead.\",\n FutureWarning,\n )\n self.freeze_feature_encoder()\n\n def freeze_feature_encoder(self):\n \"\"\"\n Calling this function will disable the gradient computation for the feature encoder so that its parameter will\n not be updated during training.\n \"\"\"\n self.wavlm.feature_extractor._freeze_parameters()\n\n @add_start_docstrings_to_model_forward(WAVLM_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n processor_class=_PROCESSOR_FOR_DOC,\n checkpoint=_CHECKPOINT_FOR_DOC,\n output_type=CausalLMOutput,\n config_class=_CONFIG_FOR_DOC,\n expected_output=_CTC_EXPECTED_OUTPUT,\n expected_loss=_CTC_EXPECTED_LOSS,\n )\n def forward(\n self,\n input_values,\n attention_mask=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n labels=None,\n ):\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):\n Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to\n the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.\n All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,\n config.vocab_size - 1]`.\n \"\"\"\n\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n outputs = self.wavlm(\n input_values,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n hidden_states = outputs[0]\n hidden_states = self.dropout(hidden_states)\n\n logits = self.lm_head(hidden_states)\n\n loss = None\n if labels is not None:\n\n if labels.max() >= self.config.vocab_size:\n raise ValueError(f\"Label values must be <= vocab_size: {self.config.vocab_size}\")\n\n # retrieve loss input_lengths from attention_mask\n attention_mask = (\n attention_mask if attention_mask is not None else torch.ones_like(input_values, dtype=torch.long)\n )\n input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)\n\n # assuming that padded tokens are filled with -100\n # when not being attended to\n labels_mask = labels >= 0\n target_lengths = labels_mask.sum(-1)\n flattened_targets = labels.masked_select(labels_mask)\n\n # ctc_loss doesn't support fp16\n log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)\n\n with torch.backends.cudnn.flags(enabled=False):\n loss = nn.functional.ctc_loss(\n log_probs,\n flattened_targets,\n input_lengths,\n target_lengths,\n blank=self.config.pad_token_id,\n reduction=self.config.ctc_loss_reduction,\n zero_infinity=self.config.ctc_zero_infinity,\n )\n\n if not return_dict:\n output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]\n return ((loss,) + output) if loss is not None else output\n\n return CausalLMOutput(\n loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions\n )\n\n\n@add_start_docstrings(\n \"\"\"\n WavLM Model with a sequence classification head on top (a linear layer over the pooled output) for tasks like\n SUPERB Keyword Spotting.\n \"\"\",\n WAVLM_START_DOCSTRING,\n)\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForSequenceClassification with Wav2Vec2->WavLM, wav2vec2->wavlm, WAV_2_VEC_2->WAVLM\nclass WavLMForSequenceClassification(WavLMPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n\n if hasattr(config, \"add_adapter\") and config.add_adapter:\n raise ValueError(\n \"Sequence classification does not support the use of WavLM adapters (config.add_adapter=True)\"\n )\n self.wavlm = WavLMModel(config)\n num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings\n if config.use_weighted_layer_sum:\n self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)\n self.projector = nn.Linear(config.hidden_size, config.classifier_proj_size)\n self.classifier = nn.Linear(config.classifier_proj_size, config.num_labels)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n def freeze_feature_extractor(self):\n \"\"\"\n Calling this function will disable the gradient computation for the feature encoder so that its parameters will\n not be updated during training.\n \"\"\"\n warnings.warn(\n \"The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5.\"\n \"Please use the equivalent `freeze_feature_encoder` method instead.\",\n FutureWarning,\n )\n self.freeze_feature_encoder()\n\n def freeze_feature_encoder(self):\n \"\"\"\n Calling this function will disable the gradient computation for the feature encoder so that its parameter will\n not be updated during training.\n \"\"\"\n self.wavlm.feature_extractor._freeze_parameters()\n\n def freeze_base_model(self):\n \"\"\"\n Calling this function will disable the gradient computation for the base model so that its parameters will not\n be updated during training. Only the classification head will be updated.\n \"\"\"\n for param in self.wavlm.parameters():\n param.requires_grad = False\n\n @add_start_docstrings_to_model_forward(WAVLM_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n processor_class=_FEAT_EXTRACTOR_FOR_DOC,\n checkpoint=_SEQ_CLASS_CHECKPOINT,\n output_type=SequenceClassifierOutput,\n config_class=_CONFIG_FOR_DOC,\n modality=\"audio\",\n expected_output=_SEQ_CLASS_EXPECTED_OUTPUT,\n expected_loss=_SEQ_CLASS_EXPECTED_LOSS,\n )\n def forward(\n self,\n input_values,\n attention_mask=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n labels=None,\n ):\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n \"\"\"\n\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states\n\n outputs = self.wavlm(\n input_values,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n if self.config.use_weighted_layer_sum:\n hidden_states = outputs[_HIDDEN_STATES_START_POSITION]\n hidden_states = torch.stack(hidden_states, dim=1)\n norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)\n hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)\n else:\n hidden_states = outputs[0]\n\n hidden_states = self.projector(hidden_states)\n if attention_mask is None:\n pooled_output = hidden_states.mean(dim=1)\n else:\n padding_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)\n hidden_states[~padding_mask] = 0.0\n pooled_output = hidden_states.sum(dim=1) / padding_mask.sum(dim=1).view(-1, 1)\n\n logits = self.classifier(pooled_output)\n\n loss = None\n if labels is not None:\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))\n\n if not return_dict:\n output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]\n return ((loss,) + output) if loss is not None else output\n\n return SequenceClassifierOutput(\n loss=loss,\n logits=logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n\n@add_start_docstrings(\n \"\"\"\n WavLM Model with a frame classification head on top for tasks like Speaker Diarization.\n \"\"\",\n WAVLM_START_DOCSTRING,\n)\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForAudioFrameClassification with Wav2Vec2->WavLM, wav2vec2->wavlm, WAV_2_VEC_2->WAVLM\nclass WavLMForAudioFrameClassification(WavLMPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n\n if hasattr(config, \"add_adapter\") and config.add_adapter:\n raise ValueError(\n \"Audio frame classification does not support the use of WavLM adapters (config.add_adapter=True)\"\n )\n self.wavlm = WavLMModel(config)\n num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings\n if config.use_weighted_layer_sum:\n self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)\n self.classifier = nn.Linear(config.hidden_size, config.num_labels)\n\n self.init_weights()\n\n def freeze_feature_extractor(self):\n \"\"\"\n Calling this function will disable the gradient computation for the feature encoder so that its parameter will\n not be updated during training.\n \"\"\"\n warnings.warn(\n \"The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5.\"\n \"Please use the equivalent `freeze_feature_encoder` method instead.\",\n FutureWarning,\n )\n self.freeze_feature_encoder()\n\n def freeze_feature_encoder(self):\n \"\"\"\n Calling this function will disable the gradient computation for the feature encoder so that its parameter will\n not be updated during training.\n \"\"\"\n self.wavlm.feature_extractor._freeze_parameters()\n\n def freeze_base_model(self):\n \"\"\"\n Calling this function will disable the gradient computation for the base model so that its parameters will not\n be updated during training. Only the classification head will be updated.\n \"\"\"\n for param in self.wavlm.parameters():\n param.requires_grad = False\n\n @add_start_docstrings_to_model_forward(WAVLM_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n processor_class=_FEAT_EXTRACTOR_FOR_DOC,\n checkpoint=_FRAME_CLASS_CHECKPOINT,\n output_type=TokenClassifierOutput,\n config_class=_CONFIG_FOR_DOC,\n modality=\"audio\",\n expected_output=_FRAME_EXPECTED_OUTPUT,\n )\n def forward(\n self,\n input_values,\n attention_mask=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n ):\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n \"\"\"\n\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states\n\n outputs = self.wavlm(\n input_values,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n if self.config.use_weighted_layer_sum:\n hidden_states = outputs[_HIDDEN_STATES_START_POSITION]\n hidden_states = torch.stack(hidden_states, dim=1)\n norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)\n hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)\n else:\n hidden_states = outputs[0]\n\n logits = self.classifier(hidden_states)\n\n if not return_dict:\n output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]\n return output\n\n return TokenClassifierOutput(\n loss=None,\n logits=logits,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.AMSoftmaxLoss\nclass AMSoftmaxLoss(nn.Module):\n def __init__(self, input_dim, num_labels, scale=30.0, margin=0.4):\n super(AMSoftmaxLoss, self).__init__()\n self.scale = scale\n self.margin = margin\n self.num_labels = num_labels\n self.weight = nn.Parameter(torch.randn(input_dim, num_labels), requires_grad=True)\n self.loss = nn.CrossEntropyLoss()\n\n def forward(self, hidden_states, labels):\n labels = labels.flatten()\n weight = nn.functional.normalize(self.weight, dim=0)\n hidden_states = nn.functional.normalize(hidden_states, dim=1)\n cos_theta = torch.mm(hidden_states, weight)\n psi = cos_theta - self.margin\n\n onehot = nn.functional.one_hot(labels, self.num_labels)\n logits = self.scale * torch.where(onehot.bool(), psi, cos_theta)\n loss = self.loss(logits, labels)\n\n return loss\n\n\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.TDNNLayer\nclass TDNNLayer(nn.Module):\n def __init__(self, config, layer_id=0):\n super().__init__()\n self.in_conv_dim = config.tdnn_dim[layer_id - 1] if layer_id > 0 else config.tdnn_dim[layer_id]\n self.out_conv_dim = config.tdnn_dim[layer_id]\n self.kernel_size = config.tdnn_kernel[layer_id]\n self.dilation = config.tdnn_dilation[layer_id]\n\n self.kernel = nn.Linear(self.in_conv_dim * self.kernel_size, self.out_conv_dim)\n self.activation = nn.ReLU()\n\n def forward(self, hidden_states):\n hidden_states = hidden_states.unsqueeze(1)\n hidden_states = nn.functional.unfold(\n hidden_states,\n (self.kernel_size, self.in_conv_dim),\n stride=(1, self.in_conv_dim),\n dilation=(self.dilation, 1),\n )\n hidden_states = hidden_states.transpose(1, 2)\n hidden_states = self.kernel(hidden_states)\n\n hidden_states = self.activation(hidden_states)\n return hidden_states\n\n\n@add_start_docstrings(\n \"\"\"\n WavLM Model with an XVector feature extraction head on top for tasks like Speaker Verification.\n \"\"\",\n WAVLM_START_DOCSTRING,\n)\n# Copied from transformers.models.wav2vec2.modeling_wav2vec2.Wav2Vec2ForXVector with Wav2Vec2->WavLM, wav2vec2->wavlm, WAV_2_VEC_2->WAVLM\nclass WavLMForXVector(WavLMPreTrainedModel):\n def __init__(self, config):\n super().__init__(config)\n\n self.wavlm = WavLMModel(config)\n num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings\n if config.use_weighted_layer_sum:\n self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)\n self.projector = nn.Linear(config.hidden_size, config.tdnn_dim[0])\n\n tdnn_layers = [TDNNLayer(config, i) for i in range(len(config.tdnn_dim))]\n self.tdnn = nn.ModuleList(tdnn_layers)\n\n self.feature_extractor = nn.Linear(config.tdnn_dim[-1] * 2, config.xvector_output_dim)\n self.classifier = nn.Linear(config.xvector_output_dim, config.xvector_output_dim)\n\n self.objective = AMSoftmaxLoss(config.xvector_output_dim, config.num_labels)\n\n self.init_weights()\n\n def freeze_feature_extractor(self):\n \"\"\"\n Calling this function will disable the gradient computation for the feature encoder so that its parameter will\n not be updated during training.\n \"\"\"\n warnings.warn(\n \"The method `freeze_feature_extractor` is deprecated and will be removed in Transformers v5.\"\n \"Please use the equivalent `freeze_feature_encoder` method instead.\",\n FutureWarning,\n )\n self.freeze_feature_encoder()\n\n def freeze_feature_encoder(self):\n \"\"\"\n Calling this function will disable the gradient computation for the feature encoder so that its parameter will\n not be updated during training.\n \"\"\"\n self.wavlm.feature_extractor._freeze_parameters()\n\n def freeze_base_model(self):\n \"\"\"\n Calling this function will disable the gradient computation for the base model so that its parameters will not\n be updated during training. Only the classification head will be updated.\n \"\"\"\n for param in self.wavlm.parameters():\n param.requires_grad = False\n\n def _get_tdnn_output_lengths(self, input_lengths: Union[torch.LongTensor, int]):\n \"\"\"\n Computes the output length of the TDNN layers\n \"\"\"\n\n def _conv_out_length(input_length, kernel_size, stride):\n # 1D convolutional layer output length formula taken\n # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html\n return (input_length - kernel_size) // stride + 1\n\n for kernel_size in self.config.tdnn_kernel:\n input_lengths = _conv_out_length(input_lengths, kernel_size, 1)\n\n return input_lengths\n\n @add_start_docstrings_to_model_forward(WAVLM_INPUTS_DOCSTRING)\n @add_code_sample_docstrings(\n processor_class=_FEAT_EXTRACTOR_FOR_DOC,\n checkpoint=_XVECTOR_CHECKPOINT,\n output_type=XVectorOutput,\n config_class=_CONFIG_FOR_DOC,\n modality=\"audio\",\n expected_output=_XVECTOR_EXPECTED_OUTPUT,\n )\n def forward(\n self,\n input_values,\n attention_mask=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n labels=None,\n ):\n r\"\"\"\n labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):\n Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n \"\"\"\n\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states\n\n outputs = self.wavlm(\n input_values,\n attention_mask=attention_mask,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n\n if self.config.use_weighted_layer_sum:\n hidden_states = outputs[_HIDDEN_STATES_START_POSITION]\n hidden_states = torch.stack(hidden_states, dim=1)\n norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)\n hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)\n else:\n hidden_states = outputs[0]\n\n hidden_states = self.projector(hidden_states)\n\n for tdnn_layer in self.tdnn:\n hidden_states = tdnn_layer(hidden_states)\n\n # Statistic Pooling\n if attention_mask is None:\n mean_features = hidden_states.mean(dim=1)\n std_features = hidden_states.std(dim=1)\n else:\n feat_extract_output_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(dim=1))\n tdnn_output_lengths = self._get_tdnn_output_lengths(feat_extract_output_lengths)\n mean_features = []\n std_features = []\n for i, length in enumerate(tdnn_output_lengths):\n mean_features.append(hidden_states[i, :length].mean(dim=0))\n std_features.append(hidden_states[i, :length].std(dim=0))\n mean_features = torch.stack(mean_features)\n std_features = torch.stack(std_features)\n statistic_pooling = torch.cat([mean_features, std_features], dim=-1)\n\n output_embeddings = self.feature_extractor(statistic_pooling)\n logits = self.classifier(output_embeddings)\n\n loss = None\n if labels is not None:\n loss = self.objective(logits, labels)\n\n if not return_dict:\n output = (logits, output_embeddings) + outputs[_HIDDEN_STATES_START_POSITION:]\n return ((loss,) + output) if loss is not None else output\n\n return XVectorOutput(\n loss=loss,\n logits=logits,\n embeddings=output_embeddings,\n hidden_states=outputs.hidden_states,\n attentions=outputs.attentions,\n )\n",
"# coding=utf-8\n# Copyright 2021, The HuggingFace Inc. team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\" Testing suite for the PyTorch BART model. \"\"\"\n\n\nimport copy\nimport tempfile\nimport unittest\n\nimport timeout_decorator # noqa\n\nfrom transformers import BartConfig, is_torch_available\nfrom transformers.file_utils import cached_property\nfrom transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device\n\nfrom ..generation.test_generation_utils import GenerationTesterMixin\nfrom ..test_configuration_common import ConfigTester\nfrom ..test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor\n\n\nif is_torch_available():\n import torch\n\n from transformers import (\n AutoModelForSequenceClassification,\n BartForCausalLM,\n BartForConditionalGeneration,\n BartForQuestionAnswering,\n BartForSequenceClassification,\n BartModel,\n BartTokenizer,\n pipeline,\n )\n from transformers.models.bart.modeling_bart import BartDecoder, BartEncoder, shift_tokens_right\n\n\ndef prepare_bart_inputs_dict(\n config,\n input_ids,\n decoder_input_ids=None,\n attention_mask=None,\n decoder_attention_mask=None,\n head_mask=None,\n decoder_head_mask=None,\n cross_attn_head_mask=None,\n):\n if attention_mask is None:\n attention_mask = input_ids.ne(config.pad_token_id)\n if decoder_attention_mask is None:\n decoder_attention_mask = decoder_input_ids.ne(config.pad_token_id)\n if head_mask is None:\n head_mask = torch.ones(config.encoder_layers, config.encoder_attention_heads, device=torch_device)\n if decoder_head_mask is None:\n decoder_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device)\n if cross_attn_head_mask is None:\n cross_attn_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device)\n return {\n \"input_ids\": input_ids,\n \"decoder_input_ids\": decoder_input_ids,\n \"attention_mask\": attention_mask,\n \"decoder_attention_mask\": attention_mask,\n \"head_mask\": head_mask,\n \"decoder_head_mask\": decoder_head_mask,\n \"cross_attn_head_mask\": cross_attn_head_mask,\n }\n\n\nclass BartModelTester:\n def __init__(\n self,\n parent,\n batch_size=13,\n seq_length=7,\n is_training=True,\n use_labels=False,\n vocab_size=99,\n hidden_size=16,\n num_hidden_layers=2,\n num_attention_heads=4,\n intermediate_size=4,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=20,\n eos_token_id=2,\n pad_token_id=1,\n bos_token_id=0,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.seq_length = seq_length\n self.is_training = is_training\n self.use_labels = use_labels\n self.vocab_size = vocab_size\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.intermediate_size = intermediate_size\n self.hidden_act = hidden_act\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.eos_token_id = eos_token_id\n self.pad_token_id = pad_token_id\n self.bos_token_id = bos_token_id\n\n def prepare_config_and_inputs(self):\n input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)\n input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size).clamp(\n 3,\n )\n input_ids[:, -1] = self.eos_token_id # Eos Token\n\n decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)\n\n config = self.get_config()\n inputs_dict = prepare_bart_inputs_dict(config, input_ids, decoder_input_ids)\n return config, inputs_dict\n\n def get_config(self):\n return BartConfig(\n vocab_size=self.vocab_size,\n d_model=self.hidden_size,\n encoder_layers=self.num_hidden_layers,\n decoder_layers=self.num_hidden_layers,\n encoder_attention_heads=self.num_attention_heads,\n decoder_attention_heads=self.num_attention_heads,\n encoder_ffn_dim=self.intermediate_size,\n decoder_ffn_dim=self.intermediate_size,\n dropout=self.hidden_dropout_prob,\n attention_dropout=self.attention_probs_dropout_prob,\n max_position_embeddings=self.max_position_embeddings,\n eos_token_id=self.eos_token_id,\n bos_token_id=self.bos_token_id,\n pad_token_id=self.pad_token_id,\n )\n\n def get_pipeline_config(self):\n config = self.get_config()\n config.max_position_embeddings = 100\n return config\n\n def prepare_config_and_inputs_for_common(self):\n config, inputs_dict = self.prepare_config_and_inputs()\n return config, inputs_dict\n\n def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict):\n model = BartModel(config=config).get_decoder().to(torch_device).eval()\n input_ids = inputs_dict[\"input_ids\"]\n attention_mask = inputs_dict[\"attention_mask\"]\n head_mask = inputs_dict[\"head_mask\"]\n\n # first forward pass\n outputs = model(input_ids, attention_mask=attention_mask, head_mask=head_mask, use_cache=True)\n\n output, past_key_values = outputs.to_tuple()\n\n # create hypothetical multiple next token and extent to next_input_ids\n next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)\n next_attn_mask = ids_tensor((self.batch_size, 3), 2)\n\n # append to next input_ids and\n next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)\n next_attention_mask = torch.cat([attention_mask, next_attn_mask], dim=-1)\n\n output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)[\"last_hidden_state\"]\n output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[\n \"last_hidden_state\"\n ]\n\n # select random slice\n random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()\n output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()\n output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()\n\n self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])\n\n # test that outputs are equal for slice\n self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))\n\n def check_encoder_decoder_model_standalone(self, config, inputs_dict):\n model = BartModel(config=config).to(torch_device).eval()\n outputs = model(**inputs_dict)\n\n encoder_last_hidden_state = outputs.encoder_last_hidden_state\n last_hidden_state = outputs.last_hidden_state\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n encoder = model.get_encoder()\n encoder.save_pretrained(tmpdirname)\n encoder = BartEncoder.from_pretrained(tmpdirname).to(torch_device)\n\n encoder_last_hidden_state_2 = encoder(inputs_dict[\"input_ids\"], attention_mask=inputs_dict[\"attention_mask\"])[\n 0\n ]\n\n self.parent.assertTrue((encoder_last_hidden_state_2 - encoder_last_hidden_state).abs().max().item() < 1e-3)\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n decoder = model.get_decoder()\n decoder.save_pretrained(tmpdirname)\n decoder = BartDecoder.from_pretrained(tmpdirname).to(torch_device)\n\n last_hidden_state_2 = decoder(\n input_ids=inputs_dict[\"decoder_input_ids\"],\n attention_mask=inputs_dict[\"decoder_attention_mask\"],\n encoder_hidden_states=encoder_last_hidden_state,\n encoder_attention_mask=inputs_dict[\"attention_mask\"],\n )[0]\n\n self.parent.assertTrue((last_hidden_state_2 - last_hidden_state).abs().max().item() < 1e-3)\n\n\n@require_torch\nclass BartHeadTests(unittest.TestCase):\n vocab_size = 99\n\n def _get_config_and_data(self):\n input_ids = torch.tensor(\n [\n [71, 82, 18, 33, 46, 91, 2],\n [68, 34, 26, 58, 30, 82, 2],\n [5, 97, 17, 39, 94, 40, 2],\n [76, 83, 94, 25, 70, 78, 2],\n [87, 59, 41, 35, 48, 66, 2],\n [55, 13, 16, 58, 5, 2, 1], # note padding\n [64, 27, 31, 51, 12, 75, 2],\n [52, 64, 86, 17, 83, 39, 2],\n [48, 61, 9, 24, 71, 82, 2],\n [26, 1, 60, 48, 22, 13, 2],\n [21, 5, 62, 28, 14, 76, 2],\n [45, 98, 37, 86, 59, 48, 2],\n [70, 70, 50, 9, 28, 0, 2],\n ],\n dtype=torch.long,\n device=torch_device,\n )\n\n batch_size = input_ids.shape[0]\n config = BartConfig(\n vocab_size=self.vocab_size,\n d_model=24,\n encoder_layers=2,\n decoder_layers=2,\n encoder_attention_heads=2,\n decoder_attention_heads=2,\n encoder_ffn_dim=32,\n decoder_ffn_dim=32,\n max_position_embeddings=48,\n eos_token_id=2,\n pad_token_id=1,\n bos_token_id=0,\n )\n return config, input_ids, batch_size\n\n def test_sequence_classification_forward(self):\n config, input_ids, batch_size = self._get_config_and_data()\n labels = _long_tensor([2] * batch_size).to(torch_device)\n model = BartForSequenceClassification(config)\n model.to(torch_device)\n outputs = model(input_ids=input_ids, decoder_input_ids=input_ids, labels=labels)\n expected_shape = torch.Size((batch_size, config.num_labels))\n self.assertEqual(outputs[\"logits\"].shape, expected_shape)\n self.assertIsInstance(outputs[\"loss\"].item(), float)\n\n def test_question_answering_forward(self):\n config, input_ids, batch_size = self._get_config_and_data()\n sequence_labels = ids_tensor([batch_size], 2).to(torch_device)\n model = BartForQuestionAnswering(config)\n model.to(torch_device)\n outputs = model(\n input_ids=input_ids,\n start_positions=sequence_labels,\n end_positions=sequence_labels,\n )\n\n self.assertEqual(outputs[\"start_logits\"].shape, input_ids.shape)\n self.assertEqual(outputs[\"end_logits\"].shape, input_ids.shape)\n self.assertIsInstance(outputs[\"loss\"].item(), float)\n\n @timeout_decorator.timeout(1)\n def test_lm_forward(self):\n config, input_ids, batch_size = self._get_config_and_data()\n lm_labels = ids_tensor([batch_size, input_ids.shape[1]], self.vocab_size).to(torch_device)\n lm_model = BartForConditionalGeneration(config)\n lm_model.to(torch_device)\n outputs = lm_model(input_ids=input_ids, labels=lm_labels)\n expected_shape = (batch_size, input_ids.shape[1], config.vocab_size)\n self.assertEqual(outputs[\"logits\"].shape, expected_shape)\n self.assertIsInstance(outputs[\"loss\"].item(), float)\n\n def test_lm_uneven_forward(self):\n config = BartConfig(\n vocab_size=self.vocab_size,\n d_model=14,\n encoder_layers=2,\n decoder_layers=2,\n encoder_attention_heads=2,\n decoder_attention_heads=2,\n encoder_ffn_dim=8,\n decoder_ffn_dim=8,\n max_position_embeddings=48,\n )\n lm_model = BartForConditionalGeneration(config).to(torch_device)\n context = torch.tensor(\n [[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]], device=torch_device, dtype=torch.long\n )\n summary = torch.tensor([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]], device=torch_device, dtype=torch.long)\n outputs = lm_model(input_ids=context, decoder_input_ids=summary, labels=summary)\n expected_shape = (*summary.shape, config.vocab_size)\n self.assertEqual(outputs[\"logits\"].shape, expected_shape)\n\n def test_generate_beam_search(self):\n input_ids = torch.tensor([[71, 82, 2], [68, 34, 2]], device=torch_device, dtype=torch.long)\n config = BartConfig(\n vocab_size=self.vocab_size,\n d_model=24,\n encoder_layers=2,\n decoder_layers=2,\n encoder_attention_heads=2,\n decoder_attention_heads=2,\n encoder_ffn_dim=32,\n decoder_ffn_dim=32,\n max_position_embeddings=48,\n eos_token_id=2,\n pad_token_id=1,\n bos_token_id=0,\n )\n lm_model = BartForConditionalGeneration(config).to(torch_device)\n lm_model.eval()\n\n max_length = 5\n generated_ids = lm_model.generate(\n input_ids.clone(),\n do_sample=True,\n num_return_sequences=1,\n num_beams=2,\n no_repeat_ngram_size=3,\n max_length=max_length,\n )\n self.assertEqual(generated_ids.shape, (input_ids.shape[0], max_length))\n\n def test_shift_tokens_right(self):\n input_ids = torch.tensor([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]], dtype=torch.long)\n shifted = shift_tokens_right(input_ids, 1, 2)\n n_pad_before = input_ids.eq(1).float().sum()\n n_pad_after = shifted.eq(1).float().sum()\n self.assertEqual(shifted.shape, input_ids.shape)\n self.assertEqual(n_pad_after, n_pad_before - 1)\n self.assertTrue(torch.eq(shifted[:, 0], 2).all())\n\n @slow\n def test_tokenization(self):\n tokenizer = BartTokenizer.from_pretrained(\"facebook/bart-large\")\n examples = [\" Hello world\", \" DomDramg\"] # need leading spaces for equality\n fairseq_results = [\n torch.tensor([0, 20920, 232, 2]),\n torch.tensor([0, 11349, 495, 4040, 571, 2]),\n ]\n for ex, desired_result in zip(examples, fairseq_results):\n bart_toks = tokenizer.encode(ex, return_tensors=\"pt\").squeeze()\n assert_tensors_close(desired_result.long(), bart_toks, prefix=ex)\n\n def test_generate_fp16(self):\n config, input_ids, batch_size = self._get_config_and_data()\n attention_mask = input_ids.ne(1).to(torch_device)\n model = BartForConditionalGeneration(config).eval().to(torch_device)\n if torch_device == \"cuda\":\n model.half()\n model.generate(input_ids, attention_mask=attention_mask)\n model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3)\n\n def test_dummy_inputs(self):\n config, *_ = self._get_config_and_data()\n model = BartForConditionalGeneration(config).eval().to(torch_device)\n model(**model.dummy_inputs)\n\n def test_resize_tokens_embeddings_more(self):\n config, input_ids, _ = self._get_config_and_data()\n\n def _get_embs(m):\n return (m.get_input_embeddings().weight.data.clone(), m.get_output_embeddings().weight.data.clone())\n\n model = BartForConditionalGeneration(config).eval().to(torch_device)\n input, output = _get_embs(model)\n self.assertTrue(torch.eq(input, output).all())\n new_vocab_size = 45\n model.resize_token_embeddings(new_vocab_size)\n input_new, output_new = _get_embs(model)\n self.assertEqual(input_new.shape, (new_vocab_size, config.d_model))\n self.assertEqual(output_new.shape, (new_vocab_size, config.d_model))\n self.assertTrue(torch.eq(input_new, output_new).all())\n\n\n@require_torch\nclass BartModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):\n all_model_classes = (\n (BartModel, BartForConditionalGeneration, BartForSequenceClassification, BartForQuestionAnswering)\n if is_torch_available()\n else ()\n )\n all_generative_model_classes = (BartForConditionalGeneration,) if is_torch_available() else ()\n is_encoder_decoder = True\n test_pruning = False\n test_missing_keys = False\n\n def setUp(self):\n self.model_tester = BartModelTester(self)\n self.config_tester = ConfigTester(self, config_class=BartConfig)\n\n def test_config(self):\n self.config_tester.run_common_tests()\n\n def test_save_load_strict(self):\n config, inputs_dict = self.model_tester.prepare_config_and_inputs()\n for model_class in self.all_model_classes:\n model = model_class(config)\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n model.save_pretrained(tmpdirname)\n model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)\n self.assertEqual(info[\"missing_keys\"], [])\n\n def test_decoder_model_past_with_large_inputs(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)\n\n def test_encoder_decoder_model_standalone(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common()\n self.model_tester.check_encoder_decoder_model_standalone(*config_and_inputs)\n\n # BartForSequenceClassification does not support inputs_embeds\n def test_inputs_embeds(self):\n config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()\n\n for model_class in (BartModel, BartForConditionalGeneration, BartForQuestionAnswering):\n model = model_class(config)\n model.to(torch_device)\n model.eval()\n\n inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class))\n\n if not self.is_encoder_decoder:\n input_ids = inputs[\"input_ids\"]\n del inputs[\"input_ids\"]\n else:\n encoder_input_ids = inputs[\"input_ids\"]\n decoder_input_ids = inputs.get(\"decoder_input_ids\", encoder_input_ids)\n del inputs[\"input_ids\"]\n inputs.pop(\"decoder_input_ids\", None)\n\n wte = model.get_input_embeddings()\n if not self.is_encoder_decoder:\n inputs[\"inputs_embeds\"] = wte(input_ids)\n else:\n inputs[\"inputs_embeds\"] = wte(encoder_input_ids)\n inputs[\"decoder_inputs_embeds\"] = wte(decoder_input_ids)\n\n with torch.no_grad():\n model(**inputs)[0]\n\n def test_generate_fp16(self):\n config, input_dict = self.model_tester.prepare_config_and_inputs()\n input_ids = input_dict[\"input_ids\"]\n attention_mask = input_ids.ne(1).to(torch_device)\n model = BartForConditionalGeneration(config).eval().to(torch_device)\n if torch_device == \"cuda\":\n model.half()\n model.generate(input_ids, attention_mask=attention_mask)\n model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3)\n\n\ndef assert_tensors_close(a, b, atol=1e-12, prefix=\"\"):\n \"\"\"If tensors have different shapes, different values or a and b are not both tensors, raise a nice Assertion error.\"\"\"\n if a is None and b is None:\n return True\n try:\n if torch.allclose(a, b, atol=atol):\n return True\n raise\n except Exception:\n pct_different = (torch.gt((a - b).abs(), atol)).float().mean().item()\n if a.numel() > 100:\n msg = f\"tensor values are {pct_different:.1%} percent different.\"\n else:\n msg = f\"{a} != {b}\"\n if prefix:\n msg = prefix + \": \" + msg\n raise AssertionError(msg)\n\n\ndef _long_tensor(tok_lst):\n return torch.tensor(tok_lst, dtype=torch.long, device=torch_device)\n\n\n@require_torch\n@slow\nclass FastIntegrationTests(unittest.TestCase):\n \"\"\"These tests are useful for debugging since they operate on a model with 1 encoder layer and 1 decoder layer.\"\"\"\n\n @cached_property\n def tok(self):\n return BartTokenizer.from_pretrained(\"facebook/bart-large\")\n\n @cached_property\n def xsum_1_1_model(self):\n return BartForConditionalGeneration.from_pretrained(\"sshleifer/distilbart-xsum-1-1\")\n\n def test_xsum_1_1_generation(self):\n hf = self.xsum_1_1_model\n tok = self.tok\n ARTICLE = 'The Palestinian Authority officially became the 123rd member of the International Criminal Court on Wednesday, a step that gives the court jurisdiction over alleged crimes in Palestinian territories. The formal accession was marked with a ceremony at The Hague, in the Netherlands, where the court is based. The Palestinians signed the ICC\\'s founding Rome Statute in January, when they also accepted its jurisdiction over alleged crimes committed \"in the occupied Palestinian territory, including East Jerusalem, since June 13, 2014.\" Later that month, the ICC opened a preliminary examination into the situation in Palestinian territories, paving the way for possible war crimes investigations against Israelis. As members of the court, Palestinians may be subject to counter-charges as well. Israel and the United States, neither of which is an ICC member, opposed the Palestinians\\' efforts to join the body. But Palestinian Foreign Minister Riad al-Malki, speaking at Wednesday\\'s ceremony, said it was a move toward greater justice. \"As Palestine formally becomes a State Party to the Rome Statute today, the world is also a step closer to ending a long era of impunity and injustice,\" he said, according to an ICC news release. \"Indeed, today brings us closer to our shared goals of justice and peace.\" Judge Kuniko Ozaki, a vice president of the ICC, said acceding to the treaty was just the first step for the Palestinians. \"As the Rome Statute today enters into force for the State of Palestine, Palestine acquires all the rights as well as responsibilities that come with being a State Party to the Statute. These are substantive commitments, which cannot be taken lightly,\" she said. Rights group Human Rights Watch welcomed the development. \"Governments seeking to penalize Palestine for joining the ICC should immediately end their pressure, and countries that support universal acceptance of the court\\'s treaty should speak out to welcome its membership,\" said Balkees Jarrah, international justice counsel for the group. \"What\\'s objectionable is the attempts to undermine international justice, not Palestine\\'s decision to join a treaty to which over 100 countries around the world are members.\" In January, when the preliminary ICC examination was opened, Israeli Prime Minister Benjamin Netanyahu described it as an outrage, saying the court was overstepping its boundaries. The United States also said it \"strongly\" disagreed with the court\\'s decision. \"As we have said repeatedly, we do not believe that Palestine is a state and therefore we do not believe that it is eligible to join the ICC,\" the State Department said in a statement. It urged the warring sides to resolve their differences through direct negotiations. \"We will continue to oppose actions against Israel at the ICC as counterproductive to the cause of peace,\" it said. But the ICC begs to differ with the definition of a state for its purposes and refers to the territories as \"Palestine.\" While a preliminary examination is not a formal investigation, it allows the court to review evidence and determine whether to investigate suspects on both sides. Prosecutor Fatou Bensouda said her office would \"conduct its analysis in full independence and impartiality.\" The war between Israel and Hamas militants in Gaza last summer left more than 2,000 people dead. The inquiry will include alleged war crimes committed since June. The International Criminal Court was set up in 2002 to prosecute genocide, crimes against humanity and war crimes.'\n EXPECTED = \" The International Criminal Court (ICC) has announced that it has been announced by the International Criminal court.\"\n\n dct = tok(ARTICLE, return_tensors=\"pt\")\n generated_ids = hf.generate(**dct, num_beams=4)\n result = tok.batch_decode(generated_ids, skip_special_tokens=True)[0]\n assert EXPECTED == result\n\n def test_xsum_1_1_batch_generation(self):\n # test batch\n\n batch = self.tok(\n [\n 'The Palestinian Authority officially became the 123rd member of the International Criminal Court on Wednesday, a step that gives the court jurisdiction over alleged crimes in Palestinian territories. The formal accession was marked with a ceremony at The Hague, in the Netherlands, where the court is based. The Palestinians signed the ICC\\'s founding Rome Statute in January, when they also accepted its jurisdiction over alleged crimes committed \"in the occupied Palestinian territory, including East Jerusalem, since June 13, 2014.\" Later that month, the ICC opened a preliminary examination into the situation in Palestinian territories, paving the way for possible war crimes investigations against Israelis. As members of the court, Palestinians may be subject to counter-charges as well. Israel and the United States, neither of which is an ICC member, opposed the Palestinians\\' efforts to join the body. But Palestinian Foreign Minister Riad al-Malki, speaking at Wednesday\\'s ceremony, said it was a move toward greater justice. \"As Palestine formally becomes a State Party to the Rome Statute today, the world is also a step closer to ending a long era of impunity and injustice,\" he said, according to an ICC news release. \"Indeed, today brings us closer to our shared goals of justice and peace.\" Judge Kuniko Ozaki, a vice president of the ICC, said acceding to the treaty was just the first step for the Palestinians. \"As the Rome Statute today enters into force for the State of Palestine, Palestine acquires all the rights as well as responsibilities that come with being a State Party to the Statute. These are substantive commitments, which cannot be taken lightly,\" she said. Rights group Human Rights Watch welcomed the development. \"Governments seeking to penalize Palestine for joining the ICC should immediately end their pressure, and countries that support universal acceptance of the court\\'s treaty should speak out to welcome its membership,\" said Balkees Jarrah, international justice counsel for the group. \"What\\'s objectionable is the attempts to undermine international justice, not Palestine\\'s decision to join a treaty to which over 100 countries around the world are members.\" In January, when the preliminary ICC examination was opened, Israeli Prime Minister Benjamin Netanyahu described it as an outrage, saying the court was overstepping its boundaries. The United States also said it \"strongly\" disagreed with the court\\'s decision. \"As we have said repeatedly, we do not believe that Palestine is a state and therefore we do not believe that it is eligible to join the ICC,\" the State Department said in a statement. It urged the warring sides to resolve their differences through direct negotiations. \"We will continue to oppose actions against Israel at the ICC as counterproductive to the cause of peace,\" it said. But the ICC begs to differ with the definition of a state for its purposes and refers to the territories as \"Palestine.\" While a preliminary examination is not a formal investigation, it allows the court to review evidence and determine whether to investigate suspects on both sides. Prosecutor Fatou Bensouda said her office would \"conduct its analysis in full independence and impartiality.\" The war between Israel and Hamas militants in Gaza last summer left more than 2,000 people dead. The inquiry will include alleged war crimes committed since June. The International Criminal Court was set up in 2002 to prosecute genocide, crimes against humanity and war crimes.',\n 'The French prosecutor leading an investigation into the crash of Germanwings Flight 9525 insisted Wednesday that he was not aware of any video footage from on board the plane. Marseille prosecutor Brice Robin told CNN that \"so far no videos were used in the crash investigation.\" He added, \"A person who has such a video needs to immediately give it to the investigators.\" Robin\\'s comments follow claims by two magazines, German daily Bild and French Paris Match, of a cell phone video showing the harrowing final seconds from on board Germanwings Flight 9525 as it crashed into the French Alps. All 150 on board were killed. Paris Match and Bild reported that the video was recovered from a phone at the wreckage site. The two publications described the supposed video, but did not post it on their websites. The publications said that they watched the video, which was found by a source close to the investigation. \"One can hear cries of \\'My God\\' in several languages,\" Paris Match reported. \"Metallic banging can also be heard more than three times, perhaps of the pilot trying to open the cockpit door with a heavy object. Towards the end, after a heavy shake, stronger than the others, the screaming intensifies. Then nothing.\" \"It is a very disturbing scene,\" said Julian Reichelt, editor-in-chief of Bild online. An official with France\\'s accident investigation agency, the BEA, said the agency is not aware of any such video. Lt. Col. Jean-Marc Menichini, a French Gendarmerie spokesman in charge of communications on rescue efforts around the Germanwings crash site, told CNN that the reports were \"completely wrong\" and \"unwarranted.\" Cell phones have been collected at the site, he said, but that they \"hadn\\'t been exploited yet.\" Menichini said he believed the cell phones would need to be sent to the Criminal Research Institute in Rosny sous-Bois, near Paris, in order to be analyzed by specialized technicians working hand-in-hand with investigators. But none of the cell phones found so far have been sent to the institute, Menichini said. Asked whether staff involved in the search could have leaked a memory card to the media, Menichini answered with a categorical \"no.\" Reichelt told \"Erin Burnett: Outfront\" that he had watched the video and stood by the report, saying Bild and Paris Match are \"very confident\" that the clip is real. He noted that investigators only revealed they\\'d recovered cell phones from the crash site after Bild and Paris Match published their reports. \"That is something we did not know before. ... Overall we can say many things of the investigation weren\\'t revealed by the investigation at the beginning,\" he said. What was mental state of Germanwings co-pilot? German airline Lufthansa confirmed Tuesday that co-pilot Andreas Lubitz had battled depression years before he took the controls of Germanwings Flight 9525, which he\\'s accused of deliberately crashing last week in the French Alps. Lubitz told his Lufthansa flight training school in 2009 that he had a \"previous episode of severe depression,\" the airline said Tuesday. Email correspondence between Lubitz and the school discovered in an internal investigation, Lufthansa said, included medical documents he submitted in connection with resuming his flight training. The announcement indicates that Lufthansa, the parent company of Germanwings, knew of Lubitz\\'s battle with depression, allowed him to continue training and ultimately put him in the cockpit. Lufthansa, whose CEO Carsten Spohr previously said Lubitz was 100% fit to fly, described its statement Tuesday as a \"swift and seamless clarification\" and said it was sharing the information and documents -- including training and medical records -- with public prosecutors. Spohr traveled to the crash site Wednesday, where recovery teams have been working for the past week to recover human remains and plane debris scattered across a steep mountainside. He saw the crisis center set up in Seyne-les-Alpes, laid a wreath in the village of Le Vernet, closer to the crash site, where grieving families have left flowers at a simple stone memorial. Menichini told CNN late Tuesday that no visible human remains were left at the site but recovery teams would keep searching. French President Francois Hollande, speaking Tuesday, said that it should be possible to identify all the victims using DNA analysis by the end of the week, sooner than authorities had previously suggested. In the meantime, the recovery of the victims\\' personal belongings will start Wednesday, Menichini said. Among those personal belongings could be more cell phones belonging to the 144 passengers and six crew on board. Check out the latest from our correspondents . The details about Lubitz\\'s correspondence with the flight school during his training were among several developments as investigators continued to delve into what caused the crash and Lubitz\\'s possible motive for downing the jet. A Lufthansa spokesperson told CNN on Tuesday that Lubitz had a valid medical certificate, had passed all his examinations and \"held all the licenses required.\" Earlier, a spokesman for the prosecutor\\'s office in Dusseldorf, Christoph Kumpa, said medical records reveal Lubitz suffered from suicidal tendencies at some point before his aviation career and underwent psychotherapy before he got his pilot\\'s license. Kumpa emphasized there\\'s no evidence suggesting Lubitz was suicidal or acting aggressively before the crash. Investigators are looking into whether Lubitz feared his medical condition would cause him to lose his pilot\\'s license, a European government official briefed on the investigation told CNN on Tuesday. While flying was \"a big part of his life,\" the source said, it\\'s only one theory being considered. Another source, a law enforcement official briefed on the investigation, also told CNN that authorities believe the primary motive for Lubitz to bring down the plane was that he feared he would not be allowed to fly because of his medical problems. Lubitz\\'s girlfriend told investigators he had seen an eye doctor and a neuropsychologist, both of whom deemed him unfit to work recently and concluded he had psychological issues, the European government official said. But no matter what details emerge about his previous mental health struggles, there\\'s more to the story, said Brian Russell, a forensic psychologist. \"Psychology can explain why somebody would turn rage inward on themselves about the fact that maybe they weren\\'t going to keep doing their job and they\\'re upset about that and so they\\'re suicidal,\" he said. \"But there is no mental illness that explains why somebody then feels entitled to also take that rage and turn it outward on 149 other people who had nothing to do with the person\\'s problems.\" Germanwings crash compensation: What we know . Who was the captain of Germanwings Flight 9525? CNN\\'s Margot Haddad reported from Marseille and Pamela Brown from Dusseldorf, while Laura Smith-Spark wrote from London. CNN\\'s Frederik Pleitgen, Pamela Boykoff, Antonia Mortensen, Sandrine Amiel and Anna-Maja Rappard contributed to this report.',\n ],\n return_tensors=\"pt\",\n padding=\"longest\",\n truncation=True,\n )\n generated_ids = self.xsum_1_1_model.generate(**batch, num_beams=4)\n result = self.tok.batch_decode(generated_ids, skip_special_tokens=True)\n assert (\n result[0]\n == \" The International Criminal Court (ICC) has announced that it has been announced by the International Criminal court.\"\n )\n assert (\n result[1]\n == \" An investigation into the crash that killed at least 10 people in the French capital has been released by the French police investigating the crash.\"\n )\n\n def test_encoder_equiv(self):\n # test batch\n\n batch = self.tok(\n [\n 'The Palestinian Authority officially became the 123rd member of the International Criminal Court on Wednesday, a step that gives the court jurisdiction over alleged crimes in Palestinian territories. The formal accession was marked with a ceremony at The Hague, in the Netherlands, where the court is based. The Palestinians signed the ICC\\'s founding Rome Statute in January, when they also accepted its jurisdiction over alleged crimes committed \"in the occupied Palestinian territory, including East Jerusalem, since June 13, 2014.\" Later that month, the ICC opened a preliminary examination into the situation in Palestinian territories, paving the way for possible war crimes investigations against Israelis. As members of the court, Palestinians may be subject to counter-charges as well. Israel and the United States, neither of which is an ICC member, opposed the Palestinians\\' efforts to join the body. But Palestinian Foreign Minister Riad al-Malki, speaking at Wednesday\\'s ceremony, said it was a move toward greater justice. \"As Palestine formally becomes a State Party to the Rome Statute today, the world is also a step closer to ending a long era of impunity and injustice,\" he said, according to an ICC news release. \"Indeed, today brings us closer to our shared goals of justice and peace.\" Judge Kuniko Ozaki, a vice president of the ICC, said acceding to the treaty was just the first step for the Palestinians. \"As the Rome Statute today enters into force for the State of Palestine, Palestine acquires all the rights as well as responsibilities that come with being a State Party to the Statute. These are substantive commitments, which cannot be taken lightly,\" she said. Rights group Human Rights Watch welcomed the development. \"Governments seeking to penalize Palestine for joining the ICC should immediately end their pressure, and countries that support universal acceptance of the court\\'s treaty should speak out to welcome its membership,\" said Balkees Jarrah, international justice counsel for the group. \"What\\'s objectionable is the attempts to undermine international justice, not Palestine\\'s decision to join a treaty to which over 100 countries around the world are members.\" In January, when the preliminary ICC examination was opened, Israeli Prime Minister Benjamin Netanyahu described it as an outrage, saying the court was overstepping its boundaries. The United States also said it \"strongly\" disagreed with the court\\'s decision. \"As we have said repeatedly, we do not believe that Palestine is a state and therefore we do not believe that it is eligible to join the ICC,\" the State Department said in a statement. It urged the warring sides to resolve their differences through direct negotiations. \"We will continue to oppose actions against Israel at the ICC as counterproductive to the cause of peace,\" it said. But the ICC begs to differ with the definition of a state for its purposes and refers to the territories as \"Palestine.\" While a preliminary examination is not a formal investigation, it allows the court to review evidence and determine whether to investigate suspects on both sides. Prosecutor Fatou Bensouda said her office would \"conduct its analysis in full independence and impartiality.\" The war between Israel and Hamas militants in Gaza last summer left more than 2,000 people dead. The inquiry will include alleged war crimes committed since June. The International Criminal Court was set up in 2002 to prosecute genocide, crimes against humanity and war crimes.',\n 'The French prosecutor leading an investigation into the crash of Germanwings Flight 9525 insisted Wednesday that he was not aware of any video footage from on board the plane. Marseille prosecutor Brice Robin told CNN that \"so far no videos were used in the crash investigation.\" He added, \"A person who has such a video needs to immediately give it to the investigators.\" Robin\\'s comments follow claims by two magazines, German daily Bild and French Paris Match, of a cell phone video showing the harrowing final seconds from on board Germanwings Flight 9525 as it crashed into the French Alps. All 150 on board were killed. Paris Match and Bild reported that the video was recovered from a phone at the wreckage site. The two publications described the supposed video, but did not post it on their websites. The publications said that they watched the video, which was found by a source close to the investigation. \"One can hear cries of \\'My God\\' in several languages,\" Paris Match reported. \"Metallic banging can also be heard more than three times, perhaps of the pilot trying to open the cockpit door with a heavy object. Towards the end, after a heavy shake, stronger than the others, the screaming intensifies. Then nothing.\" \"It is a very disturbing scene,\" said Julian Reichelt, editor-in-chief of Bild online. An official with France\\'s accident investigation agency, the BEA, said the agency is not aware of any such video. Lt. Col. Jean-Marc Menichini, a French Gendarmerie spokesman in charge of communications on rescue efforts around the Germanwings crash site, told CNN that the reports were \"completely wrong\" and \"unwarranted.\" Cell phones have been collected at the site, he said, but that they \"hadn\\'t been exploited yet.\" Menichini said he believed the cell phones would need to be sent to the Criminal Research Institute in Rosny sous-Bois, near Paris, in order to be analyzed by specialized technicians working hand-in-hand with investigators. But none of the cell phones found so far have been sent to the institute, Menichini said. Asked whether staff involved in the search could have leaked a memory card to the media, Menichini answered with a categorical \"no.\" Reichelt told \"Erin Burnett: Outfront\" that he had watched the video and stood by the report, saying Bild and Paris Match are \"very confident\" that the clip is real. He noted that investigators only revealed they\\'d recovered cell phones from the crash site after Bild and Paris Match published their reports. \"That is something we did not know before. ... Overall we can say many things of the investigation weren\\'t revealed by the investigation at the beginning,\" he said. What was mental state of Germanwings co-pilot? German airline Lufthansa confirmed Tuesday that co-pilot Andreas Lubitz had battled depression years before he took the controls of Germanwings Flight 9525, which he\\'s accused of deliberately crashing last week in the French Alps. Lubitz told his Lufthansa flight training school in 2009 that he had a \"previous episode of severe depression,\" the airline said Tuesday. Email correspondence between Lubitz and the school discovered in an internal investigation, Lufthansa said, included medical documents he submitted in connection with resuming his flight training. The announcement indicates that Lufthansa, the parent company of Germanwings, knew of Lubitz\\'s battle with depression, allowed him to continue training and ultimately put him in the cockpit. Lufthansa, whose CEO Carsten Spohr previously said Lubitz was 100% fit to fly, described its statement Tuesday as a \"swift and seamless clarification\" and said it was sharing the information and documents -- including training and medical records -- with public prosecutors. Spohr traveled to the crash site Wednesday, where recovery teams have been working for the past week to recover human remains and plane debris scattered across a steep mountainside. He saw the crisis center set up in Seyne-les-Alpes, laid a wreath in the village of Le Vernet, closer to the crash site, where grieving families have left flowers at a simple stone memorial. Menichini told CNN late Tuesday that no visible human remains were left at the site but recovery teams would keep searching. French President Francois Hollande, speaking Tuesday, said that it should be possible to identify all the victims using DNA analysis by the end of the week, sooner than authorities had previously suggested. In the meantime, the recovery of the victims\\' personal belongings will start Wednesday, Menichini said. Among those personal belongings could be more cell phones belonging to the 144 passengers and six crew on board. Check out the latest from our correspondents . The details about Lubitz\\'s correspondence with the flight school during his training were among several developments as investigators continued to delve into what caused the crash and Lubitz\\'s possible motive for downing the jet. A Lufthansa spokesperson told CNN on Tuesday that Lubitz had a valid medical certificate, had passed all his examinations and \"held all the licenses required.\" Earlier, a spokesman for the prosecutor\\'s office in Dusseldorf, Christoph Kumpa, said medical records reveal Lubitz suffered from suicidal tendencies at some point before his aviation career and underwent psychotherapy before he got his pilot\\'s license. Kumpa emphasized there\\'s no evidence suggesting Lubitz was suicidal or acting aggressively before the crash. Investigators are looking into whether Lubitz feared his medical condition would cause him to lose his pilot\\'s license, a European government official briefed on the investigation told CNN on Tuesday. While flying was \"a big part of his life,\" the source said, it\\'s only one theory being considered. Another source, a law enforcement official briefed on the investigation, also told CNN that authorities believe the primary motive for Lubitz to bring down the plane was that he feared he would not be allowed to fly because of his medical problems. Lubitz\\'s girlfriend told investigators he had seen an eye doctor and a neuropsychologist, both of whom deemed him unfit to work recently and concluded he had psychological issues, the European government official said. But no matter what details emerge about his previous mental health struggles, there\\'s more to the story, said Brian Russell, a forensic psychologist. \"Psychology can explain why somebody would turn rage inward on themselves about the fact that maybe they weren\\'t going to keep doing their job and they\\'re upset about that and so they\\'re suicidal,\" he said. \"But there is no mental illness that explains why somebody then feels entitled to also take that rage and turn it outward on 149 other people who had nothing to do with the person\\'s problems.\" Germanwings crash compensation: What we know . Who was the captain of Germanwings Flight 9525? CNN\\'s Margot Haddad reported from Marseille and Pamela Brown from Dusseldorf, while Laura Smith-Spark wrote from London. CNN\\'s Frederik Pleitgen, Pamela Boykoff, Antonia Mortensen, Sandrine Amiel and Anna-Maja Rappard contributed to this report.',\n ],\n return_tensors=\"pt\",\n padding=\"longest\",\n truncation=True,\n )\n features = self.xsum_1_1_model.get_encoder()(**batch).last_hidden_state\n expected = [[-0.0828, -0.0251, -0.0674], [0.1277, 0.3311, -0.0255], [0.2613, -0.0840, -0.2763]]\n assert_tensors_close(features[0, :3, :3], torch.tensor(expected), atol=1e-3)\n\n\n@require_torch\n@require_sentencepiece\n@require_tokenizers\nclass BartModelIntegrationTests(unittest.TestCase):\n @cached_property\n def default_tokenizer(self):\n return BartTokenizer.from_pretrained(\"facebook/bart-large\")\n\n @slow\n def test_inference_no_head(self):\n model = BartModel.from_pretrained(\"facebook/bart-large\").to(torch_device)\n input_ids = _long_tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])\n attention_mask = input_ids.ne(model.config.pad_token_id)\n with torch.no_grad():\n output = model(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state\n expected_shape = torch.Size((1, 11, 1024))\n self.assertEqual(output.shape, expected_shape)\n expected_slice = torch.tensor(\n [[0.7144, 0.8143, -1.2813], [0.7144, 0.8143, -1.2813], [-0.0467, 2.5911, -2.1845]], device=torch_device\n )\n self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-3))\n\n @slow\n def test_base_mask_filling(self):\n pbase = pipeline(task=\"fill-mask\", model=\"facebook/bart-base\")\n src_text = [\" I went to the <mask>.\"]\n results = [x[\"token_str\"] for x in pbase(src_text)]\n assert \" bathroom\" in results\n\n @slow\n def test_large_mask_filling(self):\n plarge = pipeline(task=\"fill-mask\", model=\"facebook/bart-large\")\n src_text = [\" I went to the <mask>.\"]\n results = [x[\"token_str\"] for x in plarge(src_text)]\n expected_results = [\" bathroom\", \" gym\", \" wrong\", \" movies\", \" hospital\"]\n self.assertListEqual(results, expected_results)\n\n @slow\n def test_mnli_inference(self):\n example_b = [0, 31414, 232, 328, 740, 1140, 69, 46078, 1588, 2, 1]\n input_ids = _long_tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2], example_b])\n\n model = AutoModelForSequenceClassification.from_pretrained(\"facebook/bart-large-mnli\").to(\n torch_device\n ) # eval called in from_pre\n attention_mask = input_ids.ne(model.config.pad_token_id)\n # Test that model hasn't changed\n with torch.no_grad():\n outputs = model(input_ids=input_ids, attention_mask=attention_mask)\n\n batched_logits = outputs.logits\n expected_shape = torch.Size((2, 3))\n self.assertEqual(batched_logits.shape, expected_shape)\n expected_slice = torch.tensor([[0.1907, 1.4342, -1.0289]], device=torch_device)\n logits_arr = batched_logits[0].detach()\n\n # Test that padding does not change results\n input_ids_no_pad = _long_tensor([example_b[:-1]])\n attention_mask_no_pad = input_ids_no_pad.ne(model.config.pad_token_id)\n\n with torch.no_grad():\n logits2 = model(input_ids=input_ids_no_pad, attention_mask=attention_mask_no_pad).logits.squeeze()\n assert_tensors_close(batched_logits[1], logits2, atol=1e-3)\n assert_tensors_close(expected_slice, logits_arr, atol=1e-3)\n\n @slow\n def test_xsum_summarization_same_as_fairseq(self):\n model = BartForConditionalGeneration.from_pretrained(\"facebook/bart-large-xsum\").to(torch_device)\n tok = self.default_tokenizer\n\n PGE_ARTICLE = \"\"\" PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.\"\"\"\n\n EXPECTED_SUMMARY = \"California's largest power company has begun shutting off electricity to thousands of customers in the state.\"\n dct = tok.batch_encode_plus(\n [PGE_ARTICLE],\n max_length=1024,\n padding=\"max_length\",\n truncation=True,\n return_tensors=\"pt\",\n ).to(torch_device)\n\n hypotheses_batch = model.generate(\n input_ids=dct[\"input_ids\"],\n attention_mask=dct[\"attention_mask\"],\n num_beams=2,\n max_length=62,\n min_length=11,\n length_penalty=1.0,\n no_repeat_ngram_size=3,\n early_stopping=True,\n decoder_start_token_id=model.config.eos_token_id,\n )\n\n decoded = tok.batch_decode(\n hypotheses_batch,\n skip_special_tokens=True,\n )\n self.assertEqual(EXPECTED_SUMMARY, decoded[0])\n\n def test_xsum_config_generation_params(self):\n config = BartConfig.from_pretrained(\"facebook/bart-large-xsum\")\n expected_params = dict(num_beams=6, do_sample=False, early_stopping=True, length_penalty=1.0)\n config_params = {k: getattr(config, k, \"MISSING\") for k, v in expected_params.items()}\n self.assertDictEqual(expected_params, config_params)\n\n @slow\n def test_cnn_summarization_same_as_fairseq(self):\n hf = BartForConditionalGeneration.from_pretrained(\"facebook/bart-large-cnn\").to(torch_device)\n tok = BartTokenizer.from_pretrained(\"facebook/bart-large\")\n\n FRANCE_ARTICLE = ' Marseille, France (CNN)The French prosecutor leading an investigation into the crash of Germanwings Flight 9525 insisted Wednesday that he was not aware of any video footage from on board the plane. Marseille prosecutor Brice Robin told CNN that \"so far no videos were used in the crash investigation.\" He added, \"A person who has such a video needs to immediately give it to the investigators.\" Robin\\'s comments follow claims by two magazines, German daily Bild and French Paris Match, of a cell phone video showing the harrowing final seconds from on board Germanwings Flight 9525 as it crashed into the French Alps. All 150 on board were killed. Paris Match and Bild reported that the video was recovered from a phone at the wreckage site. The two publications described the supposed video, but did not post it on their websites. The publications said that they watched the video, which was found by a source close to the investigation. \"One can hear cries of \\'My God\\' in several languages,\" Paris Match reported. \"Metallic banging can also be heard more than three times, perhaps of the pilot trying to open the cockpit door with a heavy object. Towards the end, after a heavy shake, stronger than the others, the screaming intensifies. Then nothing.\" \"It is a very disturbing scene,\" said Julian Reichelt, editor-in-chief of Bild online. An official with France\\'s accident investigation agency, the BEA, said the agency is not aware of any such video. Lt. Col. Jean-Marc Menichini, a French Gendarmerie spokesman in charge of communications on rescue efforts around the Germanwings crash site, told CNN that the reports were \"completely wrong\" and \"unwarranted.\" Cell phones have been collected at the site, he said, but that they \"hadn\\'t been exploited yet.\" Menichini said he believed the cell phones would need to be sent to the Criminal Research Institute in Rosny sous-Bois, near Paris, in order to be analyzed by specialized technicians working hand-in-hand with investigators. But none of the cell phones found so far have been sent to the institute, Menichini said. Asked whether staff involved in the search could have leaked a memory card to the media, Menichini answered with a categorical \"no.\" Reichelt told \"Erin Burnett: Outfront\" that he had watched the video and stood by the report, saying Bild and Paris Match are \"very confident\" that the clip is real. He noted that investigators only revealed they\\'d recovered cell phones from the crash site after Bild and Paris Match published their reports. \"That is something we did not know before. ... Overall we can say many things of the investigation weren\\'t revealed by the investigation at the beginning,\" he said. What was mental state of Germanwings co-pilot? German airline Lufthansa confirmed Tuesday that co-pilot Andreas Lubitz had battled depression years before he took the controls of Germanwings Flight 9525, which he\\'s accused of deliberately crashing last week in the French Alps. Lubitz told his Lufthansa flight training school in 2009 that he had a \"previous episode of severe depression,\" the airline said Tuesday. Email correspondence between Lubitz and the school discovered in an internal investigation, Lufthansa said, included medical documents he submitted in connection with resuming his flight training. The announcement indicates that Lufthansa, the parent company of Germanwings, knew of Lubitz\\'s battle with depression, allowed him to continue training and ultimately put him in the cockpit. Lufthansa, whose CEO Carsten Spohr previously said Lubitz was 100% fit to fly, described its statement Tuesday as a \"swift and seamless clarification\" and said it was sharing the information and documents -- including training and medical records -- with public prosecutors. Spohr traveled to the crash site Wednesday, where recovery teams have been working for the past week to recover human remains and plane debris scattered across a steep mountainside. He saw the crisis center set up in Seyne-les-Alpes, laid a wreath in the village of Le Vernet, closer to the crash site, where grieving families have left flowers at a simple stone memorial. Menichini told CNN late Tuesday that no visible human remains were left at the site but recovery teams would keep searching. French President Francois Hollande, speaking Tuesday, said that it should be possible to identify all the victims using DNA analysis by the end of the week, sooner than authorities had previously suggested. In the meantime, the recovery of the victims\\' personal belongings will start Wednesday, Menichini said. Among those personal belongings could be more cell phones belonging to the 144 passengers and six crew on board. Check out the latest from our correspondents . The details about Lubitz\\'s correspondence with the flight school during his training were among several developments as investigators continued to delve into what caused the crash and Lubitz\\'s possible motive for downing the jet. A Lufthansa spokesperson told CNN on Tuesday that Lubitz had a valid medical certificate, had passed all his examinations and \"held all the licenses required.\" Earlier, a spokesman for the prosecutor\\'s office in Dusseldorf, Christoph Kumpa, said medical records reveal Lubitz suffered from suicidal tendencies at some point before his aviation career and underwent psychotherapy before he got his pilot\\'s license. Kumpa emphasized there\\'s no evidence suggesting Lubitz was suicidal or acting aggressively before the crash. Investigators are looking into whether Lubitz feared his medical condition would cause him to lose his pilot\\'s license, a European government official briefed on the investigation told CNN on Tuesday. While flying was \"a big part of his life,\" the source said, it\\'s only one theory being considered. Another source, a law enforcement official briefed on the investigation, also told CNN that authorities believe the primary motive for Lubitz to bring down the plane was that he feared he would not be allowed to fly because of his medical problems. Lubitz\\'s girlfriend told investigators he had seen an eye doctor and a neuropsychologist, both of whom deemed him unfit to work recently and concluded he had psychological issues, the European government official said. But no matter what details emerge about his previous mental health struggles, there\\'s more to the story, said Brian Russell, a forensic psychologist. \"Psychology can explain why somebody would turn rage inward on themselves about the fact that maybe they weren\\'t going to keep doing their job and they\\'re upset about that and so they\\'re suicidal,\" he said. \"But there is no mental illness that explains why somebody then feels entitled to also take that rage and turn it outward on 149 other people who had nothing to do with the person\\'s problems.\" Germanwings crash compensation: What we know . Who was the captain of Germanwings Flight 9525? CNN\\'s Margot Haddad reported from Marseille and Pamela Brown from Dusseldorf, while Laura Smith-Spark wrote from London. CNN\\'s Frederik Pleitgen, Pamela Boykoff, Antonia Mortensen, Sandrine Amiel and Anna-Maja Rappard contributed to this report.' # @noq\n\n SHORTER_ARTICLE = ' (CNN)The Palestinian Authority officially became the 123rd member of the International Criminal Court on Wednesday, a step that gives the court jurisdiction over alleged crimes in Palestinian territories. The formal accession was marked with a ceremony at The Hague, in the Netherlands, where the court is based. The Palestinians signed the ICC\\'s founding Rome Statute in January, when they also accepted its jurisdiction over alleged crimes committed \"in the occupied Palestinian territory, including East Jerusalem, since June 13, 2014.\" Later that month, the ICC opened a preliminary examination into the situation in Palestinian territories, paving the way for possible war crimes investigations against Israelis. As members of the court, Palestinians may be subject to counter-charges as well. Israel and the United States, neither of which is an ICC member, opposed the Palestinians\\' efforts to join the body. But Palestinian Foreign Minister Riad al-Malki, speaking at Wednesday\\'s ceremony, said it was a move toward greater justice. \"As Palestine formally becomes a State Party to the Rome Statute today, the world is also a step closer to ending a long era of impunity and injustice,\" he said, according to an ICC news release. \"Indeed, today brings us closer to our shared goals of justice and peace.\" Judge Kuniko Ozaki, a vice president of the ICC, said acceding to the treaty was just the first step for the Palestinians. \"As the Rome Statute today enters into force for the State of Palestine, Palestine acquires all the rights as well as responsibilities that come with being a State Party to the Statute. These are substantive commitments, which cannot be taken lightly,\" she said. Rights group Human Rights Watch welcomed the development. \"Governments seeking to penalize Palestine for joining the ICC should immediately end their pressure, and countries that support universal acceptance of the court\\'s treaty should speak out to welcome its membership,\" said Balkees Jarrah, international justice counsel for the group. \"What\\'s objectionable is the attempts to undermine international justice, not Palestine\\'s decision to join a treaty to which over 100 countries around the world are members.\" In January, when the preliminary ICC examination was opened, Israeli Prime Minister Benjamin Netanyahu described it as an outrage, saying the court was overstepping its boundaries. The United States also said it \"strongly\" disagreed with the court\\'s decision. \"As we have said repeatedly, we do not believe that Palestine is a state and therefore we do not believe that it is eligible to join the ICC,\" the State Department said in a statement. It urged the warring sides to resolve their differences through direct negotiations. \"We will continue to oppose actions against Israel at the ICC as counterproductive to the cause of peace,\" it said. But the ICC begs to differ with the definition of a state for its purposes and refers to the territories as \"Palestine.\" While a preliminary examination is not a formal investigation, it allows the court to review evidence and determine whether to investigate suspects on both sides. Prosecutor Fatou Bensouda said her office would \"conduct its analysis in full independence and impartiality.\" The war between Israel and Hamas militants in Gaza last summer left more than 2,000 people dead. The inquiry will include alleged war crimes committed since June. The International Criminal Court was set up in 2002 to prosecute genocide, crimes against humanity and war crimes. CNN\\'s Vasco Cotovio, Kareem Khadder and Faith Karimi contributed to this report.'\n\n # The below article tests that we don't add any hypotheses outside of the top n_beams\n IRAN_ARTICLE = \" (CNN)The United States and its negotiating partners reached a very strong framework agreement with Iran in Lausanne, Switzerland, on Thursday that limits Iran's nuclear program in such a way as to effectively block it from building a nuclear weapon. Expect pushback anyway, if the recent past is any harbinger. Just last month, in an attempt to head off such an agreement, House Speaker John Boehner invited Israeli Prime Minister Benjamin Netanyahu to preemptively blast it before Congress, and 47 senators sent a letter to the Iranian leadership warning them away from a deal. The debate that has already begun since the announcement of the new framework will likely result in more heat than light. It will not be helped by the gathering swirl of dubious assumptions and doubtful assertions. Let us address some of these: . The most misleading assertion, despite universal rejection by experts, is that the negotiations' objective at the outset was the total elimination of any nuclear program in Iran. That is the position of Netanyahu and his acolytes in the U.S. Congress. But that is not and never was the objective. If it had been, there would have been no Iranian team at the negotiating table. Rather, the objective has always been to structure an agreement or series of agreements so that Iran could not covertly develop a nuclear arsenal before the United States and its allies could respond. The new framework has exceeded expectations in achieving that goal. It would reduce Iran's low-enriched uranium stockpile, cut by two-thirds its number of installed centrifuges and implement a rigorous inspection regime. Another dubious assumption of opponents is that the Iranian nuclear program is a covert weapons program. Despite sharp accusations by some in the United States and its allies, Iran denies having such a program, and U.S. intelligence contends that Iran has not yet made the decision to build a nuclear weapon. Iran's continued cooperation with International Atomic Energy Agency inspections is further evidence on this point, and we'll know even more about Iran's program in the coming months and years because of the deal. In fact, the inspections provisions that are part of this agreement are designed to protect against any covert action by the Iranians. What's more, the rhetoric of some members of Congress has implied that the negotiations have been between only the United States and Iran (i.e., the 47 senators' letter warning that a deal might be killed by Congress or a future president). This of course is not the case. The talks were between Iran and the five permanent members of the U.N. Security Council (United States, United Kingdom, France, China and Russia) plus Germany, dubbed the P5+1. While the United States has played a leading role in the effort, it negotiated the terms alongside its partners. If the agreement reached by the P5+1 is rejected by Congress, it could result in an unraveling of the sanctions on Iran and threaten NATO cohesion in other areas. Another questionable assertion is that this agreement contains a sunset clause, after which Iran will be free to do as it pleases. Again, this is not the case. Some of the restrictions on Iran's nuclear activities, such as uranium enrichment, will be eased or eliminated over time, as long as 15 years. But most importantly, the framework agreement includes Iran's ratification of the Additional Protocol, which allows IAEA inspectors expanded access to nuclear sites both declared and nondeclared. This provision will be permanent. It does not sunset. Thus, going forward, if Iran decides to enrich uranium to weapons-grade levels, monitors will be able to detect such a move in a matter of days and alert the U.N. Security Council. Many in Congress have said that the agreement should be a formal treaty requiring the Senate to \\\"advise and consent.\\\" But the issue is not suited for a treaty. Treaties impose equivalent obligations on all signatories. For example, the New START treaty limits Russia and the United States to 1,550 deployed strategic warheads. But any agreement with Iran will not be so balanced. The restrictions and obligations in the final framework agreement will be imposed almost exclusively on Iran. The P5+1 are obligated only to ease and eventually remove most but not all economic sanctions, which were imposed as leverage to gain this final deal. Finally some insist that any agreement must address Iranian missile programs, human rights violations or support for Hamas or Hezbollah. As important as these issues are, and they must indeed be addressed, they are unrelated to the most important aim of a nuclear deal: preventing a nuclear Iran. To include them in the negotiations would be a poison pill. This agreement should be judged on its merits and on how it affects the security of our negotiating partners and allies, including Israel. Those judgments should be fact-based, not based on questionable assertions or dubious assumptions.\"\n\n ARTICLE_SUBWAY = ' New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County, New York. A year later, she got married again in Westchester County, but to a different man and without divorcing her first husband. Only 18 days after that marriage, she got hitched yet again. Then, Barrientos declared \"I do\" five more times, sometimes only within two weeks of each other. In 2010, she married once more, this time in the Bronx. In an application for a marriage license, she stated it was her \"first and only\" marriage. Barrientos, now 39, is facing two criminal counts of \"offering a false instrument for filing in the first degree,\" referring to her false statements on the 2010 marriage license application, according to court documents. Prosecutors said the marriages were part of an immigration scam. On Friday, she pleaded not guilty at State Supreme Court in the Bronx, according to her attorney, Christopher Wright, who declined to comment further. After leaving court, Barrientos was arrested and charged with theft of service and criminal trespass for allegedly sneaking into the New York subway through an emergency exit, said Detective Annette Markowski, a police spokeswoman. In total, Barrientos has been married 10 times, with nine of her marriages occurring between 1999 and 2002. All occurred either in Westchester County, Long Island, New Jersey or the Bronx. She is believed to still be married to four men, and at one time, she was married to eight men at once, prosecutors say. Prosecutors said the immigration scam involved some of her husbands, who filed for permanent residence status shortly after the marriages. Any divorces happened only after such filings were approved. It was unclear whether any of the men will be prosecuted. The case was referred to the Bronx District Attorney\\'s Office by Immigration and Customs Enforcement and the Department of Homeland Security\\'s Investigation Division. Seven of the men are from so-called \"red-flagged\" countries, including Egypt, Turkey, Georgia, Pakistan and Mali. Her eighth husband, Rashid Rajput, was deported in 2006 to his native Pakistan after an investigation by the Joint Terrorism Task Force. If convicted, Barrientos faces up to four years in prison. Her next court appearance is scheduled for May 18.'\n\n dct = tok.batch_encode_plus(\n [FRANCE_ARTICLE, SHORTER_ARTICLE, IRAN_ARTICLE, ARTICLE_SUBWAY],\n max_length=1024,\n padding=\"max_length\",\n truncation_strategy=\"only_first\",\n truncation=True,\n return_tensors=\"pt\",\n )\n\n self.assertEqual(1024, dct[\"input_ids\"].shape[1])\n hypotheses_batch = hf.generate(\n input_ids=dct[\"input_ids\"].to(torch_device),\n attention_mask=dct[\"attention_mask\"].to(torch_device),\n num_beams=2,\n )\n assert hypotheses_batch[:, 1].eq(0).all().item()\n\n EXPECTED = [\n \"A French prosecutor says he is not aware of any video footage from on board the plane. Two German \"\n \"magazines claim to have found a cell phone video showing the crash. The publications say they watched \"\n \"the video, which was found by a source close to the investigation. All 150 on board Germanwings Flight \"\n \"9525 were killed.\",\n \"Palestinian Authority becomes 123rd member of the International Criminal Court. The move gives the court \"\n \"jurisdiction over alleged crimes in Palestinian territories. Israel and the United States opposed the \"\n \"Palestinians' efforts to join the body. But Palestinian Foreign Minister Riad al-Malki said it was a \"\n \"move toward greater justice.\",\n \"U.S. and its negotiating partners reached a strong framework agreement with Iran. Peter Bergen: The \"\n \"debate that has already begun will likely result in more heat than light. He says critics have made \"\n \"dubious assumptions and doubtful assertions. Bergen says the goal was to block Iran from building a \"\n \"nuclear weapon.\",\n \"Liana Barrientos, 39, has been married 10 times, sometimes within two weeks of each other. Prosecutors \"\n \"say the marriages were part of an immigration scam. She pleaded not guilty at State Supreme Court in the \"\n \"Bronx on Friday. If convicted, she faces up to four years in prison.\",\n ]\n\n generated_summaries = tok.batch_decode(\n hypotheses_batch.tolist(), clean_up_tokenization_spaces=True, skip_special_tokens=True\n )\n assert generated_summaries == EXPECTED\n\n\nclass BartStandaloneDecoderModelTester:\n def __init__(\n self,\n parent,\n vocab_size=99,\n batch_size=13,\n d_model=16,\n decoder_seq_length=7,\n is_training=True,\n is_decoder=True,\n use_attention_mask=True,\n use_cache=False,\n use_labels=True,\n decoder_start_token_id=2,\n decoder_ffn_dim=32,\n decoder_layers=4,\n encoder_attention_heads=4,\n decoder_attention_heads=4,\n max_position_embeddings=30,\n is_encoder_decoder=False,\n pad_token_id=0,\n bos_token_id=1,\n eos_token_id=2,\n scope=None,\n ):\n self.parent = parent\n self.batch_size = batch_size\n self.decoder_seq_length = decoder_seq_length\n # For common tests\n self.seq_length = self.decoder_seq_length\n self.is_training = is_training\n self.use_attention_mask = use_attention_mask\n self.use_labels = use_labels\n\n self.vocab_size = vocab_size\n self.d_model = d_model\n self.hidden_size = d_model\n self.num_hidden_layers = decoder_layers\n self.decoder_layers = decoder_layers\n self.decoder_ffn_dim = decoder_ffn_dim\n self.encoder_attention_heads = encoder_attention_heads\n self.decoder_attention_heads = decoder_attention_heads\n self.num_attention_heads = decoder_attention_heads\n self.eos_token_id = eos_token_id\n self.bos_token_id = bos_token_id\n self.pad_token_id = pad_token_id\n self.decoder_start_token_id = decoder_start_token_id\n self.use_cache = use_cache\n self.max_position_embeddings = max_position_embeddings\n self.is_encoder_decoder = is_encoder_decoder\n\n self.scope = None\n self.decoder_key_length = decoder_seq_length\n self.base_model_out_len = 2\n self.decoder_attention_idx = 1\n\n def prepare_config_and_inputs(self):\n input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)\n\n attention_mask = None\n if self.use_attention_mask:\n attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2)\n\n lm_labels = None\n if self.use_labels:\n lm_labels = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)\n\n config = BartConfig(\n vocab_size=self.vocab_size,\n d_model=self.d_model,\n encoder_layers=self.decoder_layers,\n decoder_layers=self.decoder_layers,\n decoder_ffn_dim=self.decoder_ffn_dim,\n encoder_attention_heads=self.encoder_attention_heads,\n decoder_attention_heads=self.decoder_attention_heads,\n eos_token_id=self.eos_token_id,\n bos_token_id=self.bos_token_id,\n use_cache=self.use_cache,\n pad_token_id=self.pad_token_id,\n decoder_start_token_id=self.decoder_start_token_id,\n max_position_embeddings=self.max_position_embeddings,\n is_encoder_decoder=self.is_encoder_decoder,\n )\n\n return (\n config,\n input_ids,\n attention_mask,\n lm_labels,\n )\n\n def prepare_config_and_inputs_for_decoder(self):\n (\n config,\n input_ids,\n attention_mask,\n lm_labels,\n ) = self.prepare_config_and_inputs()\n\n encoder_hidden_states = floats_tensor([self.batch_size, self.decoder_seq_length, self.hidden_size])\n encoder_attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2)\n\n return (\n config,\n input_ids,\n attention_mask,\n encoder_hidden_states,\n encoder_attention_mask,\n lm_labels,\n )\n\n def create_and_check_decoder_model_past(\n self,\n config,\n input_ids,\n attention_mask,\n lm_labels,\n ):\n config.use_cache = True\n model = BartDecoder(config=config).to(torch_device).eval()\n # first forward pass\n outputs = model(input_ids, use_cache=True)\n outputs_use_cache_conf = model(input_ids)\n outputs_no_past = model(input_ids, use_cache=False)\n\n self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))\n self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)\n\n past_key_values = outputs[\"past_key_values\"]\n\n # create hypothetical next token and extent to next_input_ids\n next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)\n\n # append to next input_ids and\n next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)\n\n output_from_no_past = model(next_input_ids)[\"last_hidden_state\"]\n output_from_past = model(next_tokens, past_key_values=past_key_values)[\"last_hidden_state\"]\n\n # select random slice\n random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()\n output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()\n output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()\n\n # test that outputs are equal for slice\n assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)\n\n def create_and_check_decoder_model_attention_mask_past(\n self,\n config,\n input_ids,\n attention_mask,\n lm_labels,\n ):\n model = BartDecoder(config=config).to(torch_device).eval()\n\n # create attention mask\n attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)\n\n half_seq_length = input_ids.shape[-1] // 2\n attn_mask[:, half_seq_length:] = 0\n\n # first forward pass\n past_key_values = model(input_ids, attention_mask=attn_mask, use_cache=True)[\"past_key_values\"]\n\n # create hypothetical next token and extent to next_input_ids\n next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)\n\n # change a random masked slice from input_ids\n random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1\n random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1)\n input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens\n\n # append to next input_ids and attn_mask\n next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)\n attn_mask = torch.cat(\n [attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)],\n dim=1,\n )\n\n # get two different outputs\n output_from_no_past = model(next_input_ids, attention_mask=attn_mask)[\"last_hidden_state\"]\n output_from_past = model(next_tokens, attention_mask=attn_mask, past_key_values=past_key_values)[\n \"last_hidden_state\"\n ]\n\n # select random slice\n random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()\n output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()\n output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()\n\n # test that outputs are equal for slice\n assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)\n\n def prepare_config_and_inputs_for_common(self):\n config_and_inputs = self.prepare_config_and_inputs()\n (\n config,\n input_ids,\n attention_mask,\n lm_labels,\n ) = config_and_inputs\n\n inputs_dict = {\n \"input_ids\": input_ids,\n \"attention_mask\": attention_mask,\n }\n return config, inputs_dict\n\n\n@require_torch\nclass BartStandaloneDecoderModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):\n all_model_classes = (BartDecoder, BartForCausalLM) if is_torch_available() else ()\n all_generative_model_classes = (BartForCausalLM,) if is_torch_available() else ()\n test_pruning = False\n is_encoder_decoder = False\n\n def setUp(\n self,\n ):\n self.model_tester = BartStandaloneDecoderModelTester(self, is_training=False)\n self.config_tester = ConfigTester(self, config_class=BartConfig)\n\n def test_config(self):\n self.config_tester.run_common_tests()\n\n def test_decoder_model_past(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_decoder_model_past(*config_and_inputs)\n\n def test_decoder_model_attn_mask_past(self):\n config_and_inputs = self.model_tester.prepare_config_and_inputs()\n self.model_tester.create_and_check_decoder_model_attention_mask_past(*config_and_inputs)\n\n def test_retain_grad_hidden_states_attentions(self):\n # decoder cannot keep gradients\n return\n"
] |
[
[
"torch.abs",
"torch.nn.init.uniform_",
"torch.nn.functional.softmax",
"torch.nn.functional.glu",
"torch.zeros",
"torch.cat",
"torch.nn.Embedding",
"torch.FloatTensor",
"torch.where",
"torch.full_like",
"torch.nn.Dropout",
"torch.nn.CrossEntropyLoss",
"torch.mm",
"torch.ones",
"numpy.arange",
"torch.randn",
"torch.backends.cudnn.flags",
"torch.tensor",
"torch.arange",
"torch.nn.GroupNorm",
"numpy.zeros",
"torch.ones_like",
"torch.sigmoid",
"torch.empty",
"torch.nn.init.constant_",
"numpy.put_along_axis",
"torch.nn.ModuleList",
"torch.nn.Linear",
"torch.log",
"numpy.random.rand",
"torch.nn.Conv1d",
"torch.stack",
"numpy.array",
"torch.nn.functional.ctc_loss",
"torch.nn.functional.normalize",
"numpy.random.random",
"torch.nn.functional.log_softmax",
"torch.nn.utils.weight_norm",
"torch.nn.LayerNorm",
"numpy.ones",
"numpy.random.uniform",
"numpy.broadcast_to",
"torch.nn.functional.one_hot",
"torch.nn.functional.unfold",
"torch.nn.ReLU",
"torch.nn.init.kaiming_normal_"
],
[
"torch.Size",
"torch.ones",
"torch.cat",
"torch.eq",
"torch.tensor",
"torch.no_grad",
"torch.allclose"
]
] |
ihmeuw/vivarium
|
[
"77393d2e84ff2351c926f65b33272b7225cf9628"
] |
[
"src/vivarium/examples/disease_model/intervention.py"
] |
[
"import pandas as pd\n\nfrom vivarium.framework.engine import Builder\n\n\nclass TreatmentIntervention:\n\n configuration_defaults = {\n 'intervention': {\n 'effect_size': 0.5,\n }\n }\n\n def __init__(self, name: str, affected_value: str):\n self.name = name\n self.affected_value = affected_value\n self.configuration_defaults = {name: TreatmentIntervention.configuration_defaults['intervention']}\n\n # noinspection PyAttributeOutsideInit\n def setup(self, builder: Builder):\n effect_size = builder.configuration[self.name].effect_size\n builder.value.register_value_modifier(self.affected_value, modifier=self.intervention_effect)\n self.effect_size = builder.value.register_value_producer(\n f'{self.name}.effect_size', source=lambda index: pd.Series(effect_size, index=index)\n )\n\n def intervention_effect(self, index, value):\n return value * (1 - self.effect_size(index))\n"
] |
[
[
"pandas.Series"
]
] |
OmerAhmedKhan/recommendationSystem
|
[
"17d6bf5b450bb03389ec1eb4b5ce04927b15107e"
] |
[
"GraphScripts/Collaborative_Filters.py"
] |
[
"import pandas as pd\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.metrics import mean_squared_error\n\n\n\nu_cols = ['user_id', 'age', 'sex', 'occupation', 'zip_code']\n\nusers = pd.read_csv('u.user', sep='|', names=u_cols,\n encoding='latin-1')\nX_train = pd.read_csv('X_train.csv')\nr_matrix = X_train.pivot_table(values='rating', index='user_id',\ncolumns='movie_id')\nX_test = pd.read_csv('X_test.csv')\n\n\nitem = pd.read_csv('item.csv')\nitem.drop(['Unnamed: 0', 'video release date'], axis = 1, inplace = True)\n\n\n#Function that computes the root mean squared error (or RMSE)\ndef rmse(y_true, y_pred):\n return np.sqrt(mean_squared_error(y_true, y_pred))\n\n\ndef score(cf_model):\n\n #Construct a list of user-movie tuples from the testing dataset\n id_pairs = zip(X_test['user_id'], X_test['movie_id'])\n\n #Predict the rating for every user-movie tuple\n y_pred = np.array([cf_model(user, movie) for (user, movie) in id_pairs])\n\n #Extract the actual ratings given by the users in the test data\n y_true = np.array(X_test['rating'])\n\n #Return the final RMSE score\n return rmse(y_true, y_pred)\n\n\nmerged_df = pd.merge(X_train, users)\nmerged_df = merged_df.drop(\"Unnamed: 0\", axis = 1)\n\n\ngender_mean = merged_df[['movie_id', 'sex', 'rating']].groupby(['movie_id', 'sex'])['rating'].mean()\n\nusers = users.set_index('user_id')\n\n#__________________________________\n#GENDER BASED CF\ndef gcf(uid, mid):\n if mid in r_matrix:\n gen = users.loc[uid]['sex']\n if gen in gender_mean[mid]:\n gender_rating = gender_mean[mid][gen]\n else:\n gender_rating = 2.5\n else:\n gender_rating = 2.5\n return gender_rating\n\ngcf_score = score(gcf)\n\n\nage_mean = merged_df[['movie_id', 'age', 'rating']].groupby(['movie_id', 'age'])['rating'].mean()\n\n#__________________________________\n#AGE BASED CF\ndef agecf(uid, mid):\n if mid in r_matrix:\n age = users.loc[uid]['age']\n if age in age_mean[mid]:\n age_rating = age_mean[mid][age]\n else:\n age_rating = 2.5\n else:\n age_rating = 2.5\n return age_rating\n\nagecf_score = score(agecf)\n\n#__________________________________\n# AGE & GENDER CF\nage_gender_mean = merged_df[['age', 'rating', 'movie_id', 'sex']].pivot_table(values = 'rating', index = 'movie_id',\n columns = ['sex', 'age'], aggfunc = 'mean')\n\ndef age_gender_cf(uid, mid):\n if mid in age_gender_mean.index:\n user = users.loc[uid]\n age = user['age']\n sex = user['sex']\n if sex in age_gender_mean.loc[mid]:\n if age in age_gender_mean.loc[mid][sex]:\n rating = age_gender_mean.loc[mid][sex][age]\n if np.isnan(rating):\n rating = 2.5\n return rating\n return 2.5\n\nage_gender_cf_score = score(age_gender_cf)\n\n#__________________________________\n# GENDER & OCCUPATION CF\ngen_occ_mean = merged_df[['sex', 'rating', 'movie_id', 'occupation']].pivot_table(values = 'rating', index = 'movie_id',\n columns = ['occupation', 'sex'], aggfunc = 'mean')\n\ndef goc_cf(uid, mid):\n if mid in gen_occ_mean.index:\n user = users.loc[uid]\n gen = user['sex']\n job = user['occupation']\n if job in gen_occ_mean.loc[mid]:\n if gen in gen_occ_mean.loc[mid][job]:\n rating = gen_occ_mean.loc[mid][job][gen]\n if np.isnan(rating):\n rating = 2.5\n return rating\n return 2.5\n\ngoc_cf_score = score(goc_cf)\n\nscores = {'age_gender': age_gender_cf_score, 'age': agecf_score, 'gender_job': goc_cf_score, 'gender': gcf_score,\n 'mean': 1.0233040312606156, 'w_mean': 1.0174483808407588}\n\nnames = list(scores.keys())\nvalues = list(scores.values())\nfor i in range(0,len(names)):\n plt.bar(i, values[i], tick_label = names[i])\nplt.xticks(range(0,len(names)),names)\nplt.ylabel(\"Score\")\nplt.xlabel(\"Collaborative Filters\")\nplt.title(\"Collaborative Filters score\")\nplt.show()\n"
] |
[
[
"pandas.merge",
"pandas.read_csv",
"matplotlib.pyplot.title",
"numpy.isnan",
"sklearn.metrics.mean_squared_error",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] |
cdever01/torchani
|
[
"3f7e1347a06422f50010c04a65219e22f2179bfa"
] |
[
"tests/test_vibrational.py"
] |
[
"import os\nimport math\nimport unittest\nimport torch\nimport torchani\nimport ase\nimport ase.optimize\nimport ase.vibrations\nimport numpy\n\n\npath = os.path.dirname(os.path.realpath(__file__))\npath = os.path.join(path, '../dataset/xyz_files/H2O.xyz')\n\n\nclass TestVibrational(unittest.TestCase):\n\n def testVibrationalWavenumbers(self):\n model = torchani.models.ANI1x().double()\n d = 0.9575\n t = math.pi / 180 * 104.51\n molecule = ase.Atoms('H2O', positions=[\n (d, 0, 0),\n (d * math.cos(t), d * math.sin(t), 0),\n (0, 0, 0),\n ], calculator=model.ase())\n opt = ase.optimize.BFGS(molecule)\n opt.run(fmax=1e-6)\n masses = torch.tensor([1.008, 12.011, 14.007, 15.999], dtype=torch.double)\n # compute vibrational frequencies by ASE\n vib = ase.vibrations.Vibrations(molecule)\n vib.run()\n freq = torch.tensor([numpy.real(x) for x in vib.get_frequencies()[6:]])\n modes = []\n for j in range(6, 6 + len(freq)):\n modes.append(vib.get_mode(j))\n modes = torch.tensor(modes)\n # compute vibrational by torchani\n species = model.species_to_tensor(molecule.get_chemical_symbols()).unsqueeze(0)\n coordinates = torch.from_numpy(molecule.get_positions()).unsqueeze(0).requires_grad_(True)\n _, energies = model((species, coordinates))\n hessian = torchani.utils.hessian(coordinates, energies=energies)\n freq2, modes2, _, _ = torchani.utils.vibrational_analysis(masses[species], hessian)\n freq2 = freq2[6:].float()\n modes2 = modes2[6:]\n ratio = freq2 / freq\n self.assertLess((ratio - 1).abs().max(), 0.02)\n\n diff1 = (modes - modes2).abs().max(dim=-1).values.max(dim=-1).values\n diff2 = (modes + modes2).abs().max(dim=-1).values.max(dim=-1).values\n diff = torch.where(diff1 < diff2, diff1, diff2)\n self.assertLess(diff.max(), 0.02)\n\n\nif __name__ == '__main__':\n unittest.main()\n"
] |
[
[
"numpy.real",
"torch.where",
"torch.tensor"
]
] |
m-abdulhak/OpenSfM
|
[
"767756c2c2f35a2d081a03dffdaa0ba21400a89e"
] |
[
"opensfm/actions/undistort.py"
] |
[
"import logging\n\nimport cv2\nimport numpy as np\nfrom opensfm import dataset\nfrom opensfm import features\nfrom opensfm import log\nfrom opensfm import pygeometry\nfrom opensfm import pysfm\nfrom opensfm import transformations as tf\nfrom opensfm import types\nfrom opensfm.context import parallel_map\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef run_dataset(data, reconstruction, reconstruction_index, tracks, output):\n \"\"\"Export reconstruction to NVM_V3 format from VisualSfM\n\n Args:\n reconstruction: reconstruction to undistort\n reconstruction_index: index of the reconstruction component to undistort\n tracks: tracks graph of the reconstruction\n output: undistorted\n\n \"\"\"\n\n udata = dataset.UndistortedDataSet(data, output)\n reconstructions = data.load_reconstruction(reconstruction)\n if data.tracks_exists(tracks):\n tracks_manager = data.load_tracks_manager(tracks)\n else:\n tracks_manager = None\n\n if reconstructions:\n r = reconstructions[reconstruction_index]\n undistort_reconstruction(tracks_manager, r, data, udata)\n\n\ndef undistort_reconstruction(tracks_manager, reconstruction, data, udata):\n urec = types.Reconstruction()\n urec.points = reconstruction.points\n utracks_manager = pysfm.TracksManager()\n logger.debug(\"Undistorting the reconstruction\")\n undistorted_shots = {}\n for shot in reconstruction.shots.values():\n if shot.camera.projection_type == \"perspective\":\n camera = perspective_camera_from_perspective(shot.camera)\n urec.add_camera(camera)\n subshots = [get_shot_with_different_camera(urec, shot, camera)]\n elif shot.camera.projection_type == \"brown\":\n camera = perspective_camera_from_brown(shot.camera)\n urec.add_camera(camera)\n subshots = [get_shot_with_different_camera(urec, shot, camera)]\n elif shot.camera.projection_type in [\"fisheye\", \"fisheye_opencv\"]:\n camera = perspective_camera_from_fisheye(shot.camera)\n urec.add_camera(camera)\n subshots = [get_shot_with_different_camera(urec, shot, camera)]\n elif pygeometry.Camera.is_panorama(shot.camera.projection_type):\n subshot_width = int(data.config[\"depthmap_resolution\"])\n subshots = perspective_views_of_a_panorama(shot, subshot_width, urec)\n\n for subshot in subshots:\n if tracks_manager:\n add_subshot_tracks(tracks_manager, utracks_manager, shot, subshot)\n undistorted_shots[shot.id] = subshots\n\n udata.save_undistorted_reconstruction([urec])\n if tracks_manager:\n udata.save_undistorted_tracks_manager(utracks_manager)\n\n arguments = []\n for shot in reconstruction.shots.values():\n arguments.append((shot, undistorted_shots[shot.id], data, udata))\n\n processes = data.config[\"processes\"]\n parallel_map(undistort_image_and_masks, arguments, processes)\n\n\ndef undistort_image_and_masks(arguments):\n shot, undistorted_shots, data, udata = arguments\n log.setup()\n logger.debug(\"Undistorting image {}\".format(shot.id))\n max_size = data.config[\"undistorted_image_max_size\"]\n\n # Undistort image\n image = data.load_image(shot.id, unchanged=True, anydepth=True)\n if image is not None:\n undistorted = undistort_image(\n shot, undistorted_shots, image, cv2.INTER_AREA, max_size\n )\n for k, v in undistorted.items():\n udata.save_undistorted_image(k, v)\n\n # Undistort mask\n mask = data.load_mask(shot.id)\n if mask is not None:\n undistorted = undistort_image(\n shot, undistorted_shots, mask, cv2.INTER_NEAREST, max_size\n )\n for k, v in undistorted.items():\n udata.save_undistorted_mask(k, v)\n\n # Undistort segmentation\n segmentation = data.load_segmentation(shot.id)\n if segmentation is not None:\n undistorted = undistort_image(\n shot, undistorted_shots, segmentation, cv2.INTER_NEAREST, max_size\n )\n for k, v in undistorted.items():\n udata.save_undistorted_segmentation(k, v)\n\n # Undistort detections\n detection = data.load_detection(shot.id)\n if detection is not None:\n undistorted = undistort_image(\n shot, undistorted_shots, detection, cv2.INTER_NEAREST, max_size\n )\n for k, v in undistorted.items():\n udata.save_undistorted_detection(k, v)\n\n\ndef undistort_image(shot, undistorted_shots, original, interpolation, max_size):\n \"\"\"Undistort an image into a set of undistorted ones.\n\n Args:\n shot: the distorted shot\n undistorted_shots: the set of undistorted shots covering the\n distorted shot field of view. That is 1 for most camera\n types and 6 for spherical cameras.\n original: the original distorted image array.\n interpolation: the opencv interpolation flag to use.\n max_size: maximum size of the undistorted image.\n \"\"\"\n if original is None:\n return\n\n projection_type = shot.camera.projection_type\n if projection_type in [\"perspective\", \"brown\", \"fisheye\", \"fisheye_opencv\"]:\n new_camera = undistorted_shots[0].camera\n height, width = original.shape[:2]\n map1, map2 = pygeometry.compute_camera_mapping(\n shot.camera, new_camera, width, height\n )\n undistorted = cv2.remap(original, map1, map2, interpolation)\n return {shot.id: scale_image(undistorted, max_size)}\n elif pygeometry.Camera.is_panorama(projection_type):\n subshot_width = undistorted_shots[0].camera.width\n width = 4 * subshot_width\n height = width // 2\n image = cv2.resize(original, (width, height), interpolation=interpolation)\n mint = cv2.INTER_LINEAR if interpolation == cv2.INTER_AREA else interpolation\n res = {}\n for subshot in undistorted_shots:\n undistorted = render_perspective_view_of_a_panorama(\n image, shot, subshot, mint\n )\n res[subshot.id] = scale_image(undistorted, max_size)\n return res\n else:\n raise NotImplementedError(\n \"Undistort not implemented for projection type: {}\".format(\n shot.camera.projection_type\n )\n )\n\n\ndef scale_image(image, max_size):\n \"\"\"Scale an image not to exceed max_size.\"\"\"\n height, width = image.shape[:2]\n factor = max_size / float(max(height, width))\n if factor >= 1:\n return image\n width = int(round(width * factor))\n height = int(round(height * factor))\n return cv2.resize(image, (width, height), interpolation=cv2.INTER_NEAREST)\n\n\ndef get_shot_with_different_camera(urec, shot, camera):\n new_shot = urec.create_shot(shot.id, shot.camera.id, shot.pose)\n new_shot.metadata = shot.metadata\n return new_shot\n\n\ndef perspective_camera_from_perspective(distorted):\n \"\"\"Create an undistorted camera from a distorted.\"\"\"\n camera = pygeometry.Camera.create_perspective(distorted.focal, 0.0, 0.0)\n camera.id = distorted.id\n camera.width = distorted.width\n camera.height = distorted.height\n return camera\n\n\ndef perspective_camera_from_brown(brown):\n \"\"\"Create a perspective camera from a Brown camera.\"\"\"\n camera = pygeometry.Camera.create_perspective(\n brown.focal * (1 + brown.aspect_ratio) / 2.0, 0.0, 0.0\n )\n camera.id = brown.id\n camera.width = brown.width\n camera.height = brown.height\n return camera\n\n\ndef perspective_camera_from_fisheye(fisheye):\n \"\"\"Create a perspective camera from a fisheye.\"\"\"\n camera = pygeometry.Camera.create_perspective(fisheye.focal, 0.0, 0.0)\n camera.id = fisheye.id\n camera.width = fisheye.width\n camera.height = fisheye.height\n return camera\n\n\ndef perspective_camera_from_fisheye_opencv(fisheye_opencv):\n \"\"\"Create a perspective camera from a fisheye extended.\"\"\"\n camera = pygeometry.Camera.create_perspective(\n fisheye_opencv.focal * (1 + fisheye_opencv.aspect_ratio) / 2.0, 0.0, 0.0\n )\n camera.id = fisheye_opencv.id\n camera.width = fisheye_opencv.width\n camera.height = fisheye_opencv.height\n return camera\n\n\ndef perspective_views_of_a_panorama(spherical_shot, width, reconstruction):\n \"\"\"Create 6 perspective views of a panorama.\"\"\"\n camera = pygeometry.Camera.create_perspective(0.5, 0.0, 0.0)\n camera.id = \"perspective_panorama_camera\"\n camera.width = width\n camera.height = width\n reconstruction.add_camera(camera)\n\n names = [\"front\", \"left\", \"back\", \"right\", \"top\", \"bottom\"]\n rotations = [\n tf.rotation_matrix(-0 * np.pi / 2, (0, 1, 0)),\n tf.rotation_matrix(-1 * np.pi / 2, (0, 1, 0)),\n tf.rotation_matrix(-2 * np.pi / 2, (0, 1, 0)),\n tf.rotation_matrix(-3 * np.pi / 2, (0, 1, 0)),\n tf.rotation_matrix(-np.pi / 2, (1, 0, 0)),\n tf.rotation_matrix(+np.pi / 2, (1, 0, 0)),\n ]\n shots = []\n for name, rotation in zip(names, rotations):\n R = np.dot(rotation[:3, :3], spherical_shot.pose.get_rotation_matrix())\n o = spherical_shot.pose.get_origin()\n pose = pygeometry.Pose()\n pose.set_rotation_matrix(R)\n pose.set_origin(o)\n shots.append(\n reconstruction.create_shot(\n \"{}_perspective_view_{}\".format(spherical_shot.id, name),\n camera.id,\n pose,\n )\n )\n return shots\n\n\ndef render_perspective_view_of_a_panorama(\n image,\n panoshot,\n perspectiveshot,\n interpolation=cv2.INTER_LINEAR,\n borderMode=cv2.BORDER_WRAP,\n):\n \"\"\"Render a perspective view of a panorama.\"\"\"\n # Get destination pixel coordinates\n dst_shape = (perspectiveshot.camera.height, perspectiveshot.camera.width)\n dst_y, dst_x = np.indices(dst_shape).astype(np.float32)\n dst_pixels_denormalized = np.column_stack([dst_x.ravel(), dst_y.ravel()])\n\n dst_pixels = features.normalized_image_coordinates(\n dst_pixels_denormalized,\n perspectiveshot.camera.width,\n perspectiveshot.camera.height,\n )\n\n # Convert to bearing\n dst_bearings = perspectiveshot.camera.pixel_bearing_many(dst_pixels)\n\n # Rotate to panorama reference frame\n rotation = np.dot(\n panoshot.pose.get_rotation_matrix(),\n perspectiveshot.pose.get_rotation_matrix().T,\n )\n rotated_bearings = np.dot(dst_bearings, rotation.T)\n\n # Project to panorama pixels\n src_pixels = panoshot.camera.project_many(rotated_bearings)\n src_pixels_denormalized = features.denormalized_image_coordinates(\n src_pixels, image.shape[1], image.shape[0]\n )\n\n src_pixels_denormalized.shape = dst_shape + (2,)\n\n # Sample color\n x = src_pixels_denormalized[..., 0].astype(np.float32)\n y = src_pixels_denormalized[..., 1].astype(np.float32)\n colors = cv2.remap(image, x, y, interpolation, borderMode=borderMode)\n\n return colors\n\n\ndef add_subshot_tracks(tracks_manager, utracks_manager, shot, subshot):\n \"\"\"Add shot tracks to the undistorted tracks_manager.\"\"\"\n if shot.id not in tracks_manager.get_shot_ids():\n return\n\n if pygeometry.Camera.is_panorama(shot.camera.projection_type):\n add_pano_subshot_tracks(tracks_manager, utracks_manager, shot, subshot)\n else:\n for track_id, obs in tracks_manager.get_shot_observations(shot.id).items():\n utracks_manager.add_observation(subshot.id, track_id, obs)\n\n\ndef add_pano_subshot_tracks(tracks_manager, utracks_manager, panoshot, perspectiveshot):\n \"\"\"Add edges between subshots and visible tracks.\"\"\"\n for track_id, obs in tracks_manager.get_shot_observations(panoshot.id).items():\n bearing = panoshot.camera.pixel_bearing(obs.point)\n rotation = np.dot(\n perspectiveshot.pose.get_rotation_matrix(),\n panoshot.pose.get_rotation_matrix().T,\n )\n\n rotated_bearing = np.dot(bearing, rotation.T)\n if rotated_bearing[2] <= 0:\n continue\n\n perspective_feature = perspectiveshot.camera.project(rotated_bearing)\n if (\n perspective_feature[0] < -0.5\n or perspective_feature[0] > 0.5\n or perspective_feature[1] < -0.5\n or perspective_feature[1] > 0.5\n ):\n continue\n\n obs.point = perspective_feature\n utracks_manager.add_observation(perspectiveshot.id, track_id, obs)\n"
] |
[
[
"numpy.dot",
"numpy.indices"
]
] |
MoisesExpositoAlonso/deepbiosphere
|
[
"555bd6d081b2bca87f43eaa3896f1eeec9ea4f3e"
] |
[
"scripts/DEEPBIO_GBIF.py"
] |
[
"\"\"\"\nParsing and gridding GBIF [taxon, latitude, longitude] .csv file\n@author: [email protected]\n\n\"\"\"\n\nimport pandas as pd\nimport os\nimport numpy as np\n\n\n###########################################################################################\ndef subcoor(d,lat,lon):\n d_ = d.loc[d.iloc[:,1]<lat+1].loc[d.iloc[:,1]>lat].loc[d.iloc[:,2]<lon+1].loc[d.iloc[:,2]>lon]\n return(d_)\n\ndef makegrid(n):\n a=np.array(list(range(n)))+1 # axis with offset for 0 base index to 1\n points=product(a,repeat=2) #only allow repeats for (i,j), (j,i) pairs with i!=j\n return(np.asarray(list(points)) )\n\ndef maketensor(z,y,x):\n a = np.zeros((z, y, x))\n return(a)\n\ndef makespphash(iterable):\n seen = set()\n result = []\n for element in iterable:\n hashed = element\n if isinstance(element, dict):\n hashed = tuple(sorted(element.iteritems()))\n elif isinstance(element, list):\n hashed = tuple(element)\n if hashed not in seen:\n result.append(element)\n seen.add(hashed)\n return result\n\n################################################################################\n\ndef readgbif(path=\"../gbif/pgbif.csv\",sep=\"\\t\"):\n d = pd.read_csv(path, sep)\n #print('Load GBIF file with #rows = %i' %(d.size))\n return(d)\n\ndef tensorgbif():\n spp=makespphash(d.iloc[:,0])\n spptot=len(spp)\n sppdic=make_sppdic(spp,spptot)\n #tens=maketensor(10,10,spptot) # this for future implementation\n return('notimplemented yet')\n\n\ndef whichwindow(w,v):\n count=0\n for i in w:\n if v>=i[0] and v<i[1]:\n break\n else:\n count=count+1\n return count\n\ndef iffamily(val,fam):\n if val==fam:\n return(1)\n else:\n return(0)\n\ndef tensoronetaxon(step, breaks, lat,lon, d, sppname,vtype=\"freq\"):\n if vtype not in [\"freq\",\"yesno\"]:\n Exception(\"The type of raster has to be either 'freq' or 'yesno'\")\n # Subset to SF\n d_ = subcoor(d,lat,lon)\n cactusnum=int(d_[d_['family'] == sppname].size)\n # print('There are {} {} within this grid'.format(sppname,cactusnum))\n ## make grid steps\n sb= step/breaks\n xwind=[[lon+(sb*i),lon+(sb*(i+1))] for i in range(int(breaks))]\n ywind=[[lat+(sb*i),lat+(sb*(i+1))] for i in range(int(breaks))]\n ####################################################\n # Fill tensor\n tens=maketensor(2,breaks+1,breaks+1)#only for cactaceae\n for index, r in d_.iterrows():\n # print(r)\n da=whichwindow(ywind,r[1])\n do=whichwindow(xwind,r[2])\n dspp=iffamily(r[0],sppname)\n tens[dspp,da,do]= tens[dspp,da,do] +1\n # total observation per grid\n totobs=tens.sum(axis=0)\n # % of cactaceae\n if vtype==\"freq\":\n cactae=tens[1,:,:]/(totobs+0.0001)\n else:\n cactae=tens[1,:,:]\n cactae=(cactae>0)*1\n return(cactae)\n\ndef key_for_value(d, value):\n # this will be useful for final implementation\n return(list(d.keys())[list(d.values()).index(value)])\n\ndef make_sppdic(spp,total):\n sppdic={}\n for i in range(0,total):\n sppdic[i]=spp[i]\n return(sppdic)\n\ndef tensorgbif(lat,lon,step, breaks,d, sppdic,vtype=\"yesno\"):\n if vtype not in [\"freq\",\"yesno\"]:\n Exception(\"The type of raster has to be either 'freq' or 'yesno'\")\n # Subset to SF\n d_ = subcoor(d,lat,lon)\n ## make grid steps\n sb= step/breaks\n xwind=[[lon+(sb*i),lon+(sb*(i+1))] for i in range(int(breaks))]\n ywind=[[lat+(sb*i),lat+(sb*(i+1))] for i in range(int(breaks))]\n ywind.reverse() \n # reverse necessary, as 2d numpy array the first dimension is\n # the vertical but starts oppositely as we measure lat | \n # v \n # the horizontal dimension works intuitively ->\n ##########################################################\n # Fill tensor\n tens=maketensor(len(sppdic),breaks+1,breaks+1)#only for cactaceae\n for index, r in d_.iterrows():\n # print(r)\n da=whichwindow(ywind,r[1])\n do=whichwindow(xwind,r[2])\n dspp=key_for_value(sppdic,r[0])\n tens[dspp,da,do]= tens[dspp,da,do] +1\n # total observation per grid\n totobs=tens.sum(axis=0)\n # % of cactaceae\n if vtype==\"freq\":\n cactae=tens[:,:,:]/(totobs+0.0001)\n else:\n cactae=tens[:,:,:]\n cactae=(cactae>0)*1\n return(totobs,cactae) \n\ndef vec_tensorgbif(latlon,step,breaks,d,sppdic,vtype):\n tots=[]\n spp=[]\n for lalo in latlon:\n to,sp = tensorgbif(float(lalo[0]),float(lalo[1]),step, breaks, d, sppdic,vtype)\n tots.append(to)\n spp.append(sp)\n return(tots,spp)\n\n\n# def make_cacdic(spp,total):\n# sppdic={'Cactaceae':1 , 'NoCactaceae':0}\n# return(sppdic)\n\n# def make_locdic(lon,totalwindows=1,windowstep=0.1):\n# locdic={}\n# lon=round(lon,1)\n# for i in range(0,totalwindows):\n# locdic[i]=round(lon,1)\n# lon=lon+windowstep\n# return(locdic)\n\n\n# # generate translators of location\n# londic=make_locdic(lon,breaks+1)\n# latdic=make_locdic(lat,breaks+1)\n# # total cactus\n# # d_[d_['family']=='Cactaceae'].size\n# d_[d_['family']=='Brassicaceae'].size\n#\n"
] |
[
[
"pandas.read_csv",
"numpy.zeros"
]
] |
gowtham366/CG_Chennai_Hackathon_2019
|
[
"16a3dc0a399a53f9bf2913b92d6a0952ae86379a"
] |
[
"loan.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 25 10:25:07 2019\n\n@author: gowthc\n\"\"\"\nimport pandas as pd\n#import re\nimport nltk\nfrom sklearn.datasets import load_files\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.svm import SVC\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import accuracy_score\n#import dataframes as df\nnltk.download('stopwords')\n#import pickle;\nimport numpy as np\nfrom nltk.corpus import stopwords\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom nltk.stem import WordNetLemmatizer\ndocuments=[]\nstemmer=WordNetLemmatizer()\ntrain_data=pd.read_csv(\"/content/LoanTest/train.csv\")\ntest_data=pd.read_csv(\"/content/LoanTest/test.csv\")\nprint(train_data.describe())\nsns.barplot(x=train_data[\"PAN_flag\"],y=train_data[\"VoterID_flag\"])\nprint(train_data.head())\nprint(set(train_data[\"Employment.Type\"]))\ntrain_data=train_data.fillna({\"Employment.Type\":\"O\"})\ntest_data=test_data.fillna({\"Employment.Type\":\"O\"})\nprint(set(train_data[\"Employment.Type\"]))\nprint(set(test_data[\"Employment.Type\"]))\nEmployment_mapping={\"Salaried\":0,\"Self employed\":1,\"O\":2}\ntrain_data[\"Employment.Type\"]=train_data[\"Employment.Type\"].map(Employment_mapping)\ntest_data[\"Employment.Type\"]=test_data[\"Employment.Type\"].map(Employment_mapping)\nprint(set(train_data[\"Employment.Type\"]))\nprint(set(train_data[\"AVERAGE.ACCT.AGE\"]))\n\ndef parse_dates(date):\n date=str(date)\n date=date.split()\n year=date[0][0]\n year=int(year)\n Month=date[1][0]\n Month=int(Month)\n #print(year)\n #print(Month)\n total_month=year+Month/12\n #print(total_month)\n return total_month\ntrain_data[\"AVERAGE.ACCT.AGE\"]=train_data[\"AVERAGE.ACCT.AGE\"].apply(lambda row:parse_dates(row))\n\ndef parse_dates1(date):\n date=str(date)\n date=date.split()\n year=date[0][0]\n year=int(year)\n Month=date[1][0]\n Month=int(Month)\n #print(year)\n #print(Month)\n total_month=year+Month/12\n #print(total_month)\n return total_month\ntrain_data[\"CREDIT.HISTORY.LENGTH\"]=train_data[\"CREDIT.HISTORY.LENGTH\"].apply(lambda row:parse_dates1(row))\n'''\ndef parse_dates2(date):\n date=str(date)\n date=date.split()\n year=date[0][0]\n year=int(year)\n Month=date[1][0]\n Month=int(Month)\n #print(year)\n #print(Month)\n total_month=year+Month/12\n #print(total_month)\n return total_month\ntest_data[\"AVERAGE.ACCT.AGE\"]=test_data[\"AVERAGE.ACCT.AGE\"].apply(lambda row:parse_dates2(row))\n\ndef parse_dates3(date):\n date=str(date)\n date=date.split()\n year=date[0][0]\n year=int(year)\n Month=date[1][0]\n Month=int(Month)\n #print(year)\n #print(Month)\n total_month=year+Month/12\n #print(total_month)\n return total_month\ntest_data[\"AVERAGE.ACCT.AGE\"]=test_data[\"AVERAGE.ACCT.AGE\"].apply(lambda row:parse_dates3(row))\n'''\n\nprint(train_data[\"AVERAGE.ACCT.AGE\"])\n'''\nscale1=StandardScaler()\nscale1.fit_transform(test_data[[\"UniqueID\",\"asset_cost\",\"Employment.Type\",\"PERFORM_CNS.SCORE\",\"PRI.NO.OF.ACCTS\",\"PRI.ACTIVE.ACCTS\",\"PERFORM_CNS.SCORE\",\"PRI.NO.OF.ACCTS\",\"SEC.OVERDUE.ACCTS\",\"SEC.CURRENT.BALANCE\",\"SEC.SANCTIONED.AMOUNT\",\"SEC.DISBURSED.AMOUNT\",\"NEW.ACCTS.IN.LAST.SIX.MONTHS\",\"DELINQUENT.ACCTS.IN.LAST.SIX.MONTHS\",\"NO.OF_INQUIRIES\",\"AVERAGE.ACCT.AGE\",\"CREDIT.HISTORY.LENGTH\"]].values)\nXX_Train=test_data[[\"UniqueID\",\"asset_cost\",\"Employment.Type\",\"PERFORM_CNS.SCORE\",\"PRI.NO.OF.ACCTS\",\"PRI.ACTIVE.ACCTS\",\"PERFORM_CNS.SCORE\",\"PRI.NO.OF.ACCTS\",\"SEC.OVERDUE.ACCTS\",\"SEC.CURRENT.BALANCE\",\"SEC.SANCTIONED.AMOUNT\",\"SEC.DISBURSED.AMOUNT\",\"NEW.ACCTS.IN.LAST.SIX.MONTHS\",\"DELINQUENT.ACCTS.IN.LAST.SIX.MONTHS\",\"NO.OF_INQUIRIES\",\"AVERAGE.ACCT.AGE\",\"CREDIT.HISTORY.LENGTH\"]]\nXX_Train,XX_val,YY_val=train_test_split(XX_Train,test_size=0.1)\nadaboost=AdaBoostClassifier()\nadaboost.fit(XX_Train,)\ny1_pred=LogReg.predict(XX_val)\n'''\nscale=StandardScaler()\nscale.fit_transform(train_data[[\"UniqueID\",\"asset_cost\",\"Employment.Type\",\"PERFORM_CNS.SCORE\",\"PRI.NO.OF.ACCTS\",\"PRI.ACTIVE.ACCTS\",\"PERFORM_CNS.SCORE\",\"PRI.NO.OF.ACCTS\",\"SEC.OVERDUE.ACCTS\",\"SEC.CURRENT.BALANCE\",\"SEC.SANCTIONED.AMOUNT\",\"SEC.DISBURSED.AMOUNT\",\"NEW.ACCTS.IN.LAST.SIX.MONTHS\",\"DELINQUENT.ACCTS.IN.LAST.SIX.MONTHS\",\"NO.OF_INQUIRIES\",\"AVERAGE.ACCT.AGE\",\"CREDIT.HISTORY.LENGTH\"]].values)\nX_Train=train_data[[\"UniqueID\",\"asset_cost\",\"Employment.Type\",\"PERFORM_CNS.SCORE\",\"PRI.NO.OF.ACCTS\",\"PRI.ACTIVE.ACCTS\",\"PERFORM_CNS.SCORE\",\"PRI.NO.OF.ACCTS\",\"SEC.OVERDUE.ACCTS\",\"SEC.CURRENT.BALANCE\",\"SEC.SANCTIONED.AMOUNT\",\"SEC.DISBURSED.AMOUNT\",\"NEW.ACCTS.IN.LAST.SIX.MONTHS\",\"DELINQUENT.ACCTS.IN.LAST.SIX.MONTHS\",\"NO.OF_INQUIRIES\",\"AVERAGE.ACCT.AGE\",\"CREDIT.HISTORY.LENGTH\"]]\nY_Train=train_data[\"loan_default\"]\nX_Train,X_val,Y_Train,Y_val=train_test_split(X_Train,Y_Train,test_size=0.1)\nLogReg=AdaBoostClassifier()\nLogReg.fit(X_Train,Y_Train)\ny_pred=LogReg.predict(X_val)\nprint(\"Validation Accuracy: \",accuracy_score(Y_val,y_pred)*100)\n"
] |
[
[
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"sklearn.ensemble.AdaBoostClassifier",
"sklearn.preprocessing.StandardScaler",
"sklearn.metrics.accuracy_score"
]
] |
oplatek/Theano
|
[
"09605e7cae876e15c5502c4edaba6a9644c50c11",
"09605e7cae876e15c5502c4edaba6a9644c50c11"
] |
[
"theano/tensor/elemwise.py",
"theano/sandbox/gpuarray/tests/test_elemwise.py"
] |
[
"from __future__ import print_function\nimport sys\nfrom copy import copy\n\nimport numpy\n\nimport theano\nfrom theano import gof\nfrom theano.compat import izip\nfrom theano.compat import get_unbound_function\nfrom six import iteritems\nfrom six.moves import xrange\nfrom theano.gof import Apply, Op, OpenMPOp\nfrom theano import scalar\nfrom theano.scalar import get_scalar_type\nfrom theano.printing import pprint\nfrom theano.gradient import DisconnectedType\nfrom theano.gof.null_type import NullType\nfrom theano.gof.utils import hash_from_dict\nfrom theano.tensor import elemwise_cgen as cgen\n\nconfig = theano.config\n\n# We cannot import discrete_dtypes or float_dtypes from tensor.basic yet,\n# so we redefine them here\ndiscrete_dtypes = list(map(str, scalar.discrete_types))\nfloat_dtypes = list(map(str, scalar.float_types))\n\n\n# tensor depends on elemwise to provide definitions for several ops\n# but elemwise needs to make TensorType instances, so we have these as\n# placeholders and the tensor module fills them\ndef as_tensor_variable(data):\n raise Exception(\"Circular dependencies prevent using this\"\n \"here. import tensor before elemwise\")\n\n\ndef TensorType(*inputs, **kwargs):\n raise Exception(\"Circular dependencies prevent \"\n \"using this here. import tensor before elemwise\")\n\n\ndef TensorVariable(*inputs, **kwargs):\n raise Exception(\"Circular dependencies \"\n \"prevent using this here. import tensor before elemwise\")\n\n\ndef TensorConstant(*inputs, **kwargs):\n raise Exception(\"Circular dependencies \"\n \"prevent using this here. import tensor before elemwise\")\n\n\n##################\n# DimShuffle #\n##################\n\nclass DimShuffle(Op):\n \"\"\"\n Allows to reorder the dimensions of a tensor or insert or remove\n broadcastable dimensions.\n\n In the following examples, 'x' means that we insert a broadcastable\n dimension and a numerical index represents the dimension of the same\n rank in the tensor passed to perform.\n\n Parameters\n ----------\n input_broadcastable\n The expected broadcastable pattern of the input\n new_order\n A list representing the relationship between the input's\n dimensions and the output's dimensions. Each element of the\n list can either be an index or 'x'. Indices must be encoded\n as python integers, not theano symbolic integers.\n inplace : bool, optional\n If True, the output will be a view of the input.\n If False (default), the output will be a copy of the input.\n\n If j = new_order[i] is an index, the output's ith dimension\n will be the input's jth dimension.\n If new_order[i] is 'x', the output's ith dimension will\n be 1 and Broadcast operations will be allowed to do broadcasting\n over that dimension.\n\n If input.broadcastable[i] == False then i must be found in new_order.\n Broadcastable dimensions, on the other hand, can be discarded.\n\n Extended Summary\n ----------------\n DimShuffle((False, False, False), ['x', 2, 'x', 0, 1])\n\n This op will only work on 3d tensors with no broadcastable\n dimensions. The first dimension will be broadcastable,\n then we will have the third dimension of the input tensor as\n the second of the resulting tensor, etc. If the tensor has\n shape (20, 30, 40), the resulting tensor will have dimensions\n (1, 40, 1, 20, 30). (AxBxC tensor is mapped to 1xCx1xAxB tensor)\n\n DimShuffle((True, False), [1])\n\n This op will only work on 2d tensors with the first dimension\n broadcastable.\n The second dimension of the input tensor will be the first dimension of\n the resulting tensor.\n If the tensor has shape (1, 20), the resulting tensor will have shape\n (20, ).\n\n More examples :\n DimShuffle((), ['x']) -> make a 0d (scalar) into a 1d vector\n DimShuffle((False, False), [0, 1]) -> identity\n DimShuffle((False, False), [1, 0]) -> inverts the 1st and 2nd dimensions\n DimShuffle((False,), ['x', 0]) -> make a row out\n of a 1d vector (N to 1xN)\n DimShuffle((False,), [0, 'x']) -> make a column\n out of a 1d vector (N to Nx1)\n DimShuffle((False, False, False), [2, 0, 1]) -> AxBxC to CxAxB\n DimShuffle((False, False), [0, 'x', 1]) -> AxB to Ax1xB\n DimShuffle((False, False), [1, 'x', 0]) -> AxB to Bx1xA\n\n The reordering of the dimensions can be done in numpy with the\n transpose function.\n Adding, subtracting dimensions can be done with reshape.\n\n \"\"\"\n\n _f16_ok = True\n check_input = False\n\n def __init__(self, input_broadcastable, new_order, inplace=False):\n input_broadcastable = tuple(input_broadcastable)\n self.input_broadcastable = input_broadcastable\n new_order = tuple(new_order)\n self.new_order = new_order\n self.inplace = inplace\n\n for i, j in enumerate(new_order):\n if j != 'x':\n # There is a bug in numpy that results in isinstance(x, int)\n # returning False for numpy integers.\n # See <http://projects.scipy.org/numpy/ticket/2235>.\n if not isinstance(j, (int, numpy.integer)):\n raise TypeError(\"DimShuffle indices must be python ints.\")\n if j >= len(input_broadcastable):\n raise ValueError((\"new_order[%d] is %d, but the input \"\n \"only has %d axes.\") %\n (i, j, len(input_broadcastable)))\n if j in new_order[(i + 1):]:\n raise ValueError(\"The same input dimension may not appear \"\n \"twice in the list of output dimensions\",\n new_order)\n\n # list of dimensions of the input to drop\n self.drop = []\n for i, b in enumerate(input_broadcastable):\n if i not in new_order:\n # we want to drop this dimension because it's not a value in\n # new_order\n if b == 1: # 1 aka True\n self.drop.append(i)\n else:\n # we cannot drop non-broadcastable dimensions\n raise ValueError(\n \"You cannot drop a non-broadcastable dimension.\",\n (input_broadcastable, new_order))\n\n # this is the list of the original dimensions that we keep\n self.shuffle = [x for x in new_order if x != 'x']\n\n # list of dimensions of the output that are broadcastable and were not\n # in the original input\n self.augment = [i for i, x in enumerate(new_order) if x == 'x']\n\n if self.inplace:\n self.view_map = {0: [0]}\n\n self._rehash()\n\n def __getstate__(self):\n d = dict(self.__dict__)\n del d['_hashval']\n return d\n\n def __setstate__(self, d):\n self.__dict__.update(d)\n self._rehash()\n\n def make_node(self, _input):\n input = as_tensor_variable(_input)\n ib = tuple(input.type.broadcastable)\n if not ib == self.input_broadcastable:\n if len(ib) != len(self.input_broadcastable):\n raise TypeError((\n \"The number of dimensions of the \"\n \"input is incorrect for this op. Expected %s, got %s.\"\n % (self.input_broadcastable, ib)))\n for expected, b in zip(self.input_broadcastable, ib):\n if expected is True and b is False:\n raise TypeError((\n \"The broadcastable pattern of the \"\n \"input is incorrect for this op. Expected %s, got %s.\"\n % (self.input_broadcastable, ib)))\n # else, expected == b or expected is False and b is True\n # Both case are good.\n\n ob = []\n for value in self.new_order:\n if value == 'x':\n ob.append(True)\n else:\n ob.append(ib[value])\n\n output = TensorType(dtype=input.type.dtype,\n broadcastable=ob)()\n\n return Apply(self, [input], [output])\n\n def __eq__(self, other):\n # it's probably not necessary to compare input_broadcastable\n return type(self) == type(other) \\\n and self.inplace == other.inplace \\\n and self.new_order == other.new_order \\\n and self.input_broadcastable == other.input_broadcastable\n\n def _rehash(self):\n self._hashval = (hash(type(self).__name__) ^\n hash(type(self).__module__) ^\n hash(self.inplace) ^\n hash(self.new_order) ^\n hash(self.input_broadcastable))\n\n def __hash__(self):\n return self._hashval\n\n def __str__(self):\n if self.inplace:\n return \"InplaceDimShuffle{%s}\" % \",\".join(str(x)\n for x in self.new_order)\n else:\n return \"DimShuffle{%s}\" % \",\".join(str(x) for x in self.new_order)\n\n def perform(self, node, inp, out):\n input, = inp\n storage, = out\n # drop\n res = input\n if type(res) != numpy.ndarray and type(res) != numpy.memmap:\n raise TypeError(res)\n\n # transpose\n res = res.transpose(self.shuffle + self.drop)\n\n # augment\n shape = list(res.shape[:len(self.shuffle)])\n for augm in self.augment:\n shape.insert(augm, 1)\n res = res.reshape(shape)\n\n # copy (if not inplace)\n if not self.inplace:\n res = numpy.copy(res)\n\n storage[0] = numpy.asarray(res) # asarray puts scalars back into array\n\n def infer_shape(self, node, shapes):\n ishp, = shapes\n # transpose\n rval = [ishp[i] for i in self.shuffle]\n\n # augment\n for augm in self.augment:\n rval.insert(augm, 1)\n return [rval]\n\n def R_op(self, inputs, eval_points):\n if None in eval_points:\n return [None]\n return self(*eval_points, **dict(return_list=True))\n\n def c_code(self, node, name, inp, out, sub):\n input, = inp\n res, = out\n basename = input + '__view_or_copy'\n\n def statements(lst):\n return ';\\n'.join(lst) + ';'\n\n nd_in = len(self.input_broadcastable)\n nd_out = len(self.new_order)\n\n check_input_nd = [('if (PyArray_NDIM(%(input)s) != ' + str(nd_in) + ')'\n '{PyErr_SetString(PyExc_NotImplementedError, '\n '\"input nd\"); %(fail)s;}')]\n\n clear_output = ['if (%(res)s) {Py_XDECREF(%(res)s);}']\n\n # get the copy / view of the input depending on whether we're doingi\n # things inplace or not.\n if self.inplace:\n get_base = [\n '{ PyArrayObject * %(basename)s = %(input)s', 'Py_INCREF((PyObject*)%(basename)s)']\n else:\n get_base = [('{ PyArrayObject * %(basename)s = '\n '(PyArrayObject*)PyArray_FromAny((PyObject*)%(input)s,'\n ' NULL, 0, 0, NPY_ARRAY_ALIGNED|NPY_ARRAY_ENSURECOPY,'\n ' NULL)')]\n\n shape_statements = ['npy_intp dimensions[%i]' % nd_out]\n for i, o in enumerate(self.new_order):\n if o != 'x':\n shape_statements += [('dimensions[' + str(\n i) + '] = PyArray_DIMS(%(basename)s)[' + str(o) + ']')]\n else:\n shape_statements += [('dimensions[' + str(i) + '] = 1')]\n\n strides_statements = ['npy_intp strides[%i]' % nd_out]\n\n # set the strides of the non-broadcasted dimensions\n for i, o in enumerate(self.new_order):\n if o != 'x':\n strides_statements += [('strides[' + str(i) +\n '] = PyArray_DIMS(%(basename)s)[' +\n str(o) +\n '] == 1? 0 : '\n 'PyArray_STRIDES(%(basename)s)[' +\n str(o) + ']')]\n else:\n strides_statements += [('strides[' + str(i) + '] = 0')]\n\n # set the strides of the broadcasted dimensions\n # this algorithm is from numpy: PyArray_Newshape() in\n # cvs/numpy/numpy/core/src/multiarraymodule.c\n if nd_out > 0:\n strides_statements.append(\n 'if (strides[' +\n str(nd_out) +\n '-1] == 0) strides[' +\n str(nd_out) +\n '-1] = PyArray_DESCR(%(basename)s)->elsize'\n )\n for i in xrange(nd_out - 2, -1, -1):\n strides_statements.append(\n \"if (strides[%(i)s] == 0) strides[%(i)s] = strides[%(i)s+1] * dimensions[%(i)s+1]\" % dict(i=str(i)))\n\n #\n # PyObject* PyArray_New(PyTypeObject* subtype, int nd, npy_intp* dims, int type_num,\n # npy_intp* strides, void* data, int itemsize, int flags, PyObject* obj)\n #\n close_bracket = [\n # create a new array,\n ('%(res)s = (PyArrayObject*)PyArray_New(&PyArray_Type, '\n '' + str(nd_out) + ', dimensions, '\n 'PyArray_TYPE(%(basename)s), strides, '\n 'PyArray_DATA(%(basename)s), PyArray_ITEMSIZE(%(basename)s), '\n # borrow only the writable flag from the base\n # the NPY_OWNDATA flag will default to 0.\n '(NPY_ARRAY_WRITEABLE*PyArray_ISWRITEABLE(%(basename)s)), '\n 'NULL)'),\n 'if (%(res)s == NULL) %(fail)s;',\n # recalculate flags: CONTIGUOUS, FORTRAN, ALIGNED\n 'PyArray_UpdateFlags(%(res)s, NPY_ARRAY_UPDATE_ALL)',\n # we are making a view in both inplace and non-inplace cases\n \"\"\"\n#if NPY_API_VERSION < 0x00000007\nPyArray_BASE(%(res)s) = (PyObject*)%(basename)s;\n#else\nPyArray_SetBaseObject(%(res)s, (PyObject*)%(basename)s);\n#endif\n\"\"\"\n '}']\n\n full_code = statements(check_input_nd +\n clear_output +\n get_base +\n shape_statements +\n strides_statements +\n close_bracket)\n\n if 0:\n print('C_CODE')\n print('')\n print(self)\n print(\"IN BROAD\", self.input_broadcastable)\n print(\"NEW ORDER\", self.new_order)\n print(\"SHUFFLE\", self.shuffle)\n print(\"AUGMENT\", self.augment)\n print('------------')\n print('')\n print(full_code)\n\n if 0:\n sys.exit()\n\n return full_code % dict(locals(), **sub)\n\n def c_code_cache_version(self):\n return (3,)\n\n def grad(self, inp, grads):\n x, = inp\n gz, = grads\n gz = as_tensor_variable(gz)\n grad_order = ['x'] * len(x.type.broadcastable)\n for i, v in enumerate(self.new_order):\n if v != 'x':\n grad_order[v] = i\n # Do not make the DimShuffle inplace as an optimization at the\n # canonicalization optimization phase will remove the inplace.\n # The inplace will be reintroduced automatically later in the graph.\n if 'int' in inp[0].dtype:\n return [inp[0].zeros_like(dtype=theano.config.floatX)]\n else:\n return [DimShuffle(gz.type.broadcastable, grad_order)(\n Elemwise(scalar.identity)(gz))]\n\n\nclass DimShufflePrinter:\n\n def __p(self, new_order, pstate, r):\n if new_order != () and new_order[0] == 'x':\n return \"%s\" % self.__p(new_order[1:], pstate, r)\n# return \"[%s]\" % self.__p(new_order[1:], pstate, r)\n if list(new_order) == list(range(r.type.ndim)):\n return pstate.pprinter.process(r)\n if list(new_order) == list(reversed(range(r.type.ndim))):\n return \"%s.T\" % pstate.pprinter.process(r)\n return \"DimShuffle{%s}(%s)\" % (\", \".join(map(str, new_order)),\n pstate.pprinter.process(r))\n\n def process(self, r, pstate):\n if r.owner is None:\n raise TypeError(\"Can only print DimShuffle.\")\n elif isinstance(r.owner.op, DimShuffle):\n ord = r.owner.op.new_order\n return self.__p(ord, pstate, r.owner.inputs[0])\n else:\n raise TypeError(\"Can only print DimShuffle.\")\n\npprint.assign(lambda pstate, r: r.owner and isinstance(r.owner.op, DimShuffle),\n DimShufflePrinter())\n\n\n################\n# Elemwise #\n################\n\nclass Elemwise(OpenMPOp):\n \"\"\"\n Generalizes a scalar op to tensors.\n\n All the inputs must have the same number of dimensions. When the\n Op is performed, for each dimension, each input's size for that\n dimension must be the same. As a special case, it can also be 1\n but only if the input's broadcastable flag is True for that\n dimension. In that case, the tensor is (virtually) replicated\n along that dimension to match the size of the others.\n\n The dtypes of the outputs mirror those of the scalar Op that is\n being generalized to tensors. In particular, if the calculations\n for an output are done inplace on an input, the output type must\n be the same as the corresponding input type (see the doc of\n scalar.ScalarOp to get help about controlling the output type)\n\n Parameters\n -----------\n scalar_op\n An instance of a subclass of scalar.ScalarOp which works uniquely\n on scalars.\n inplace_pattern\n A dictionary that maps the index of an output to the\n index of an input so the output is calculated inplace using\n the input's storage. (Just like destroymap, but without the lists.)\n nfunc_spec\n Either None or a tuple of three elements,\n (nfunc_name, nin, nout) such that getattr(numpy, nfunc_name)\n implements this operation, takes nin inputs and nout outputs.\n Note that nin cannot always be inferred from the scalar op's\n own nin field because that value is sometimes 0 (meaning a\n variable number of inputs), whereas the numpy function may\n not have varargs.\n\n Examples\n --------\n Elemwise(add) # represents + on tensors (x + y)\n Elemwise(add, {0 : 0}) # represents the += operation (x += y)\n Elemwise(add, {0 : 1}) # represents += on the second argument (y += x)\n Elemwise(mul)(rand(10, 5), rand(1, 5)) # the second input is completed\n # along the first dimension to match the first input\n Elemwise(true_div)(rand(10, 5), rand(10, 1)) # same but along the\n # second dimension\n Elemwise(int_div)(rand(1, 5), rand(10, 1)) # the output has size (10, 5)\n Elemwise(log)(rand(3, 4, 5))\n\n \"\"\"\n\n def __init__(self, scalar_op, inplace_pattern=None, name=None,\n nfunc_spec=None, openmp=None):\n if inplace_pattern is None:\n inplace_pattern = {}\n self.name = name\n self.scalar_op = scalar_op\n self.inplace_pattern = inplace_pattern\n self.destroy_map = dict((o, [i]) for o, i in inplace_pattern.items())\n\n self.ufunc = None\n self.nfunc = None\n if nfunc_spec is None:\n nfunc_spec = getattr(scalar_op, 'nfunc_spec', None)\n self.nfunc_spec = nfunc_spec\n if nfunc_spec:\n self.nfunc = getattr(numpy, nfunc_spec[0])\n\n # precompute the hash of this node\n self._rehash()\n super(Elemwise, self).__init__(openmp=openmp)\n\n def __getstate__(self):\n d = copy(self.__dict__)\n d.pop('ufunc')\n d.pop('nfunc')\n d.pop('__epydoc_asRoutine', None)\n d.pop('_hashval')\n return d\n\n def __setstate__(self, d):\n super(Elemwise, self).__setstate__(d)\n self.ufunc = None\n self.nfunc = None\n if getattr(self, 'nfunc_spec', None):\n self.nfunc = getattr(numpy, self.nfunc_spec[0])\n elif 0 < self.scalar_op.nin < 32:\n self.ufunc = numpy.frompyfunc(self.scalar_op.impl,\n self.scalar_op.nin,\n self.scalar_op.nout)\n self._rehash()\n\n def make_node(self, *inputs):\n \"\"\"\n If the inputs have different number of dimensions, their shape\n is left-completed to the greatest number of dimensions with 1s\n using DimShuffle.\n \"\"\"\n inputs = list(map(as_tensor_variable, inputs))\n shadow = self.scalar_op.make_node(\n *[get_scalar_type(dtype=i.type.dtype).make_variable()\n for i in inputs])\n\n target_length = max([input.type.ndim for input in inputs])\n\n args = []\n for input in inputs:\n length = input.type.ndim\n difference = target_length - length\n if not difference:\n args.append(input)\n else:\n # TODO: use LComplete instead\n args.append(DimShuffle(\n input.type.broadcastable,\n ['x'] * difference + list(range(length)),\n inplace=False)(input))\n inputs = args\n\n # HERE: all the broadcast dims have the same length now\n\n # cleverness: we iterate over the first, second, third broadcast flag\n # of all inputs in parallel... the all() gives us each output\n # broadcastable bit in turn.\n\n # it is multiplied by nout because Elemwise supports multiple outputs\n # (nout of them)\n out_broadcastables = [[all(bcast)\n for bcast in\n izip(*[input.type.broadcastable\n for input in inputs])]] * shadow.nout\n\n # inplace_pattern maps output idx -> input idx\n inplace_pattern = self.inplace_pattern\n if inplace_pattern:\n for overwriter, overwritten in iteritems(inplace_pattern):\n for ob, ib in izip(out_broadcastables[overwriter],\n inputs[overwritten].type.broadcastable):\n if ib and not ob:\n raise ValueError(\n \"Operation cannot be done inplace on an input \"\n \"with broadcasted dimensions.\")\n\n out_dtypes = [o.type.dtype for o in shadow.outputs]\n if any(inputs[i].type.dtype != out_dtypes[o]\n for o, i in inplace_pattern.items()):\n raise TypeError((\n \"Cannot do an inplace operation on incompatible data types.\",\n ([i.type.dtype for i in inputs], out_dtypes, inplace_pattern)))\n\n outputs = [TensorType(dtype=dtype, broadcastable=broadcastable)()\n for dtype, broadcastable in izip(out_dtypes,\n out_broadcastables)]\n return Apply(self, inputs, outputs)\n\n def __eq__(self, other):\n if type(self) == type(other):\n items = list(self.inplace_pattern.items())\n other_items = list(other.inplace_pattern.items())\n items.sort()\n other_items.sort()\n rval = ((self.scalar_op == other.scalar_op) and\n (items == other_items))\n return rval\n return False\n\n def _rehash(self):\n inplace_pattern_hash = hash_from_dict(self.inplace_pattern)\n h = hash('Elemwise') ^ hash(self.scalar_op) ^ inplace_pattern_hash\n assert h == getattr(self, '_hashval', h)\n self._hashval = h\n\n def __hash__(self):\n return self._hashval\n\n def __str__(self):\n if self.name is None:\n if self.inplace_pattern:\n items = list(self.inplace_pattern.items())\n items.sort()\n return \"Elemwise{%s}%s\" % (self.scalar_op, str(items))\n else:\n return \"Elemwise{%s}\" % (self.scalar_op)\n else:\n return self.name\n\n def R_op(self, inputs, eval_points):\n outs = self(*inputs, **dict(return_list=True))\n rval = [None for x in outs]\n # For each output\n for idx, out in enumerate(outs):\n # make such that _bgrads computes only the gradients of the\n # current output on the inputs ( and not all outputs)\n ograds = [x.zeros_like() for x in outs]\n ograds[idx] = theano.tensor.ones_like(out)\n\n bgrads = self._bgrad(inputs, ograds)\n rop_out = None\n\n for jdx, (inp, eval_point) in enumerate(izip(inputs,\n eval_points)):\n # if None, then we can just ignore this branch ..\n # what we do is to assume that for any non-differentiable\n # branch, the gradient is actually 0, which I think is not\n # the right thing to do .. have to talk to Ian and James\n # about it\n\n if bgrads[jdx] is None or \\\n isinstance(bgrads[jdx].type, DisconnectedType):\n pass\n elif eval_point is not None:\n if rop_out is None:\n rop_out = bgrads[jdx] * eval_point\n else:\n rop_out = rop_out + bgrads[jdx] * eval_point\n\n rval[idx] = rop_out\n\n return rval\n\n def connection_pattern(self, node):\n\n if hasattr(self.scalar_op, 'connection_pattern'):\n return self.scalar_op.connection_pattern(node)\n\n return [[True for output in node.outputs] for ipt in node.inputs]\n\n def grad(self, inputs, ograds):\n\n outs = self(*inputs)\n if not isinstance(outs, (list, tuple)):\n outs = [outs]\n\n # compute grad with respect to broadcasted input\n rval = self._bgrad(inputs, ograds)\n\n # TODO: make sure that zeros are clearly identifiable\n # to the gradient.grad method when the outputs have\n # some integer and some floating point outputs\n if False in [str(out.type.dtype).find('int') == -1\n for out in outs]:\n # For integer output, return value may\n # only be zero or undefined\n # We don't bother with trying to check\n # that the scalar ops correctly\n # returned something that evaluates to 0,\n # we just make the return\n # value obviously zero so that gradient.grad\n # can tell this op did\n # the right thing.\n new_rval = []\n for elem, ipt in izip(rval, inputs):\n if isinstance(elem.type, (NullType, DisconnectedType)):\n new_rval.append(elem)\n else:\n elem = ipt.zeros_like()\n if str(elem.type.dtype).find('int') != -1:\n elem = elem.astype(theano.config.floatX)\n assert str(elem.type.dtype).find('int') == -1\n new_rval.append(elem)\n return new_rval\n\n # sum out the broadcasted dimensions\n for i, ipt in enumerate(inputs):\n if isinstance(rval[i].type, (NullType, DisconnectedType)):\n continue\n\n # list of all the dimensions that are broadcastable for input[i] so\n # we can sum over them\n # todo: only count dimensions that were effectively broadcasted\n to_sum = [j for j, bcast in enumerate(ipt.type.broadcastable)\n if bcast]\n\n if to_sum:\n shuffle = []\n j = 0\n for bcast in ipt.type.broadcastable:\n if bcast == 1:\n shuffle.append('x')\n else:\n shuffle.append(j)\n j += 1\n # close if\n # close for\n sr = Sum(axis=to_sum)(rval[i])\n sr = sr.dimshuffle(shuffle)\n # sr = DimShuffle(sr.type.broadcastable, shuffle)(sr)\n rval[i] = sr\n # close if\n # close for\n\n return rval\n\n def _bgrad(self, inputs, ograds):\n # returns grad, with respect to broadcasted versions of inputs\n\n prev_setting = theano.config.compute_test_value\n\n try:\n\n theano.config.compute_test_value = 'off'\n\n def as_scalar(t):\n if isinstance(t.type, (NullType, DisconnectedType)):\n return t\n return get_scalar_type(t.type.dtype)()\n\n scalar_inputs = list(map(as_scalar, inputs))\n scalar_ograds = list(map(as_scalar, ograds))\n scalar_igrads = self.scalar_op.grad(scalar_inputs, scalar_ograds)\n for igrad in scalar_igrads:\n assert igrad is not None, self.scalar_op\n\n finally:\n\n theano.config.compute_test_value = prev_setting\n\n if not isinstance(scalar_igrads, (list, tuple)):\n raise TypeError('%s.grad returned %s instead of list or tuple' %\n (str(self.scalar_op), str(type(scalar_igrads))))\n\n nd = len(inputs[0].type.broadcastable) # this is the same for everyone\n\n def transform(r):\n # From a graph of ScalarOps, make a graph of Broadcast ops.\n if isinstance(r.type, (NullType, DisconnectedType)):\n return r\n if r in scalar_inputs:\n return inputs[scalar_inputs.index(r)]\n if r in scalar_ograds:\n return ograds[scalar_ograds.index(r)]\n node = r.owner\n if node is None:\n # the gradient contains a constant, translate it as\n # an equivalent TensorType of size 1 and proper number of\n # dimensions\n res = theano.tensor.constant(numpy.asarray(r.data), dtype=r.type.dtype)\n return DimShuffle((), ['x'] * nd, inplace=False)(res)\n new_r = Elemwise(node.op, {})(\n *[transform(ipt) for ipt in node.inputs])\n return new_r\n ret = []\n for scalar_igrad, ipt in izip(scalar_igrads, inputs):\n if scalar_igrad is None:\n # undefined gradient\n ret.append(None)\n continue\n ret.append(transform(scalar_igrad))\n\n return ret\n\n def make_thunk(self, node, storage_map, compute_map, no_recycling):\n node_ = node\n # Postpone the ufunc building to the last minutes\n # NumPy ufunc support only up to 31 inputs.\n # But our c code support more.\n if (len(node.inputs) < 32 and\n (self.nfunc is None or\n self.scalar_op.nin != len(node.inputs)) and\n self.ufunc is None):\n\n ufunc = numpy.frompyfunc(self.scalar_op.impl,\n len(node.inputs),\n self.scalar_op.nout)\n if self.scalar_op.nin > 0:\n # We can reuse it for many nodes\n self.ufunc = ufunc\n else:\n node.tag.ufunc = ufunc\n\n return super(Elemwise, node_.op).make_thunk(node_, storage_map,\n compute_map, no_recycling)\n\n def perform(self, node, inputs, output_storage):\n if len(node.inputs) >= 32:\n # Some versions of NumPy will segfault, other will raise a\n # ValueError, if the number of inputs to a ufunc is 32 or more.\n # In that case, the C version should be used, or Elemwise fusion\n # should be disabled.\n super(Elemwise, self).perform(node, inputs, output_storage)\n\n for dims in izip(*[list(zip(input.shape, sinput.type.broadcastable))\n for input, sinput in zip(inputs, node.inputs)]):\n if max(d for d, b in dims) != 1 and (1, False) in dims:\n # yes there may be more compact ways to write this code,\n # but please maintain python 2.4 compatibility\n # (no \"x if c else y\")\n msg = []\n assert len(inputs) == len(node.inputs)\n for input, sinput in zip(inputs, node.inputs):\n assert len(input.shape) == len(sinput.type.broadcastable)\n msg2 = []\n for d, b in zip(input.shape, sinput.type.broadcastable):\n if b:\n msg2 += ['*']\n else:\n msg2 += [str(d)]\n msg.append('(%s)' % \", \".join(msg2))\n\n base_exc_str = 'Dimension mismatch; shapes are %s' % (\n ', '.join(msg))\n raise ValueError(base_exc_str)\n\n # Determine the shape of outputs\n out_shape = []\n for values in izip(*[input.shape for input in inputs]):\n if any(v == 0 for v in values):\n # All non-broadcasted dimensions should be zero\n assert max(values) <= 1\n out_shape.append(0)\n else:\n out_shape.append(max(values))\n out_shape = tuple(out_shape)\n\n ufunc_args = inputs\n ufunc_kwargs = {}\n if self.nfunc and len(inputs) == self.nfunc_spec[1]:\n ufunc = self.nfunc\n nout = self.nfunc_spec[2]\n # Numpy ufuncs will sometimes perform operations in\n # float16, in particular when the input is int8.\n # This is not something that we want, and we do not\n # do it in the C code, so we specify that the computation\n # should be carried out in the returned dtype.\n # This is done via the \"sig\" kwarg of the ufunc, its value\n # should be something like \"ff->f\", where the characters\n # represent the dtype of the inputs and outputs.\n out_dtype = node.outputs[0].dtype\n if out_dtype in float_dtypes and isinstance(ufunc, numpy.ufunc):\n char = numpy.sctype2char(out_dtype)\n sig = char * node.nin + '->' + char * node.nout\n ufunc_kwargs['sig'] = sig\n # Unfortunately, the else case does not allow us to\n # directly feed the destination arguments to the nfunc\n # since it sometimes requires resizing. Doing this\n # optimization is probably not worth the effort, since we\n # should normally run the C version of the Op.\n else:\n # the second calling form is used because in certain versions of\n # numpy the first (faster) version leads to segfaults\n if self.ufunc:\n ufunc = self.ufunc\n else:\n if not hasattr(node.tag, 'ufunc'):\n # It happen that make_thunk isn't called, like in\n # get_scalar_constant_value\n node.tag.ufunc = numpy.frompyfunc(self.scalar_op.impl,\n len(node.inputs),\n self.scalar_op.nout)\n\n ufunc = node.tag.ufunc\n\n nout = ufunc.nout\n\n variables = ufunc(*ufunc_args, **ufunc_kwargs)\n\n if nout == 1:\n variables = [variables]\n i = 0\n for variable, storage, nout in izip(variables, output_storage,\n node.outputs):\n if getattr(variable, \"dtype\", \"\") == 'object':\n # Since numpy 1.6, function created with numpy.frompyfunc\n # always return an ndarray with dtype object\n variable = numpy.asarray(variable, dtype=nout.dtype)\n\n if i in self.inplace_pattern:\n odat = inputs[self.inplace_pattern[i]]\n odat[...] = variable\n storage[0] = odat\n # Sometimes NumPy return a Python type.\n # Some Theano op return a different dtype like floor, ceil,\n # trunc, eq, ...\n elif (not isinstance(variable, numpy.ndarray) or\n variable.dtype != nout.dtype):\n variable = numpy.asarray(variable, nout.dtype)\n # The next line is needed for numpy 1.9. Otherwise\n # there are tests that fail in DebugMode.\n # Normally we would call theano.misc._asarray, but it\n # is faster to inline the code. We know that the dtype\n # are the same string, just different typenum.\n if numpy.dtype(nout.dtype).num != variable.dtype.num:\n variable = variable.view(dtype=nout.dtype)\n storage[0] = variable\n # numpy.real return a view!\n elif not variable.flags.owndata:\n storage[0] = variable.copy()\n else:\n storage[0] = variable\n i += 1\n\n def infer_shape(self, node, i_shapes):\n rval = []\n for o in node.outputs:\n oshp = []\n for dim, b in enumerate(o.type.broadcastable):\n b_dim = None\n if b:\n # this is broadcastable\n b_dim = 1\n else:\n # there must be some input that is not broadcastable in\n # dimension 'dim'\n for ishp, i in izip(i_shapes, node.inputs):\n if isinstance(i.type, theano.scalar.Scalar):\n continue # we skip scalar\n if not i.type.broadcastable[dim]:\n # input i is not broadcastable in position dim\n # therefore if its shape is known, we can use it\n # as the output shape\n if ishp[dim]:\n b_dim = ishp[dim]\n break\n\n # b_dim might still be None, if every input's shape was unknown\n # in dimension 'dim'\n oshp.append(b_dim)\n # TODO: it would be interesting to return the constraining\n # information that if one of the inputs shape[dim] is known\n # and another input's shape[dim] is not, that we can now assume\n # that the other input's shape[dim] is the same as the first.\n rval.append(tuple(oshp))\n return rval\n\n def _c_all(self, node, nodename, inames, onames, sub):\n _inames = inames\n _onames = onames\n\n inames = gof.utils.uniq(inames)\n inputs = gof.utils.uniq(node.inputs)\n # assert that inames and inputs order stay consistent.\n # This is to protect again futur change of uniq.\n assert len(inames) == len(inputs)\n ii, iii = list(zip(*gof.utils.uniq(list(zip(_inames, node.inputs)))))\n assert all([x == y for x, y in zip(ii, inames)])\n assert all([x == y for x, y in zip(iii, inputs)])\n\n defines = \"\"\n undefs = \"\"\n\n # The destroy map is a map of output indices to input indices\n # that overwrite them. We just convert them to the actual\n # Variables.\n dmap = dict([(node.outputs[o], [node.inputs[i]])\n for o, i in iteritems(self.inplace_pattern)])\n\n # dtypes of the inputs\n idtypes = [input.type.dtype_specs()[1] for input in inputs]\n\n # These are the outputs that we will need to allocate\n # (output, name, name of the c type), transposed\n real = list(zip(*[(r, s, r.type.dtype_specs()[1])\n for r, s in izip(node.outputs, onames)\n if r not in dmap]))\n if real:\n real_outputs, real_onames, real_odtypes = real\n else:\n real_outputs, real_onames, real_odtypes = [], [], []\n\n # Outputs that are aliased with an input (inplace)\n # (output, name), transposed (c type name not needed since we don't\n # need to allocate.\n aliased = list(zip(*[(r, s)\n for (r, s) in izip(node.outputs, onames)\n if r in dmap]))\n if aliased:\n aliased_outputs, aliased_onames = aliased\n else:\n aliased_outputs, aliased_onames = [], []\n\n # for each input:\n # same as range(ndim), but with 'x' at all broadcastable positions\n orders = [[x and 'x' or i\n for i, x in enumerate(input.type.broadcastable)]\n for input in inputs]\n\n # number of nested loops we will need (all inputs have same\n # dimensionality)\n nnested = len(orders[0])\n sub = dict(sub)\n for i, (input, iname) in enumerate(izip(inputs, inames)):\n # the c generators will substitute the input names for\n # references to loop variables lv0, lv1, ...\n sub['lv%i' % i] = iname\n\n decl = cgen.make_declare(orders, idtypes, sub)\n checks = cgen.make_checks(orders, idtypes, sub)\n\n # Check if all inputs (except broadcasted scalar) are fortran.\n # In that case, create an fortran output ndarray.\n z = list(zip(inames, inputs))\n alloc_fortran = ' && '.join([\"PyArray_ISFORTRAN(%s)\" % arr\n for arr, var in z\n if not all(var.broadcastable)])\n # If it is a scalar, make it c contig to prevent problem with\n # NumPy C and F contig not always set as both of them.\n if len(alloc_fortran) == 0:\n alloc_fortran = '0'\n\n alloc = \"\"\n # We loop over the \"real\" outputs, i.e., those that are not\n # inplace (must be allocated) and we declare/allocate/check\n # them\n for output, oname, odtype in izip(\n real_outputs, real_onames, real_odtypes):\n i += 1 # before this loop, i = number of inputs\n sub['lv%i' % i] = oname\n sub['olv'] = oname\n alloc += cgen.make_declare([list(range(nnested))], [odtype],\n dict(sub, lv0=oname))\n alloc += cgen.make_alloc(orders, odtype, sub,\n fortran=alloc_fortran)\n alloc += cgen.make_checks([list(range(nnested))], [odtype],\n dict(sub, lv0=oname))\n olv_index = i # index of the last output\n\n # We loop over the \"aliased\" outputs, i.e., those that are\n # inplace (overwrite the contents of one of the inputs) and\n # make the output pointers point to theur corresponding input\n # pointers.\n for output, oname in izip(aliased_outputs, aliased_onames):\n olv_index = inputs.index(dmap[output][0])\n iname = inames[olv_index]\n # We make the output point to the corresponding input and\n # decrease the reference of whatever the output contained\n # prior to this\n alloc += \"\"\"\n if (%(oname)s) {\n Py_XDECREF(%(oname)s);\n }\n %(oname)s = %(iname)s;\n Py_XINCREF(%(oname)s);\n \"\"\" % locals()\n # We alias the scalar variables\n defines += \"#define %(oname)s_i %(iname)s_i\" % locals()\n undefs += \"#undef %(oname)s_i\" % locals()\n\n # Note: here, olv_index is either the index of the last output\n # which is allocated, OR, if there are any aliased outputs,\n # the index of the last of these aliased outputs.\n\n # We generate the C code of the inner loop using the scalar op\n task_code = self.scalar_op.c_code(\n Apply(self.scalar_op,\n [get_scalar_type(dtype=input.type.dtype).make_variable()\n for input in node.inputs],\n [get_scalar_type(dtype=output.type.dtype).make_variable()\n for output in node.outputs]),\n nodename + '_scalar_',\n [\"%s_i\" % s for s in _inames],\n [\"%s_i\" % s for s in onames],\n sub)\n code = \"\"\"\n {\n %(defines)s\n %(task_code)s\n %(undefs)s\n }\n \"\"\" % locals()\n\n loop_orders = orders + [list(range(nnested))] * len(real_onames)\n dtypes = (idtypes + list(real_odtypes))\n if all([o.ndim <= 1 for o in node.outputs] or\n # Use simpler code when output ndim == 0 or 1\n # or for broadcated scalar.\n all(node.outputs[0].broadcastable)):\n if nnested:\n all_code = [(\"\", \"\")] * (nnested - 1) + [(\"\", code)] + [\"\"]\n else:\n all_code = [code]\n if len(all_code) == 1:\n # No loops\n task_decl = \"\".join([\n \"%s& %s_i = *%s_iter;\\n\" % (dtype, name, name)\n for name, dtype in izip(inames + list(real_onames),\n idtypes + list(real_odtypes))])\n\n preloops = {}\n for i, (loop_order, dtype) in enumerate(zip(loop_orders, dtypes)):\n for j, index in enumerate(loop_order):\n if index != 'x':\n preloops.setdefault(j, \"\")\n preloops[j] += (\"%%(lv%(i)s)s_iter = (%(dtype)s*)(PyArray_DATA(%%(lv%(i)s)s));\\n\" % locals()) % sub\n break\n else: # all broadcastable\n preloops.setdefault(0, \"\")\n preloops[0] += (\"%%(lv%(i)s)s_iter = (%(dtype)s*)(PyArray_DATA(%%(lv%(i)s)s));\\n\" % locals()) % sub\n\n init_array = preloops.get(0, \" \")\n loop = \"\"\"\n {\n %(defines)s\n %(init_array)s\n %(task_decl)s\n %(task_code)s\n %(undefs)s\n }\n \"\"\" % locals()\n else:\n loop = cgen.make_loop(\n loop_orders=loop_orders,\n dtypes=dtypes,\n loop_tasks=all_code,\n sub=sub, openmp=self.openmp)\n else:\n loop = cgen.make_reordered_loop(\n init_loop_orders=loop_orders,\n olv_index=olv_index,\n dtypes=dtypes,\n inner_task=code,\n sub=sub, openmp=self.openmp)\n\n # If all inputs and outputs are contiguous\n # and the scalar op define optimized code for that case\n # use it! The scalar_op need to check the broadcast flag himself.\n if (all([o.ndim >= 1 for o in node.outputs]) and\n # Don't use the contig code for broadcasted scalar.\n not all(node.outputs[0].broadcastable)):\n contig = None\n try:\n contig = self.scalar_op.c_code_contiguous(\n node,\n nodename + '_scalar_contig_',\n _inames,\n onames,\n sub)\n except theano.gof.utils.MethodNotDefined:\n # Try to make one generic version, this will help the\n # compiler to vectorize the code as their won't be as\n # many ptr and the stride will be hard coded.\n if all([io.broadcastable == node.outputs[0].broadcastable or\n all(io.broadcastable)\n for io in node.inputs + node.outputs]):\n z = onames[0]\n contig = \"\"\"\n // All output have the same size\n npy_intp n = PyArray_SIZE(%(z)s);\n \"\"\" % locals()\n index = \"\"\n for x, var in zip(inames + onames,\n inputs + node.outputs):\n if not all(var.broadcastable):\n contig += \"\"\"\n dtype_%(x)s * %(x)s_ptr = (dtype_%(x)s*) PyArray_DATA(%(x)s);\n \"\"\" % locals()\n index += \"\"\"\n dtype_%(x)s& %(x)s_i = %(x)s_ptr[i];\n \"\"\" % locals()\n else:\n contig += \"\"\"\n dtype_%(x)s& %(x)s_i = ((dtype_%(x)s*) PyArray_DATA(%(x)s))[0];\n \"\"\" % locals()\n if self.openmp:\n contig += \"\"\"#pragma omp parallel for if(n>=%d)\"\"\" % (config.openmp_elemwise_minsize)\n contig += \"\"\"\n for(int i=0; i<n; i++){\n %(index)s\n %(task_code)s;\n }\n \"\"\" % locals()\n if contig is not None:\n z = list(zip(inames + onames, inputs + node.outputs))\n cond1 = ' && '.join([\"PyArray_ISCONTIGUOUS(%s)\" % arr\n for arr, var in z\n if not all(var.broadcastable)])\n cond2 = ' && '.join([\"PyArray_ISFORTRAN(%s)\" % arr\n for arr, var in z\n if not all(var.broadcastable)])\n loop = \"\"\"\n if((%(cond1)s) || (%(cond2)s)){\n %(contig)s\n }else{\n %(loop)s\n }\n \"\"\" % locals()\n return decl, checks, alloc, loop\n\n def c_code(self, node, nodename, inames, onames, sub):\n if (any(i.dtype == 'float16' for i in node.inputs) or\n any(o.dtype == 'float16' for o in node.outputs) or\n # This is for Composite\n getattr(self.scalar_op, 'inner_float16', False)):\n # Disable C code for float16 vars\n super(Elemwise, self).c_code(node, nodename, inames, onames, sub)\n code = \"\\n\".join(self._c_all(node, nodename, inames, onames, sub))\n return code\n\n def c_headers(self):\n return ['<vector>', '<algorithm>']\n\n def c_support_code(self):\n return self.scalar_op.c_support_code()\n\n def c_support_code_apply(self, node, nodename):\n support_code = self.scalar_op.c_support_code_apply(node, nodename +\n '_scalar_')\n return support_code\n\n def c_code_cache_version_apply(self, node):\n version = [12] # the version corresponding to the c code in this Op\n\n # now we insert versions for the ops on which we depend...\n scalar_node = Apply(\n self.scalar_op,\n [get_scalar_type(dtype=input.type.dtype).make_variable()\n for input in node.inputs],\n [get_scalar_type(dtype=output.type.dtype).make_variable()\n for output in node.outputs])\n version.append(self.scalar_op.c_code_cache_version_apply(scalar_node))\n for i in node.inputs + node.outputs:\n version.append(get_scalar_type(dtype=i.type.dtype).c_code_cache_version())\n version.append(('openmp', self.openmp))\n if all(version):\n return tuple(version)\n else:\n return ()\n\n def python_constant_folding(self, node):\n \"\"\"\n Return True if we do not want to compile c code\n when doing constant folding of this node.\n \"\"\"\n return node.outputs[0].ndim == 0\n\ntheano.compile.debugmode.default_make_thunk.append(\n get_unbound_function(Elemwise.make_thunk))\n\n# def elemwise_to_scal(fgraph):\n# TODO: why is this commented out? should it be removed?\n# it has needed maintenance despite being commented\n# mapping = {}\n# inputs = []\n# outputs = []\n# for node in fgraph.io_toposort():\n# if not isinstance(node.op, Elemwise):\n# raise TypeError('All ops in the graph must be Elemwise.')\n\n\n################\n# CAReduce #\n################\n\nclass CAReduce(Op):\n \"\"\"\n CAReduce = Commutative Associative Reduce\n Reduces a scalar operation along the specified axis(es).\n (The scalar op should be both commutative and assocative)\n\n The output will have the same shape as the input minus the reduced\n dimensions. It will contain the variable of accumulating all values\n over the reduced dimensions using the specified scalar op.\n\n Parameters\n ----------\n scalar_op\n A binary scalar op with only one output.\n It must be commutative and associative.\n axis\n - The dimension along which we want to reduce\n - List of dimensions that we want to reduce\n - If None, all dimensions are reduced\n\n Examples\n --------\n CAReduce(add) -> sum (ie, acts like the numpy sum operation)\n CAReduce(mul) -> product\n CAReduce(maximum) -> max\n CAReduce(minimum) -> min\n CAReduce(or_) -> any # not lazy\n CAReduce(and_) -> all # not lazy\n CAReduce(xor) -> a bit at 1 tell that there was an odd number of bit at\n that position that where 1.\n 0 it was an even number ...\n\n In order to (eventually) optimize memory usage patterns,\n L{CAReduce} makes zero guarantees on the order in which it\n iterates over the dimensions and the elements of the\n array(s). Therefore, to ensure consistent variables, the scalar\n operation represented by the reduction must be both commutative\n and associative (eg add, multiply, maximum, binary or/and/xor - but not\n subtract, divide or power).\n\n \"\"\"\n\n def __init__(self, scalar_op, axis=None):\n if scalar_op.nin not in [-1, 2] or scalar_op.nout != 1:\n raise NotImplementedError((\n \"CAReduce only supports binary functions with a single \"\n \"output.\"))\n self.scalar_op = scalar_op\n\n if axis is None:\n self.axis = axis\n # There is a bug in numpy that results in isinstance(x, int) returning\n # False for numpy integers.\n # See <http://projects.scipy.org/numpy/ticket/2235>.\n elif isinstance(axis, (int, numpy.integer)):\n self.axis = (axis,)\n elif isinstance(axis, numpy.ndarray) and axis.ndim == 0:\n self.axis = (int(axis),)\n else:\n self.axis = list(set(int(a) for a in axis))\n self.axis.sort()\n self.axis = tuple(self.axis)\n\n self.set_ufunc(scalar_op)\n\n def set_ufunc(self, scalar_op):\n # This is probably a speed up of the implementation\n if isinstance(scalar_op, theano.scalar.basic.Add):\n self.ufunc = numpy.add\n elif isinstance(scalar_op, theano.scalar.basic.Mul):\n self.ufunc = numpy.multiply\n elif isinstance(scalar_op, theano.scalar.basic.Maximum):\n self.ufunc = numpy.maximum\n elif isinstance(scalar_op, theano.scalar.basic.Minimum):\n self.ufunc = numpy.minimum\n elif isinstance(scalar_op, theano.scalar.basic.AND):\n self.ufunc = numpy.bitwise_and\n elif isinstance(scalar_op, theano.scalar.basic.OR):\n self.ufunc = numpy.bitwise_or\n elif isinstance(scalar_op, theano.scalar.basic.XOR):\n self.ufunc = numpy.bitwise_xor\n else:\n self.ufunc = numpy.frompyfunc(scalar_op.impl, 2, 1)\n\n def _output_dtype(self, input_dtype):\n return input_dtype\n\n def make_node(self, input):\n input = as_tensor_variable(input)\n\n if self.axis is not None:\n for axis in self.axis:\n if (axis >= input.type.ndim or\n (axis < 0 and abs(axis) > input.type.ndim)):\n raise ValueError((\n 'Not enough dimensions on %s to reduce on axis %s'\n % (input, axis)))\n input = as_tensor_variable(input)\n axis = self.axis\n if axis is None:\n axis = list(range(len(input.type.broadcastable)))\n if any(a < 0 for a in axis):\n axis2 = []\n for a in self.axis:\n if a < 0:\n axis2.append(a + input.type.ndim)\n else:\n axis2.append(a)\n assert len(axis) == len(axis2)\n axis = tuple(axis2)\n # We can't call self.__class__() as there is class that\n # inherit from CAReduce that don't have the same signature\n op = copy(self)\n op.set_ufunc(op.scalar_op)\n op.axis = axis\n else:\n op = self\n broadcastable = [x for i, x in enumerate(input.type.broadcastable)\n if i not in axis]\n output = TensorType(dtype=self._output_dtype(input.type.dtype),\n broadcastable=broadcastable)()\n return Apply(op, [input], [output])\n\n def __getstate__(self):\n d = copy(self.__dict__)\n d.pop('ufunc', None)\n return d\n\n def __setstate__(self, d):\n self.__dict__.update(d)\n self.set_ufunc(self.scalar_op)\n\n def __eq__(self, other):\n return (type(self) == type(other) and\n self.scalar_op == other.scalar_op and\n self.axis == other.axis)\n\n def __hash__(self):\n if self.axis is None:\n return hash(self.scalar_op)\n else:\n return hash(self.scalar_op) ^ hash(tuple(self.axis))\n\n def __str__(self):\n if self.axis is not None:\n return \"Reduce{%s}{%s}\" % (\n self.scalar_op, \", \".join(str(x) for x in self.axis))\n else:\n return \"Reduce{%s}\" % self.scalar_op\n\n def perform(self, node, inp, out):\n input, = inp\n output, = out\n axis = self.axis\n if axis is None:\n axis = list(range(input.ndim))\n variable = input\n to_reduce = reversed(sorted(axis))\n\n if hasattr(self, 'acc_dtype') and self.acc_dtype is not None:\n acc_dtype = self.acc_dtype\n else:\n acc_dtype = node.outputs[0].type.dtype\n\n if to_reduce:\n for dimension in to_reduce:\n # If it's a zero-size array, use scalar_op.identity\n # if available\n if variable.shape[dimension] == 0:\n if hasattr(self.scalar_op, 'identity'):\n # Compute the shape of the output\n v_shape = list(variable.shape)\n del v_shape[dimension]\n variable = numpy.empty(tuple(v_shape),\n dtype=acc_dtype)\n variable.fill(self.scalar_op.identity)\n else:\n raise ValueError((\n \"Input (%s) has zero-size on axis %s, but \"\n \"self.scalar_op (%s) has no attribute 'identity'\"\n % (variable, dimension, self.scalar_op)))\n else:\n # Numpy 1.6 has a bug where you sometimes have to specify\n # \"dtype='object'\" in reduce for it to work, if the ufunc\n # was built with \"frompyfunc\". We need to find out if we\n # are in one of these cases (only \"object\" is supported in\n # the output).\n if ((self.ufunc.ntypes == 1) and\n (self.ufunc.types[0][-1] == 'O')):\n variable = self.ufunc.reduce(variable, dimension,\n dtype='object')\n else:\n variable = self.ufunc.reduce(variable, dimension,\n dtype=acc_dtype)\n\n variable = numpy.asarray(variable)\n if numpy.may_share_memory(variable, input):\n # perhaps numpy is clever for reductions of size 1?\n # We don't want this.\n variable = variable.copy()\n output[0] = theano._asarray(variable,\n dtype=node.outputs[0].type.dtype)\n else:\n # Force a copy\n output[0] = numpy.array(variable, copy=True,\n dtype=node.outputs[0].type.dtype)\n\n def infer_shape(self, node, shapes):\n ishape, = shapes\n axis = self.axis\n if axis is None:\n return (),\n return [ishape[i]\n for (i, b) in enumerate(node.inputs[0].type.broadcastable)\n if i not in axis],\n\n def _c_all(self, node, name, inames, onames, sub):\n\n input = node.inputs[0]\n output = node.outputs[0]\n\n iname = inames[0]\n oname = onames[0]\n\n idtype = input.type.dtype_specs()[1]\n odtype = output.type.dtype_specs()[1]\n\n if hasattr(self, 'acc_dtype') and self.acc_dtype is not None:\n if self.acc_dtype == 'float16':\n raise theano.gof.utils.MethodNotDefined(\"no c_code for float16\")\n acc_type = TensorType(\n broadcastable=node.outputs[0].broadcastable,\n dtype=self.acc_dtype)\n adtype = acc_type.dtype_specs()[1]\n else:\n adtype = odtype\n\n axis = self.axis\n if axis is None:\n axis = list(range(len(input.type.broadcastable)))\n\n if len(axis) == 0:\n # The acc_dtype is never a downcast compared to the input dtype\n # So we just need a cast to the output dtype.\n var = theano.tensor.cast(input, node.outputs[0].dtype)\n if var is input:\n var = Elemwise(scalar.identity)(input)\n assert var.dtype == node.outputs[0].dtype\n return var.owner.op._c_all(var.owner, name, inames, onames, sub)\n\n order1 = [i for i in xrange(input.type.ndim) if i not in axis]\n order = order1 + list(axis)\n\n nnested = len(order1)\n\n sub = dict(sub)\n for i, (input, iname) in enumerate(izip(node.inputs, inames)):\n sub['lv%i' % i] = iname\n\n decl = \"\"\n if adtype != odtype:\n # Create an accumulator variable different from the output\n aname = \"acc\"\n decl = acc_type.c_declare(aname, sub)\n decl += acc_type.c_init(aname, sub)\n else:\n # the output is the accumulator variable\n aname = oname\n\n decl += cgen.make_declare([order], [idtype], sub)\n checks = cgen.make_checks([order], [idtype], sub)\n\n alloc = \"\"\n i += 1\n sub['lv%i' % i] = oname\n sub['olv'] = oname\n\n # Allocate output buffer\n alloc += cgen.make_declare(\n [list(range(nnested)) + ['x'] * len(axis)],\n [odtype], dict(sub, lv0=oname))\n alloc += cgen.make_alloc([order1], odtype, sub)\n alloc += cgen.make_checks(\n [list(range(nnested)) + ['x'] * len(axis)],\n [odtype], dict(sub, lv0=oname))\n\n if adtype != odtype:\n # Allocate accumulation buffer\n sub['lv%i' % i] = aname\n sub['olv'] = aname\n\n alloc += cgen.make_declare(\n [list(range(nnested)) + ['x'] * len(axis)],\n [adtype], dict(sub, lv0=aname))\n alloc += cgen.make_alloc([order1], adtype, sub)\n alloc += cgen.make_checks(\n [list(range(nnested)) + ['x'] * len(axis)],\n [adtype], dict(sub, lv0=aname))\n\n if hasattr(self.scalar_op, 'identity'):\n identity = self.scalar_op.identity\n elif self.scalar_op in [scalar.maximum, scalar.minimum]:\n if self.scalar_op == scalar.maximum:\n scal_name = 'maximum'\n if input.type.dtype in [\"float32\", \"float64\"]:\n identity = \"-__builtin_inf()\"\n elif input.type.dtype.startswith(\"uint\"):\n # numpy1.5.1 don't define NPY_MIN_UINT*\n identity = \"0\"\n else:\n identity = \"NPY_MIN_\" + str(input.type.dtype).upper()\n if self.scalar_op == scalar.minimum:\n scal_name = 'minimum'\n if input.type.dtype in [\"float32\", \"float64\"]:\n identity = \"__builtin_inf()\"\n else:\n identity = \"NPY_MAX_\" + str(input.type.dtype).upper()\n fail = sub[\"fail\"]\n pattern = [0] * len(node.inputs[0].broadcastable)\n axis = self.axis\n if axis is None:\n axis = list(range(len(pattern)))\n for i in axis:\n pattern[i] = 1\n pattern_ = str(pattern)[1:-1]\n decl += \"\"\"int tosum[]={%(pattern_)s};\"\"\" % locals()\n alloc += \"\"\"\nfor(int i=0;i<PyArray_NDIM(%(iname)s);i++){\n if(PyArray_DIMS(%(iname)s)[i]==0 && tosum[i]){\n PyErr_Format(PyExc_ValueError,\n \"Input of CAReduce{%(scal_name)s} has zero-size on axis %%d\",i);\n %(fail)s;\n }\n}\n \"\"\" % locals()\n else:\n raise TypeError(\n \"The CAReduce.scalar_op must have an identity field.\")\n\n task0_decl = (\"%(dtype)s& %(name)s_i = *%(name)s_iter;\\n\"\n \"%(name)s_i = %(identity)s;\"\n % dict(dtype=adtype, name=aname, identity=identity))\n\n task1_decl = (\"%(dtype)s& %(name)s_i = *%(name)s_iter;\\n\"\n % dict(dtype=idtype, name=inames[0]))\n\n task1_code = self.scalar_op.c_code(\n Apply(self.scalar_op,\n [get_scalar_type(dtype=input.type.dtype).make_variable()\n for input in (node.inputs * 2)],\n [get_scalar_type(dtype=output.type.dtype).make_variable()\n for input in node.outputs]),\n None,\n [\"%s_i\" % aname, \"%s_i\" % inames[0]],\n [\"%s_i\" % aname],\n sub)\n code1 = \"\"\"\n {\n %(task1_decl)s\n %(task1_code)s\n }\n \"\"\" % locals()\n\n if node.inputs[0].type.ndim:\n if len(axis) == 1:\n all_code = [(\"\", \"\")] * nnested + [(task0_decl, code1), \"\"]\n else:\n all_code = ([(\"\", \"\")] * nnested +\n [(task0_decl, \"\")] +\n [(\"\", \"\")] * (len(axis) - 2) +\n [(\"\", code1), \"\"])\n else:\n all_code = [task0_decl + code1]\n loop = cgen.make_loop_careduce(\n [order, list(range(nnested)) + ['x'] * len(axis)],\n [idtype, adtype], all_code, sub)\n\n end = \"\"\n if adtype != odtype:\n end = \"\"\"\n PyArray_CopyInto(%(oname)s, %(aname)s);\n \"\"\" % dict(oname=oname, aname=aname)\n end += acc_type.c_cleanup(aname, sub)\n\n return decl, checks, alloc, loop, end\n\n def c_code(self, node, name, inames, onames, sub):\n code = \"\\n\".join(self._c_all(node, name, inames, onames, sub))\n return code\n\n def c_headers(self):\n # Sometimes, Elemwise's c_code is returned, so we need its headers\n return ['<vector>', '<algorithm>']\n\n def c_code_cache_version_apply(self, node):\n version = (6,) # the version corresponding to the c code in this Op\n\n # now we insert versions for the ops on which we depend...\n scalar_node = Apply(\n self.scalar_op,\n [get_scalar_type(dtype=input.type.dtype).make_variable()\n for input in node.inputs],\n [get_scalar_type(dtype=output.type.dtype).make_variable()\n for output in node.outputs])\n version.append(self.scalar_op.c_code_cache_version_apply(scalar_node))\n for i in node.inputs + node.outputs:\n version.append(get_scalar_type(dtype=i.type.dtype).c_code_cache_version())\n if all(version):\n return tuple(version)\n else:\n return ()\n\n\nclass All(CAReduce):\n \"\"\" Applies `bitwise and` to all the values of a tensor along the\n specified axis(es).\n\n Equivalent to CAReduce(scalar.and_, axis=axis).\n\n \"\"\"\n\n def __init__(self, axis=None):\n CAReduce.__init__(self, scalar.and_, axis)\n\n def _output_dtype(self, idtype):\n return \"int8\"\n\n def __str__(self):\n if self.axis is None:\n return \"All\"\n else:\n return \"All{%s}\" % \", \".join(map(str, self.axis))\n\n def make_node(self, input):\n input = as_tensor_variable(input)\n if input.dtype not in [\"int8\", \"uint8\"]:\n input = theano.tensor.neq(input, 0)\n ret = super(All, self).make_node(input)\n return ret\n\n def grad(self, inp, grads):\n x, = inp\n return [x.zeros_like(theano.config.floatX)]\n\n\nclass Any(CAReduce):\n \"\"\" Applies `bitwise or` to all the values of a tensor along the\n specified axis(es).\n\n Equivalent to CAReduce(scalar.or_, axis=axis).\n\n \"\"\"\n\n def __init__(self, axis=None):\n CAReduce.__init__(self, scalar.or_, axis)\n\n def _output_dtype(self, idtype):\n return \"int8\"\n\n def __str__(self):\n if self.axis is None:\n return \"Any\"\n else:\n return \"Any{%s}\" % \", \".join(map(str, self.axis))\n\n def make_node(self, input):\n input = as_tensor_variable(input)\n if input.dtype not in [\"int8\", \"uint8\"]:\n input = theano.tensor.neq(input, 0)\n ret = super(Any, self).make_node(input)\n return ret\n\n def grad(self, inp, grads):\n x, = inp\n return [x.zeros_like(theano.config.floatX)]\n\n\nclass CAReduceDtype(CAReduce):\n \"\"\"\n Reduces a scalar operation along the specified axis(es).\n\n This subclass of CAReduce accepts an additional \"dtype\" parameter,\n that specifies which dtype the output should be.\n\n It also accepts an optional \"acc_dtype\", which specify the dtype that\n will be used for the accumulation.\n\n So, the accumulation will be done into a tensor of dtype \"acc_dtype\",\n then it will be casted into \"dtype\" and returned.\n\n If no dtype is provided, one will be inferred so as not to lose\n too much precision.\n\n Parameters\n ----------\n scalar_op\n A binary scalar op with only one output.\n It must be commutative and associative.\n\n axis\n - the dimension along which we want to reduce\n - list of dimensions that we want to reduce\n - if None, all dimensions are reduced\n\n dtype\n The dtype of the returned tensor. If None, then we use the default\n dtype which is the same as the input tensor's dtype except when:\n - the input dtype is a signed integer of precision < 64 bit, in\n which case we use int64\n - the input dtype is an unsigned integer of precision < 64 bit, in\n which case we use uint64\n This default dtype does _not_ depend on the value of \"acc_dtype\".\n This behavior is similar in spirit to that of numpy (except numpy\n uses the default machine integer while we always use 64 bit\n integers to avoid platform-dependent behavior).\n\n acc_dtype\n The dtype of the internal accumulator.\n If None (default), we use the dtype in the list below,\n or the input dtype if its precision is higher:\n - for int dtypes, we use at least int64;\n - for uint dtypes, we use at least uint64;\n - for float dtypes, we use at least float64;\n - for complex dtypes, we use at least complex128.\n\n \"\"\"\n\n def __init__(self, scalar_op, axis=None, dtype=None, acc_dtype=None):\n CAReduce.__init__(self, scalar_op, axis=axis)\n self.dtype = dtype\n self.acc_dtype = acc_dtype\n\n def __eq__(self, other):\n return (CAReduce.__eq__(self, other) and\n self.dtype == other.dtype and\n self.acc_dtype == other.acc_dtype)\n\n def __hash__(self):\n return CAReduce.__hash__(self) ^ hash((self.dtype, self.acc_dtype))\n\n def __setstate__(self, d):\n super(CAReduceDtype, self).__setstate__(d)\n if not hasattr(self, \"dtype\"):\n # This is needed as old pickled will crash otherwise.\n # We need to keep the old dtype behavior as the op\n # could be in an apply node with a specified dtype.\n self.dtype = \"OLD\"\n\n if not hasattr(self, \"acc_dtype\"):\n # acc_dtype is not used by any external Op, so we do not\n # need to keep the previous behaviour here.\n self.acc_dtype = None\n\n def _output_dtype(self, idtype):\n dtype = self.dtype\n if dtype == \"OLD\":\n return dict(\n int8='int32',\n int16='int32',\n int32='int64',\n uint8='uint32',\n uint16='uint32',\n uint32='uint64').get(idtype, idtype)\n if dtype is None:\n # If input has a discrete dtype, upcast it to 64\n return dict(\n int8='int64',\n int16='int64',\n int32='int64',\n uint8='uint64',\n uint16='uint64',\n uint32='uint64').get(idtype, idtype)\n else:\n # The important is that the accumulator dtype does not\n # lose precision. Then, the result can be downcasted.\n return dtype\n\n def _acc_dtype(self, idtype):\n acc_dtype = self.acc_dtype\n if acc_dtype is None:\n return dict(\n int8='int64',\n int16='int64',\n int32='int64',\n uint8='uint64',\n uint16='uint64',\n uint32='uint64',\n float16='float32',\n float32='float64',\n complex64='complex128').get(idtype, idtype)\n elif (acc_dtype in theano.tensor.continuous_dtypes and\n idtype in theano.tensor.discrete_dtypes):\n # Specifying a continuous accumulator for discrete input is OK\n return acc_dtype\n else:\n # The conversion has to be considered an upcast.\n upcasted_dtype = scalar.upcast(idtype, acc_dtype)\n if acc_dtype != upcasted_dtype:\n raise TypeError(\n 'Cannot build %s node with input dtype %s '\n 'and acc_dtype %s, as precision would be lost. '\n 'To correct this error, you can:\\n'\n ' - not specify acc_dtype, or\\n'\n ' - use an acc_dtype at least as precise as %s.\\n'\n ' - specify \"dtype\" instead of \"acc_dtype\", so '\n 'the reduction will be precise, but the result will '\n 'be casted into \"dtype\" at the end.\\n'\n 'If you are expecting the precision loss, you can '\n 'use tensor.cast(..., dtype=\"%s\"), on your input.'\n % (self, idtype, acc_dtype, upcasted_dtype, acc_dtype))\n return acc_dtype\n\n def make_node(self, input):\n # We need to redefine make_node so that, if self.dtype is None,\n # we can infer what dtype should be, and create a node from an Op\n # of the appropriate dtype.\n input = as_tensor_variable(input)\n dtype = self._output_dtype(input.dtype)\n acc_dtype = self._acc_dtype(input.dtype)\n assert dtype is not None\n assert acc_dtype is not None\n if dtype == self.dtype and acc_dtype == self.acc_dtype:\n # Don't build another instance\n op = self\n else:\n op = copy(self)\n op.set_ufunc(self.scalar_op)\n op.dtype = dtype\n op.acc_dtype = acc_dtype\n\n assert op.acc_dtype is not None\n return CAReduce.make_node(op, input)\n\n def __str__(self):\n name = self.__class__.__name__\n if self.__class__.__name__ == \"CAReduceDtype\":\n name = \"ReduceDtype{%s}\" % self.scalar_op,\n axis = \"\"\n if self.axis is not None:\n axis = \", \".join(str(x) for x in self.axis)\n axis = \"axis=[%s], \" % axis\n return \"%s{%sacc_dtype=%s}\" % (\n name,\n axis,\n str(self.acc_dtype)\n )\n\n\nclass Sum(CAReduceDtype):\n \"\"\"\n Sums all the values of a tensor along the specified axis(es).\n\n Equivalent to CAReduceDtype(scalar.add, axis=axis, dtype=dtype),\n with the difference that this defines the gradient of sum wrt its\n tensor input.\n\n Parameters\n ----------\n axis\n Axis(es) along which the tensor should be summed\n (use None to sum over all axes, and a list or tuple to sum along more\n than one axis).\n\n dtype\n The dtype of the internal accumulator and returned\n tensor. If None, then we use the default dtype which is the same as the\n input tensor's dtype except when:\n - the input dtype is a signed integer of precision < 64 bit, in\n which case we use int64\n - the input dtype is an unsigned integer of precision < 64 bit, in\n which case we use uint64\n This value does not depend on the value of \"acc_dtype\".\n\n acc_dtype\n The dtype of the internal accumulator.\n If None (default), we use the dtype in the list below,\n or the input dtype if its precision is higher:\n - for int dtypes, we use at least int64;\n - for uint dtypes, we use at least uint64;\n - for float dtypes, we use at least float64;\n - for complex dtypes, we use at least complex128.\n\n \"\"\"\n\n def __init__(self, axis=None, dtype=None, acc_dtype=None):\n CAReduceDtype.__init__(self, scalar.add, axis=axis,\n dtype=dtype, acc_dtype=acc_dtype)\n\n def grad(self, inp, grads):\n x, = inp\n\n out = self(*inp)\n\n if out.dtype.find('int') != -1:\n return [x.zeros_like(dtype=theano.config.floatX)]\n\n gz, = grads\n gz = as_tensor_variable(gz)\n axis = self.axis\n if axis is None:\n axis = list(range(x.type.ndim))\n if axis == ():\n return gz,\n new_dims = []\n i = 0\n for j, _ in enumerate(x.type.broadcastable):\n if j in axis:\n new_dims.append('x')\n else:\n new_dims.append(i)\n i += 1\n ds_op = DimShuffle(gz.type.broadcastable, new_dims)\n gx = Elemwise(scalar.second)(x, ds_op(gz))\n return [gx]\n\n def R_op(self, inputs, eval_points):\n # There is just one element in inputs and eval_points, the axis are\n # part of self\n if None in eval_points:\n return [None]\n return self(*eval_points, **dict(return_list=True))\n\n\nclass Prod(CAReduceDtype):\n \"\"\"\n Multiplies all the values of a tensor along the specified axis(es).\n\n Equivalent to CAReduce(scalar.prod, axis = axis), with the\n difference that this defines the gradient of prod wrt its tensor\n input.\n\n \"\"\"\n\n def __init__(self, axis=None, dtype=None, acc_dtype=None,\n no_zeros_in_input=False):\n CAReduceDtype.__init__(self, scalar.mul, axis=axis,\n dtype=dtype, acc_dtype=acc_dtype)\n self.no_zeros_in_input = no_zeros_in_input\n\n def __setstate__(self, dct):\n super(Prod, self).__setstate__(dct)\n # Add default value to be able to reload old pickled objects.\n if 'no_zeros_in_input' not in dct:\n self.no_zeros_in_input = False\n\n def __eq__(self, other):\n return (CAReduceDtype.__eq__(self, other) and\n self.no_zeros_in_input == other.no_zeros_in_input)\n\n def __hash__(self):\n return (CAReduceDtype.__hash__(self) ^\n hash(self.no_zeros_in_input))\n\n def grad(self, inp, grads):\n \"\"\"\n The grad of this Op could be very easy, if it is was not for the case\n where zeros are present in a given \"group\" (ie. elements reduced\n together to form the product).\n\n If no zeros are found in the elements of the product, then the\n partial derivative of the product relative to one of the elements\n (one of the inputs) is simply the product of the other elements.\n That's easy to see from the chain rule.\n\n Now the trick (with no zeros) is to take the overall product, then\n for every original element, the partial derivative is given by\n this product divided by the element itself (which equals the product\n of the other terms). This is easy to do by broadcasting the original\n product.\n\n (Note that we also need to broadcast-multiply by the\n \"incoming gradient\", ie. the gradient of the cost relative to the\n output/product).\n\n -----\n\n With zeros, things get more complicated. For a given group, we have 3\n cases:\n * No zeros in the group. Use previous trick.\n * If only one zero is present, then the gradient for that element is\n non-zero, but is zero for all others.\n * If more than one zero is present, then all the derivatives are zero.\n\n For the last two cases (with 1 or more zeros), we can't use the\n division trick, as this gives divisions by 0.\n\n Implementing that case-by-case logic is not as trivial, so a bunch of\n hacks are piled down here to do it. Notably, for the \"only one zero\"\n case, there's a special Op that computes the product of the elements\n in the group, minus the zero (see ProdWithoutZero). The trick is then\n to use the division trick for groups with no zero, to use the\n ProdWithoutZeros op where there's only one zero, and to output a\n derivative of zero for any element part of a group with more than\n one zero.\n\n I do this by first counting the number of zeros in each group (see\n the \"T.eq()\" bits), then taking this or that behavior (see T.switch)\n based on the result of this count.\n\n \"\"\"\n prod_in, = inp\n gz, = grads\n\n out = self(*inp)\n\n if (out.dtype in discrete_dtypes or\n self.acc_dtype in discrete_dtypes):\n # There is an int conversion in the way\n return [prod_in.zeros_like(dtype=theano.config.floatX)]\n\n # Prepare the broadcasting that is used everywhere to broadcast\n # over the original groups (ie. broadcast over the elements of a given\n # product)\n gz = as_tensor_variable(gz)\n axis = self.axis\n if axis is None:\n axis = list(range(prod_in.type.ndim))\n if axis == ():\n return gz,\n new_dims = []\n i = 0\n for j, _ in enumerate(prod_in.type.broadcastable):\n if j in axis:\n new_dims.append('x')\n else:\n new_dims.append(i)\n i += 1\n\n # result of the product, broadcastable over groups\n prod_out = self(prod_in).dimshuffle(new_dims)\n # incoming gradient, broadcastable over groups\n gz = gz.dimshuffle(new_dims)\n\n # division trick if we don't have zeros. This will contain\n # NaNs to be eliminated in the T.switch if we do have zeros.\n grad_case_without_zeros = (gz * prod_out / prod_in)\n\n if self.no_zeros_in_input:\n # this handles inputs with zeros, but only certain input shapes\n return [grad_case_without_zeros]\n else:\n T = theano.tensor\n\n where_zeros = T.eq(prod_in, 0.0)\n sum_where_zeros = T.sum(where_zeros, axis=self.axis)\n groups_with_single_zero = T.eq(sum_where_zeros, 1).dimshuffle(\n new_dims)\n # tensor with 0 everywhere except for those places where\n # a 0 part of a group with a single zero was to be found\n where_single_zero = groups_with_single_zero * where_zeros\n # further optimization to avoid computing ProdWithoutZeros\n # if the incoming gradient is 0\n where_gz_not_zero = T.neq(gz, 0.0)\n # only take ProdWithoutZeros for the groups with single zeros\n # with non-null incoming gradient\n where_to_take_prod_without_zeros = (\n groups_with_single_zero * where_gz_not_zero)\n # preprocess the original input so that we set 0 everywhere\n # except for groups that contain a single zero, to avoid computing\n # multiplications on other groups\n prod_without_zeros_in = where_to_take_prod_without_zeros * prod_in\n # TODO: put lazy switch here, if it'd work\n # this is pretty efficient already (no multiplication if 0), but\n # it'd be even better if we had a lazy if per element\n prod_without_zeros = ProdWithoutZeros(axis=self.axis)(\n prod_without_zeros_in)\n prod_without_zeros = prod_without_zeros.dimshuffle(new_dims)\n\n groups_without_zeros = T.eq(sum_where_zeros, 0).dimshuffle(\n new_dims)\n\n final_grad = T.switch(\n groups_without_zeros,\n grad_case_without_zeros,\n T.switch(where_single_zero, prod_without_zeros, 0.0) * gz)\n\n return [final_grad]\n\n def c_code_cache_version(self):\n return (1,)\n\n\nclass MulWithoutZeros(scalar.BinaryScalarOp):\n # \"identity\" here is zero, as in Reduce we don't want to start\n # with reducing (1, something_else): this leads to the erronous\n # case where a vector of zeros is reduced by binary reductions\n # of (1, 0), which always ends up as 1 (ie. the result for\n # the c version, for the product of [0,0,0], is 1.0)\n\n identity = 0.\n commutative = True\n associative = True\n\n def impl(self, x, y):\n if x == 0:\n return y\n if y == 0:\n return x\n return x * y\n\n def c_code(self, node, name, inp, out, sub):\n x, y = inp\n z, = out\n return ((\"%(z)s = ((%(x)s == 0) ? (%(y)s) : \" +\n \"((%(y)s == 0) ? (%(x)s) : ((%(y)s)*(%(x)s))) );\")\n % locals())\n\n def c_code_cache_version(self):\n return (1,)\n\nmul_without_zeros = MulWithoutZeros(scalar.upcast_out, name='mul_without_zeros')\n\n\nclass ProdWithoutZeros(CAReduceDtype):\n def __init__(self, axis=None, dtype=None, acc_dtype=None):\n CAReduceDtype.__init__(self, mul_without_zeros, axis=axis,\n dtype=dtype, acc_dtype=acc_dtype)\n\n def grad(self, inp, grads):\n a, = inp\n a_grad = theano.gradient.grad_not_implemented(\n self, 0, a,\n \"2nd derivatives of `product(a)` is not currently supported.\"\n \"If `a` is guarenteed to contains no zeros, use \"\n \"`product(a, no_zeros_in_input=True)`.\")\n return [a_grad]\n",
"import numpy\n\nimport theano\nfrom theano import scalar, gof\nfrom theano.tests.unittest_tools import SkipTest, assert_allclose\n\nfrom theano.tensor.tests import test_elemwise\n\nfrom .config import mode_with_gpu, test_ctx_name\nfrom .test_basic_ops import rand_gpuarray\nfrom ..elemwise import (GpuElemwise, GpuDimShuffle,\n GpuCAReduceCuda, GpuCAReduceCPY)\nfrom ..type import GpuArrayType, get_context\n\nfrom pygpu import ndgpuarray as gpuarray\n\n\n# This is acutally a test for GpuElemwise\nclass test_gpu_Broadcast(test_elemwise.test_Broadcast):\n op = GpuElemwise\n type = GpuArrayType\n cop = GpuElemwise\n ctype = GpuArrayType\n # The order is important\n linkers = [gof.PerformLinker, gof.CLinker]\n\n def setUp(self):\n if get_context(test_ctx_name).kind != 'cuda':\n self.linkers = [gof.PerformLinker]\n\n def rand_val(self, shp):\n return rand_gpuarray(*shp, **dict(cls=gpuarray))\n\n def rand_cval(self, shp):\n return rand_gpuarray(*shp, **dict(cls=gpuarray))\n\n def test_c(self):\n if get_context(test_ctx_name).kind != 'cuda':\n raise SkipTest(\"Cuda specific tests\")\n super(test_gpu_Broadcast, self).test_c()\n\n def test_c_inplace(self):\n if get_context(test_ctx_name).kind != 'cuda':\n raise SkipTest(\"Cuda specific tests\")\n super(test_gpu_Broadcast, self).test_c_inplace()\n\n\ndef test_elemwise_pow():\n # Test that GpuElemwise(pow) can compile with any combination of integer\n # or float input dtype.\n if get_context(test_ctx_name).kind != 'cuda':\n raise SkipTest(\"Cuda specific tests\")\n\n dtypes = [\"uint8\", \"uint16\", \"uint32\", \"uint64\",\n \"int8\", \"int16\", \"int32\", \"int64\",\n \"float16\", \"float32\", \"float64\"]\n\n for dtype_base in dtypes:\n for dtype_exp in dtypes:\n\n # Compile a gpu function with the specified dtypes\n base = theano.tensor.vector(dtype=dtype_base)\n exp = theano.tensor.vector(dtype=dtype_exp)\n output = base ** exp\n f = theano.function([base, exp], output)\n\n # Call the function to make sure the output is valid\n base_val = numpy.random.randint(0, 5, size=10).astype(dtype_base)\n exp_val = numpy.random.randint(0, 3, size=10).astype(dtype_exp)\n\n out = f(base_val, exp_val)\n expected_out = base_val ** exp_val\n assert_allclose(out, expected_out)\n\n\nclass test_GpuDimShuffle(test_elemwise.test_DimShuffle):\n op = GpuDimShuffle\n\n\nclass test_GpuCAReduceCPY(test_elemwise.test_CAReduce):\n dtypes = [\"float32\"]\n bin_dtypes = [\"uint8\", \"int8\"]\n op = GpuCAReduceCPY\n reds = [scalar.add, scalar.mul]\n pre_scalar_op = None\n\n def test_perform(self):\n for dtype in self.dtypes + self.bin_dtypes:\n for op in self.reds:\n self.with_linker(gof.PerformLinker(), op, dtype=dtype,\n pre_scalar_op=self.pre_scalar_op)\n\n def test_perform_nan(self):\n for dtype in self.dtypes:\n if not dtype.startswith('float'):\n continue\n for op in self.reds:\n self.with_linker(gof.PerformLinker(), op, dtype=dtype,\n test_nan=True,\n pre_scalar_op=self.pre_scalar_op)\n\n def test_c(self):\n for dtype in self.dtypes + self.bin_dtypes:\n for op in self.reds:\n self.with_linker(gof.CLinker(), op, dtype=dtype,\n pre_scalar_op=self.pre_scalar_op)\n\n def test_c_nan(self):\n for dtype in self.dtypes:\n if not dtype.startswith('float'):\n continue\n for op in self.reds:\n self.with_linker(gof.CLinker(), op, dtype=dtype,\n test_nan=True,\n pre_scalar_op=self.pre_scalar_op)\n\n def test_infer_shape(self):\n for dtype in self.dtypes:\n super(test_GpuCAReduceCPY, self).test_infer_shape(dtype)\n\n\nclass test_GpuCAReduceCuda(test_GpuCAReduceCPY):\n dtypes = [\"float32\", \"int64\"]\n bin_dtypes = [\"uint8\", \"int8\"]\n\n cases = [((5, 6), None),\n ((5, 6), (0, 1)),\n ((5, 6), (0, )),\n ((5, 6), (1, )),\n ((5, 6), (-1, )),\n ((5, 6), (-2, )),\n # ((5, 6), ()), #reduce on no axis(copy) isn't implemented\n # ((2, 3, 4, 5), (0, 1, 3)), mask 1101 isn't implemented\n # ((2, 3, 4, 5), (-2, -3)), mask 0110 isn't implemented\n ((5, 0), None),\n ((5, 0), (0, )),\n ((5, 0), (1, )),\n # ((5, 0), ()), reduce on no axis isn't implemented\n # ((), None), reduce on no axis isn't implemented\n # ((), ()) reduce on no axis isn't implemented\n\n # Test all GPU cases implemented\n ((1, 0), (1,)),\n ((0, 1), (1,)),\n ((0, 0), (1,)),\n ((0, 0, 0), (1, 2)),\n ((0, 0, 0, 0), (1, 2, 3)),\n ((2, 1), (1,)),\n ((1, 2), (1,)),\n ((100, 3, 1300), [1]),\n ((0,), [0]), ((5,), [0]),\n ((0, 0), [0, 1]), ((1, 0), [0, 1]), ((5, 4), [0, 1]), ((33, 31), [0, 1]), ((5, 4), [1]), ((5, 4), [0]), # need something bigger then 32 for some opt test.\n ((5, 4, 3), [0]), ((5, 4, 3), [1]), ((5, 4, 3), [0, 1]), ((5, 4, 3), [2]), ((5, 4, 3), [1, 2]), ((5, 4, 3), [0, 1, 2]),\n ((0, 0, 0, 0), [0, 1, 2, 3]),\n ((5, 4, 3, 20), [2, 3]), ((5, 4, 3, 2), [0, 1, 2, 3]), ((5, 4, 3, 2), [0, 2, 3]), ((5, 4, 3, 2), [1, 2, 3]),\n\n # test shape bigger then 4096 on each dimension to make sure that we work correctly when we don't have enough thread/block in each dimensions\n ((4100, 3), [0]), ((3, 4101), [0]), # 10\n ((1024, 33), [0]), ((33, 1024), [0]), # 10\n ((1025, 33), [0]), ((33, 1025), [0]), # 10\n\n ((4100, 3), [1]), ((3, 4101), [1]), # 01\n ((1024, 33), [1]), ((33, 1024), [1]), # 01\n ((1025, 33), [1]), ((33, 1025), [1]), # 01\n\n ((4100, 3), [0, 1]), ((3, 4101), [0, 1]), # 11\n ((1024, 33), [0, 1]), ((33, 1024), [0, 1]), # 01\n ((1025, 33), [0, 1]), ((33, 1025), [0, 1]), # 01\n\n ((4100, 4, 3), [0]), ((5, 4100, 3), [0]), ((5, 4, 4100), [0]), ((3, 65536, 1), [0]), # 100\n ((4100, 4, 3), [1]), ((5, 4100, 3), [1]), ((5, 4, 4100), [1]), # 010\n ((4100, 4, 3), [2]), ((5, 4100, 3), [2]), ((5, 4, 4100), [2]), # 001\n ((4100, 4, 3), [0, 1]), ((5, 4100, 3), [0, 1]), ((5, 4, 4100), [0, 1]), # 110\n ((4100, 4, 3), [1, 2]), ((5, 4100, 3), [1, 2]), ((5, 4, 4100), [1, 2]), # 011\n # ((4100,4,3),[0,2]),((5,4100,3),[0,2]),((5,4,4100),[0,2]),#101 ##not implemented\n ((4100, 4, 3), [0, 1, 2]), ((5, 4100, 3), [0, 1, 2]), ((5, 4, 4100), [0, 1, 2]), # 111\n ((65, 4, 3), [0, 1, 2]), ((5, 65, 3), [0, 1, 2]), ((5, 4, 65), [0, 1, 2]), # 111\n\n ((4100, 4, 3, 2), [2, 3]), ((4, 4100, 3, 2), [2, 3]), ((4, 3, 4100, 2), [2, 3]), ((4, 3, 2, 4100), [2, 3]), # 0011\n ((4100, 4, 3, 2), [1, 3]), ((4, 4100, 3, 2), [1, 3]), ((4, 3, 4100, 2), [1, 3]), ((4, 3, 2, 4100), [1, 3]), # 0101\n ((4100, 4, 3, 2), [0, 2, 3]), ((4, 4100, 3, 2), [0, 2, 3]), ((4, 3, 4100, 2), [0, 2, 3]), # ((4,3,2,4100),[0,2,3]),#1011\n ((4100, 4, 3, 2), [1, 2, 3]), ((4, 4100, 3, 2), [1, 2, 3]), ((4, 3, 4100, 2), [1, 2, 3]), ((4, 3, 2, 4100), [1, 2, 3]), # 0111\n ((65, 4, 3, 2), [1, 2, 3]), ((4, 65, 3, 2), [1, 2, 3]), ((4, 3, 65, 2), [1, 2, 3]), ((4, 3, 2, 65), [1, 2, 3]), # 0111\n ((4100, 2, 3, 4), [0, 1, 2, 3]), ((2, 4100, 3, 4), [0, 1, 2, 3]), ((2, 3, 4100, 4), [0, 1, 2, 3]), ((2, 3, 4, 4100), [0, 1, 2, 3]), ((128, 1, 2, 3), [0, 1, 2, 3]), # 1111\n\n # test pattern implemented by reshape\n # Skip them as this test the op directly, not the optimization with reshape\n # ((4100,4,3,2),[0]),((4,4100,3,2),[0]),((4,3,4100,2),[0]),((4,3,2,4100),[0]),#1000\n # ((4100,4,3,2),[1]),((4,4100,3,2),[1]),((4,3,4100,2),[1]),((4,3,2,4100),[1]),#0100\n # ((4100,4,3,2),[2]),((4,4100,3,2),[2]),((4,3,4100,2),[2]),((4,3,2,4100),[2]),#0010\n # ((4100,4,3,2),[3]),((4,4100,3,2),[3]),((4,3,4100,2),[3]),((4,3,2,4100),[3]),#0001\n # ((1100,2,3,4,5),[0,1,2,3,4]),((2,1100,3,4,5),[0,1,2,3,4]),((2,3,1100,4,5),[0,1,2,3,4]),((2,3,4,1100,5),[0,1,2,3,4]),((2,3,4,5,1100),[0,1,2,3,4]),#11111\n # ((5,4,3,10,11),[1,2]),\n ]\n op = GpuCAReduceCuda\n reds = [scalar.add, scalar.mul,\n scalar.maximum, scalar.minimum]\n pre_scalar_op = None\n\n def test_perform(self):\n return\n\n def test_perform_nan(self):\n return\n\n def setUp(self):\n super(test_GpuCAReduceCuda, self).setUp()\n if get_context(test_ctx_name).kind != 'cuda':\n raise SkipTest(\"Cuda specific tests\")\n\n\nclass T_gpureduce_dtype(test_elemwise.T_reduce_dtype):\n mode = mode_with_gpu.excluding('local_cut_useless_reduce')\n op = GpuCAReduceCuda\n # Currently we don't support reduction on 0 axis\n axes = [None, 0, 1, 1, [0], [1], [0, 1]]\n # We don't support complex dtype\n dtypes = ['int8', 'int16', 'int32', 'int64',\n 'uint8', 'uint16', 'uint32', 'uint64',\n 'float32', 'float64']\n\n def setUp(self):\n if get_context(test_ctx_name).kind != 'cuda':\n raise SkipTest(\"Cuda specific tests\")\n\n\ndef speed_reduce10():\n import numpy\n import theano\n data = numpy.random.rand(1000, 1000).astype(\"float32\")\n m = theano.tensor.fmatrix()\n f = theano.function([m], [m.sum(axis=0), m.T.sum(axis=0)],\n mode=mode_with_gpu)\n f(data)\n"
] |
[
[
"numpy.may_share_memory",
"numpy.asarray",
"numpy.frompyfunc",
"numpy.dtype",
"numpy.copy",
"numpy.sctype2char",
"numpy.array"
],
[
"numpy.random.rand",
"numpy.random.randint"
]
] |
slee01/homework
|
[
"144ad6311d28531c250dd610d331d6e01f8e17c2"
] |
[
"hw1/behavior_cloning.py"
] |
[
"import os\nimport pickle\nimport tensorflow as tf\nimport numpy as np\nimport tf_util\nimport gym\nimport load_policy\nimport random\nimport math\n\nimport argparse\n\ndef main(Session):\n parser = argparse.ArgumentParser()\n parser.add_argument('expert_data_file', type=str)\n parser.add_argument('envname', type=str)\n parser.add_argument('--epochs', type=int, default=30)\n parser.add_argument('--max_timesteps', type=int)\n parser.add_argument('--batch_size', type=int, default=64)\n parser.add_argument('--dagger_iter', type=int, default=20)\n\n parser.add_argument('--num_rollouts', type=int, default=5,\n help='Number of expert roll outs')\n\n args = parser.parse_args()\n env = gym.make(args.envname)\n\n with open(args.expert_data_file, 'rb') as f:\n expert_data = pickle.loads(f.read())\n print(expert_data.keys())\n\n expert_obs = expert_data['observations']\n expert_act = expert_data['actions']\n expert_act = np.squeeze(expert_act)\n\n print(\"get expert demonstrations\", len(expert_obs), \" obs / \", len(expert_act), \" act\")\n print(\"obs_shape: \", expert_obs.shape)\n print(\"act_shape: \", expert_act.shape)\n\n BC = BehaviorCloning(Session ,env)\n\n Session.run(tf.global_variables_initializer())\n max_steps = args.max_timesteps or env.spec.timestep_limit\n\n for j in range(args.dagger_iter):\n\n for i in range(args.epochs):\n for k in range(int(math.ceil(len(expert_obs)/args.batch_size))):\n loss = BC.train(expert_obs[args.batch_size*k:args.batch_size*(k+1)], expert_act[args.batch_size*k:args.batch_size*(k+1)])\n print(\"data.len: \", len(expert_obs), \"dagger iter: \", j, \" epochs: \", i , \" mn_iter: \", k, \" loss: \", loss)\n\n returns = []\n observations = []\n actions = []\n\n for i in range(args.num_rollouts):\n print('iter', i)\n obs = env.reset()\n done = False\n totalr = 0.\n steps = 0\n while not done:\n action = BC.step(obs[None, :])\n observations.append(obs)\n actions.append(action)\n obs, r, done, _ = env.step(action)\n totalr += r\n steps += 1\n\n # env.render()\n if steps % 100 == 0: print(\"%i/%i\" % (steps, max_steps))\n if steps >= max_steps:\n break\n returns.append(totalr)\n\n print('returns', returns)\n print('mean return', np.mean(returns))\n print('std of return', np.std(returns))\n print('obs.shape', np.array(observations).shape)\n print('act.shape', np.array(actions).shape)\n\n observations = np.squeeze(np.array(observations))\n actions = np.squeeze(np.array(actions))\n\n expert_obs = np.concatenate((expert_obs, observations))\n expert_act = np.concatenate((expert_act, actions))\n\n\n\nclass BehaviorCloning(object):\n def __init__(self, Session, env):\n self.state_size= env.observation_space.shape[0]\n self.action_size = env.action_space.shape[0]\n self.hidden_size = 128\n self.build_ph()\n self.model = self.build_model('bc')\n self.loss, self.optimizer = self.build_optimizer()\n\n self.sess = Session\n self.saver = tf.train.Saver()\n\n def build_ph(self):\n self.expert_obs = tf.placeholder(tf.float32, shape=[None, self.state_size])\n self.expert_act = tf.placeholder(tf.float32, shape=[None, self.action_size])\n\n def build_model(self, name):\n with tf.variable_scope(name) as scope:\n\n w1 = tf.get_variable(\"w1\", shape=[self.state_size, self.hidden_size], initializer=tf.contrib.layers.xavier_initializer())\n b1 = tf.get_variable(\"b1\", shape=[self.hidden_size], initializer=tf.contrib.layers.xavier_initializer())\n l1 = tf.nn.relu(tf.matmul(self.expert_obs, w1) + b1)\n\n w2 = tf.get_variable(\"w2\", shape=[self.hidden_size, self.hidden_size], initializer=tf.contrib.layers.xavier_initializer())\n b2 = tf.get_variable(\"b2\", shape=[self.hidden_size], initializer=tf.contrib.layers.xavier_initializer())\n l2 = tf.nn.relu(tf.matmul(l1, w2) + b2)\n\n w3 = tf.get_variable(\"w2\", shape=[self.hidden_size, self.hidden_size], initializer=tf.contrib.layers.xavier_initializer())\n b3 = tf.get_variable(\"b2\", shape=[self.hidden_size], initializer=tf.contrib.layers.xavier_initializer())\n l3 = tf.nn.relu(tf.matmul(l2, w3) + b3)\n\n w4 = tf.get_variable(\"w_steer\", shape=[self.hidden_size, self.action_size], initializer=tf.random_uniform_initializer(minval=-1e-4, maxval=1e-4))\n b4 = tf.get_variable(\"b_steer\", shape=[self.action_size], initializer=tf.random_uniform_initializer(minval=-1e-4, maxval=1e-4))\n policy = tf.nn.tanh(tf.matmul(l3, w4) + b4)\n\n scope.reuse_variables()\n\n return policy\n\n def build_optimizer(self):\n loss = 0.5 * tf.reduce_mean(tf.square(self.model - self.expert_act))\n optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)\n\n return loss, optimizer\n\n def train(self, expert_obs, expert_act):\n loss, _ = self.sess.run([self.loss, self.optimizer], feed_dict={self.expert_obs: expert_obs, self.expert_act: expert_act})\n\n return loss\n\n def save_model(self):\n checkpoint_dir = 'trained_model'\n if not os.path.exists(checkpoint_dir):\n os.mkdir(checkpoint_dir)\n self.saver.save(self.sess, os.path.join(checkpoint_dir, 'trained_model'))\n\n def load_model(self):\n checkpoint_dir = 'trained_model'\n self.saver.restore(self.sess, os.path.join(checkpoint_dir, 'trained_model'))\n\n def step(self, obs):\n return self.sess.run(self.model, feed_dict={self.expert_obs: obs})\n\n def test(self):\n pass\n\n\nif __name__ == \"__main__\":\n # config = tf.ConfigProto()\n # If you use a GPU, uncomment\n # os.environ[\"CUDA_VISIBLE_DEVICES\"] = '0'\n # config.log_device_placement = False\n # config.gpu_options.allow_growth = True\n # config.gpu_options.per_process_gpu_memory_fraction = 0.6\n\n with tf.Session() as sess:\n # trainOptions = Options()\n main(Session=sess) # , config=trainOptions)"
] |
[
[
"tensorflow.matmul",
"tensorflow.random_uniform_initializer",
"numpy.squeeze",
"tensorflow.placeholder",
"numpy.concatenate",
"tensorflow.global_variables_initializer",
"numpy.std",
"numpy.mean",
"tensorflow.variable_scope",
"tensorflow.Session",
"tensorflow.square",
"tensorflow.train.Saver",
"tensorflow.train.AdamOptimizer",
"tensorflow.contrib.layers.xavier_initializer",
"numpy.array"
]
] |
abuccts/tutel
|
[
"09bbdc379f1122b69daa1f0eab5f8a4d63f2389d"
] |
[
"tutel/parted/backend/torch/executor.py"
] |
[
"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nimport os, sys\nimport time\nimport json\nimport torch\n\nfrom tutel import system_init\nfrom tutel.impls import communicate as C\n\ndef warp_bwd_allreduce(data, is_param):\n if is_param:\n fusable_params.add(id(data))\n return C.PrimBwdAllreduce.apply(parallel_env.global_group, data)\n return C.PrimBwdAllreduce.apply(parallel_env.model_group, data)\n\ndef sharded_randn(shape, dim, dtype, requires_grad=False, is_param=False, device=None):\n if device is None:\n device = parallel_env.local_device\n torch.manual_seed(1)\n complete_tensor = torch.tensor(torch.randn(shape, dtype=dtype, device='cpu').numpy(), device=device, requires_grad=requires_grad)\n if dim >= 0:\n result = torch.chunk(complete_tensor, chunks=parallel_env.model_size, dim=dim)[parallel_env.model_rank].contiguous()\n elif dim == -2:\n numel = complete_tensor.numel()\n assert numel % parallel_env.model_size == 0\n result = complete_tensor.view(parallel_env.model_size, -1)[parallel_env.model_rank].contiguous()\n else:\n result = complete_tensor.contiguous()\n if is_param:\n result = torch.nn.Parameter(result * 1e-3)\n result.is_param = True\n if dim == -2:\n result._full_shape = shape\n result.is_param = True\n result.dim_state = dim\n return result\n\ndef init_session(group_size, group_count=1, device_type='cuda'):\n global parallel_env, fusable_params\n parallel_env = system_init.init_data_model_parallel(group_count=group_count, backend='nccl' if device_type == 'cuda' else 'gloo')\n fusable_params = set()\n assert parallel_env.model_size == group_size, f\"This codegen is designed for distributed parallelism = {group_size}, while current session only activates {parallel_env.model_size} device.\\n\\nPlease retry with command: mpiexec --allow-run-as-root -host localhost -x MASTER_ADDR=localhost -x LOCAL_SIZE={group_size} {sys.executable} -m tutel.launcher.run {sys.executable} {' '.join(sys.argv)}\"\n\ndef model_executor(module, is_training=True):\n name = module.compute_name\n model = module().to(parallel_env.local_device)\n inputs = module.synthetic_inputs()\n output = model(**inputs)\n params = model.parameters()\n\n verbose = int(os.environ.get('VERBOSE', '0'))\n\n if verbose:\n sys.stderr.write('[%d] %g %g .. %g (%s)\\n' % (parallel_env.model_rank, output.flatten()[0], output.flatten()[1], output.flatten()[-1], output.shape))\n\n if is_training:\n torch.manual_seed(1)\n label = torch.LongTensor(output.size(0)).random_(1).to(output.device)\n if params:\n optimizer = torch.optim.SGD(params, lr=1e-5)\n else:\n optimizer = model_executor\n optimizer.zero_grad = optimizer.step = lambda *x: None\n\n def next_step():\n if parallel_env.group_count > 1:\n dist.barrier()\n if output.is_cuda:\n torch.cuda.synchronize(parallel_env.local_device)\n t_start = time.time()\n\n if is_training:\n optimizer.zero_grad()\n result = model(**inputs).contiguous()\n result = torch.nn.functional.log_softmax(result.view(result.size(0), -1), dim=1)\n result = torch.nn.functional.nll_loss(result, label)\n if parallel_env.model_rank == 0 and verbose:\n sys.stderr.write(f' Loss = {result} ({output.shape}, {label.shape})\\n')\n result.backward(retain_graph=True)\n if parallel_env.group_count > 1:\n for p in params:\n if id(p) not in fusable_params:\n simple_all_reduce(p.grad, parallel_env.data_group)\n optimizer.step()\n else:\n result = model(**inputs).contiguous()\n result = result.view(-1)[0]\n\n if parallel_env.group_count > 1:\n dist.barrier()\n if output.is_cuda:\n torch.cuda.synchronize(parallel_env.local_device)\n t_stop = time.time()\n\n step_time = t_stop - t_start\n if parallel_env.model_rank == 0 and verbose:\n sys.stderr.write('Result(is_training=%s) = %g, cost = %s\\n' % (is_training, result, step_time))\n return step_time\n\n for i in range(5):\n next_step()\n average_step_time = sum([next_step() for _ in range(5)]) / 5\n if parallel_env.model_rank == 0:\n sys.stderr.write(' [%s] digest = %g .., time = %g\\n' % (name, output.flatten()[0], average_step_time))\n result = json.dumps({'name': name, 'step_time': average_step_time})\n if 'CONFIG_STORE_PATH' in os.environ:\n with open(os.environ['CONFIG_STORE_PATH'], 'w') as fp:\n fp.write(result)\n print(result)\n"
] |
[
[
"torch.cuda.synchronize",
"torch.nn.Parameter",
"torch.nn.functional.nll_loss",
"torch.manual_seed",
"torch.randn",
"torch.optim.SGD",
"torch.chunk"
]
] |
nicoloval/iterative_reconstruction
|
[
"09fc440b75e8af1e8c52973b520309b6bdcc8142"
] |
[
"tests/test_exp_knn.py"
] |
[
"'''Test function iterative_solver \n'''\nimport sys\nsys.path.append('../')\nfrom sample import iterative_solver # where the functions are\nimport sample\nimport numpy as np\nfrom numba import jit\nimport unittest # test tool\nimport networkx as nx\nimport scipy.sparse\n\n\nclass MyTest(unittest.TestCase):\n\n def setUp(self):\n pass\n \n #TODO: add more heterogenous sol\n \"\"\"\n def test_array_sym(self):\n A = np.array([[0, 1, 1, 0, 1],\n [1, 0, 1, 1, 0],\n [1, 1, 0, 0, 0],\n [0, 1, 0, 0, 1],\n [1, 0, 0, 1, 0]])\n \n A_nx = nx.convert_matrix.from_numpy_array(A)\n k = sample.out_degree(A)\n\n knn_sample = sample.nearest_neighbour_degree_undirected(A)\n # knn_nx = nx.degree_assortativity_coefficient(A_nx)\n knn_nx = nx.k_nearest_neighbors(A_nx)\n\n\n self.assertTrue(knn_sample == knn_nx)\n\n\n def test_sparse_sym(self):\n A = np.array([[0, 1, 1, 0, 1],\n [1, 0, 1, 1, 0],\n [1, 1, 0, 0, 0],\n [0, 1, 0, 0, 1],\n [1, 0, 0, 1, 0]])\n \n A_nx = nx.convert_matrix.from_numpy_array(A)\n\n # sparse matrix conversion\n A = scipy.sparse.csr_matrix(A)\n\n rows, cols = A.nonzero()\n print(rows, cols)\n A[cols,rows] = A[rows, cols]\n\n\n k = sample.out_degree(A)\n\n knn_sample = sample.nearest_neighbour_degree_undirected(A)\n # knn_nx = nx.degree_assortativity_coefficient(A_nx)\n knn_nx = nx.k_nearest_neighbors(A_nx)\n\n # debug check\n\n self.assertTrue(knn_sample == knn_nx)\n\n\n\n\n def test_array_inin(self):\n A = np.array([[0, 0, 1, 0, 1],\n [1, 0, 0, 1, 0],\n [1, 1, 0, 0, 0],\n [0, 1, 1, 0, 1],\n [1, 0, 0, 1, 0]])\n \n A_nx = nx.convert_matrix.from_numpy_array(A, create_using=nx.DiGraph())\n k = sample.in_degree(A)\n\n knn_sample = sample.nearest_neighbour_degree_inin(A)\n # knn_nx = nx.degree_assortativity_coefficient(A_nx)\n knn_nx = nx.k_nearest_neighbors(A_nx, source='in', target='in')\n\n\n self.assertTrue(knn_sample == knn_nx)\n \"\"\"\n\n\n def test_array_outout(self):\n \n sol = np.array([1, 1, 1, 1, 1, 1]) \n knn_sample = sample.expected_dcm_nearest_neighbour_degree_outout(sol)\n # knn_nx = nx.degree_assortativity_coefficient(A_nx)\n knn_byme = {1:1.0} \n\n # debug check\n \"\"\"\n print('\\n')\n print(knn_sample)\n print(knn_byme)\n \"\"\"\n\n self.assertTrue(knn_sample == knn_byme)\n\n\n def test_array_inin(self):\n \n sol = np.array([1, 1, 1, 1, 1, 1]) \n knn_sample = sample.expected_dcm_nearest_neighbour_degree_inin(sol)\n # knn_nx = nx.degree_assortativity_coefficient(A_nx)\n knn_byme = {1:1.0} \n\n # debug check\n \"\"\"\n print('\\n')\n print(knn_sample)\n print(knn_byme)\n \"\"\"\n\n self.assertTrue(knn_sample == knn_byme)\n\n\nif __name__ == '__main__':\n unittest.main()\n\n"
] |
[
[
"numpy.array"
]
] |
simontorres/specidentify
|
[
"7c148b9b8c4770b77bdeba3b1d67ffecb5607b0d"
] |
[
"specreduce/models/RSSModel.py"
] |
[
"\"\"\"RSSmodel is a class that describes the optical arm of the Robert Stobie\nSpectrograph. This model inherents from Spectragraph. The RSS is currently\ndescribed by the grating, grating angle, and camera angle. All other components\nare fixed.\n\n20090913 SMC First version\n20120325 SMC -Update to include deviations in the as built spectrograph in the grating angle\n -include the most up to date chip geometry\n20120511 SMC -Updated to inherit directly from Spectrograph\n -Included get_wavelength\n\nLimitations:\n-Set the geometry of the CCDs using the current geometry file instead of the\n default given here\n\n\"\"\"\n\nimport numpy as np\n\nfrom PySpectrograph.Spectrograph import Spectrograph, Grating, Optics, CCD, Detector, Slit\n\n\nclass RSSError(Exception):\n pass\n\n\nclass RSSModel (Spectrograph):\n\n \"\"\"A model describing the RSS spectrograph\"\"\"\n\n def __init__(self, grating_name='None', gratang=45, camang=45, slit=1.0,\n xbin=2, ybin=2, xpos=-0.2666, ypos=0.0117, wavelength=None):\n\n # set up the parts of the grating\n self.grating_name = grating_name\n self.slitang = slit\n\n # set the telescope\n self.set_telescope('RSS')\n\n # set the collimator\n self.set_collimator('RSS')\n\n # set the camera\n self.set_camera('RSS', wavelength=wavelength)\n\n # set the detector\n self.set_detector('RSS', xbin=xbin, ybin=ybin, xpos=xpos, ypos=ypos)\n\n # set up the grating\n self.set_grating(self.grating_name)\n\n # set up the slit\n self.set_slit(self.slitang)\n\n # set up the grating angle\n self.gratang = gratang\n self.camang = camang\n\n def alpha(self, da=0.23):\n \"\"\"Return the value of alpha for the spectrograph\"\"\"\n return self.gratang + da\n\n def beta(self, mF=4.2e-5, db=0.00):\n \"\"\"Return the value of beta for the spectrograph\n\n Beta_o=(1+fA)*(camang)-gratang+beta_o\n \"\"\"\n return (1 + mF) * self.camang - self.alpha() + db\n\n def focallength(self, focallength=328.0, wavelength=None):\n \"\"\"The camera focal lenght set oaccording to the following\n Wavelength should be provided in angstroms\n\n \"\"\"\n if wavelength is None:\n return focallength\n\n L = (wavelength - 4000.0) / 1000.0\n return 327.66 + -0.1861 * L + 0.5061 * L ** 2 + -0.2100 * L ** 3 + 0.0365 * L ** 4 + -0.0023 * L ** 5\n\n def get_wavelength(self, xarr, gamma=0.0):\n \"\"\"For a given spectrograph configuration, return the wavelength coordinate\n associated with a pixel coordinate.\n\n xarr: 1-D Array of pixel coordinates\n gamma: Value of gamma for the row being analyzed\n\n returns an array of wavelengths in mm\n \"\"\"\n d = self.detector.xbin * self.detector.pix_size * (xarr - self.detector.get_xpixcenter())\n dbeta = -np.degrees(np.arctan(d / self.camera.focallength))\n return self.calc_wavelength(self.alpha(), -self.beta() + dbeta, gamma=gamma)\n\n def set_telescope(self, name='RSS'):\n if name == 'RSS':\n self.telescope = Optics(name=name, focallength=46200.0)\n elif name == 'SALT':\n self.telescope = Optics(name=name, focallength=46200.0)\n else:\n raise RSSError('%s is not a supported Telescope' % name)\n\n def set_collimator(self, name='RSS', focallength=630.0):\n if name == 'RSS':\n self.collimator = Optics(name=name, focallength=focallength)\n else:\n raise RSSError('%s is not a supported collimator' % name)\n\n def set_camera(self, name='RSS', wavelength=None):\n if name == 'RSS':\n self.camera = Optics(name=name, focallength=self.focallength())\n else:\n raise RSSError('%s is not a supported camera' % name)\n\n def set_detector(self, name='RSS', geom=None, xbin=2, ybin=2, xpos=0, ypos=0):\n if name == 'RSS':\n if geom:\n pass\n else:\n # version 1\n #ccd1=Spectrograph.CCD(name='CCD1', xpix=2032, ypix=4102, pix_size=0.015, xpos=-32.19, ypos=0)\n # updated on 20120325\n ccd1 = CCD(name='CCD1', xpix=2032, ypix=4102, pix_size=0.015, xpos=-32.40, ypos=0.0486)\n ccd2 = CCD(name='CCD1', xpix=2032, ypix=4102, pix_size=0.015, xpos=0, ypos=0)\n ccd3 = CCD(name='CCD1', xpix=2032, ypix=4102, pix_size=0.015, xpos=32.218, ypos=0.0196)\n self.detector = Detector(name=name, ccd=[ccd1, ccd2, ccd3], xbin=xbin, ybin=ybin,\n xpos=xpos, ypos=ypos, plate_scale=0.224)\n else:\n raise RSSError('%s is not a supported detector' % name)\n\n def set_grating(self, name=None):\n if name == 'PG0300':\n self.grating = Grating(name='PG0300', spacing=300)\n elif name == 'PG0900':\n self.grating = Grating(name='PG0900', spacing=903.20)\n elif name == 'PG1300':\n self.grating = Grating(name='PG1300', spacing=1301.20)\n elif name == 'PG1800':\n self.grating = Grating(name='PG1800', spacing=1801.65)\n elif name == 'PG2300':\n self.grating = Grating(name='PG2300', spacing=2302.15)\n elif name == 'PG3000':\n self.grating = Grating(name='PG3000', spacing=2999.98)\n else:\n raise RSSError('%s is not a supported RSS grating' % name)\n\n def set_slit(self, slitang=1.0):\n self.slit = Slit(name='LongSlit', phi=slitang)\n self.slit.width = self.slit.calc_width(self.telescope.focallength)\n"
] |
[
[
"numpy.arctan"
]
] |
google/joint_vae
|
[
"984f456d1a38c6b27e23433aef241dea56f53384"
] |
[
"datasets/mnist_attributes/eval.py"
] |
[
"#\n# Copyright 2017 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Evaluates a multi-attribute classification model on MNIST with attributes dataset.\n\nSee the README.md file for compilation and running instructions.\n\"\"\"\n\nimport math\n\n\n\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim\n\nimport dataset_provider\n\nfrom .. import label_map\nfrom .. import multi_attribute_net\n\napp = tf.app\nflags = tf.flags\n\nFLAGS = tf.app.flags.FLAGS\n\nflags.DEFINE_integer('batch_size', 128, 'The number of images in each batch.')\n\nflags.DEFINE_string('split_type', 'iid',\n 'compositional: Train/val/test on a compositional split.'\n 'iid: Train/val/test on an IID split.')\n\n# Loading same JSON file for both 'iid'/'compositional'.\nflags.DEFINE_string(\n 'label_map_json',\n '${PWD}/data/mnist_with_attributes/label_map_iid.json',\n 'A json file storing a list tuple of (attribute keys (str), label maps for'\n ' each attribute (dict)).')\n\nflags.DEFINE_boolean('grayscale', True,\n 'Indicates whether the input image is grayscale or color')\n\nflags.DEFINE_string('preprocess_options', 'binarize',\n 'Whether use binarized images or centered '\n 'images.')\n\nflags.DEFINE_string('master', 'local',\n 'BNS name of the TensorFlow master to use.')\n\nflags.DEFINE_string('checkpoint_dir', '/tmp/deepmind_shapes_with_labels/',\n 'Directory where the model was written to.')\n\nflags.DEFINE_string('eval_dir', '/tmp/deepmind_shapes_with_labels/',\n 'Directory where the results are saved to.')\n\nflags.DEFINE_integer('eval_interval_secs', 60,\n 'The frequency, in seconds, with which evaluation is run.')\n\nflags.DEFINE_string('split_name', 'val',\n \"\"\"Either 'train' or 'val' or 'test'.\"\"\")\n\n\ndef main(_):\n g = tf.Graph()\n with g.as_default():\n images, gt_labels_list, _, num_samples, num_classes_per_attribute = (\n dataset_provider.provide_data(\n FLAGS.split_name,\n FLAGS.batch_size,\n split_type=FLAGS.split_type,\n preprocess_options=FLAGS.preprocess_options,\n grayscale=FLAGS.grayscale))\n\n # Load a label map with attributes and corresponding labels.\n attribute_label_map = label_map.LabelMap(FLAGS.label_map_json)\n\n assert attribute_label_map.count_labels == num_classes_per_attribute, (\n 'Please check your label_map_file, to make sure it corresponds to the'\n ' dataset being loaded.')\n\n # Define the model:\n logits_list = multi_attribute_net.conv_multi_attribute_net(\n images,\n num_classes_per_attribute=num_classes_per_attribute,\n attribute_names=attribute_label_map.attributes,\n is_training=False)\n\n predictions_list = [tf.argmax(logits, 1) for logits in logits_list]\n\n # Define the metrics:\n metrics_to_computation = {}\n for tower_id, sparse_gt_labels_list in enumerate(gt_labels_list):\n metrics_to_computation[\n 'Accuracy_'\n + attribute_label_map.attributes[tower_id]] = slim.metrics.accuracy(\n predictions_list[tower_id], sparse_gt_labels_list)\n names_to_values, names_to_updates = slim.metrics.aggregate_metric_map(\n metrics_to_computation)\n\n # Also compute the average accuracy across all towers, each tower\n # corresponds to an attribute.\n mean_accuracy = tf.zeros((1))\n for name, value in names_to_values.iteritems():\n slim.summaries.add_scalar_summary(\n value, name, prefix='eval', print_summary=True)\n mean_accuracy += value\n\n mean_accuracy /= len(names_to_values.keys())\n slim.summaries.add_scalar_summary(\n mean_accuracy[0], 'Accuracy', prefix='eval', print_summary=True)\n\n # This ensures that we make a single pass over all of the data.\n num_batches = math.ceil(num_samples / float(FLAGS.batch_size))\n\n slim.evaluation.evaluation_loop(\n master=FLAGS.master,\n checkpoint_dir=FLAGS.checkpoint_dir,\n logdir=FLAGS.eval_dir,\n num_evals=num_batches,\n eval_op=names_to_updates.values(),\n eval_interval_secs=FLAGS.eval_interval_secs)\n\n\nif __name__ == '__main__':\n tf.app.run()\n"
] |
[
[
"tensorflow.Graph",
"tensorflow.contrib.slim.summaries.add_scalar_summary",
"tensorflow.zeros",
"tensorflow.contrib.slim.metrics.accuracy",
"tensorflow.argmax",
"tensorflow.contrib.slim.metrics.aggregate_metric_map",
"tensorflow.app.run"
]
] |
rajatmodi62/PytorchWCT
|
[
"58a957c647f976f92cd4324d72cb5b167c6a0cc4"
] |
[
"test_model.py"
] |
[
"import torch\nimport models.vgg_normalised_conv2_1 as vgg_normalised_conv2_1\nmodel = vgg_normalised_conv2_1.vgg_normalised_conv2_1\ncheckpoint= torch.load('models/vgg_normalised_conv2_1.pth')\nmodel.load_state_dict(checkpoint)\nprint(checkpoint.keys())"
] |
[
[
"torch.load"
]
] |
ShashwatNigam99/PointRCNN
|
[
"eee5f90fe4215cff0156e1f8cecf485e18dce1f8"
] |
[
"lib/datasets/kitti_rcnn_dataset.py"
] |
[
"import numpy as np\nimport os\nimport pickle\nimport torch\n\nfrom lib.datasets.kitti_dataset import KittiDataset\nimport lib.utils.kitti_utils as kitti_utils\nimport lib.utils.roipool3d.roipool3d_utils as roipool3d_utils\nfrom lib.config import cfg\n\n\nclass KittiRCNNDataset(KittiDataset):\n def __init__(self, root_dir, npoints=16384, split='train', classes='Multiclass', mode='TRAIN', random_select=True,\n logger=None, rcnn_training_roi_dir=None, rcnn_training_feature_dir=None, rcnn_eval_roi_dir=None,\n rcnn_eval_feature_dir=None, gt_database_dir=None):\n super().__init__(root_dir=root_dir, split=split)\n if classes == 'Car':\n self.classes = ('Background', 'Car')\n aug_scene_root_dir= os.path.join(root_dir, 'KITTI', 'aug_scene')\n elif classes == 'Multiclass':\n self.classes = ('Background', 'Box', 'Shel')\n aug_scene_root_dir = os.path.join(root_dir, 'KITTI', 'aug_scene_box')\n elif classes == 'People':\n self.classes = ('Background', 'Pedestrian', 'Cyclist')\n elif classes == 'Pedestrian':\n self.classes = ('Background', 'Pedestrian')\n aug_scene_root_dir = os.path.join(root_dir, 'KITTI', 'aug_scene_ped')\n elif classes == 'Cyclist':\n self.classes = ('Background', 'Cyclist')\n aug_scene_root_dir = os.path.join(root_dir, 'KITTI', 'aug_scene_cyclist')\n else:\n assert False, \"Invalid classes: %s\" % classes\n\n self.num_class = self.classes.__len__()\n\n self.npoints = npoints\n self.sample_id_list = []\n self.random_select = random_select\n self.logger = logger\n\n if split == 'train_aug':\n self.aug_label_dir = os.path.join(aug_scene_root_dir, 'training', 'aug_label')\n self.aug_pts_dir = os.path.join(aug_scene_root_dir, 'training', 'rectified_data')\n else:\n self.aug_label_dir = os.path.join(aug_scene_root_dir, 'training', 'aug_label')\n self.aug_pts_dir = os.path.join(aug_scene_root_dir, 'training', 'rectified_data')\n\n # for rcnn training\n self.rcnn_training_bbox_list = []\n self.rpn_feature_list = {}\n self.pos_bbox_list = []\n self.neg_bbox_list = []\n self.far_neg_bbox_list = []\n self.rcnn_eval_roi_dir = rcnn_eval_roi_dir\n self.rcnn_eval_feature_dir = rcnn_eval_feature_dir\n self.rcnn_training_roi_dir = rcnn_training_roi_dir\n self.rcnn_training_feature_dir = rcnn_training_feature_dir\n\n self.gt_database = None\n\n if not self.random_select:\n self.logger.warning('random select is False')\n\n assert mode in ['TRAIN', 'EVAL', 'TEST'], 'Invalid mode: %s' % mode\n self.mode = mode\n\n if cfg.RPN.ENABLED:\n # print(\"inside rpn enabled\")\n if gt_database_dir is not None:\n self.gt_database = pickle.load(open(gt_database_dir, 'rb'))\n\n if cfg.GT_AUG_HARD_RATIO > 0:\n easy_list, hard_list = [], []\n for k in range(self.gt_database.__len__()):\n obj = self.gt_database[k]\n if obj['points'].shape[0] > 100:\n easy_list.append(obj)\n else:\n hard_list.append(obj)\n self.gt_database = [easy_list, hard_list]\n logger.info('Loading gt_database(easy(pt_num>100): %d, hard(pt_num<=100): %d) from %s'\n % (len(easy_list), len(hard_list), gt_database_dir))\n else:\n logger.info('Loading gt_database(%d) from %s' % (len(self.gt_database), gt_database_dir))\n\n if mode == 'TRAIN':\n # print(\"inside train mode preprocess training data\")\n self.preprocess_rpn_training_data()\n else:\n self.sample_id_list = [int(sample_id) for sample_id in self.image_idx_list]\n self.logger.info('Load testing samples from %s' % self.imageset_dir)\n self.logger.info('Done: total test samples %d' % len(self.sample_id_list))\n elif cfg.RCNN.ENABLED:\n for idx in range(0, self.num_sample):\n sample_id = int(self.image_idx_list[idx])\n obj_list = self.filtrate_objects(self.get_label(sample_id))\n if len(obj_list) == 0:\n # logger.info('No gt classes: %06d' % sample_id)\n continue\n self.sample_id_list.append(sample_id)\n\n print('Done: filter %s results for rcnn training: %d / %d\\n' %\n (self.mode, len(self.sample_id_list), len(self.image_idx_list)))\n\n def preprocess_rpn_training_data(self):\n \"\"\"\n Discard samples which don't have current classes, which will not be used for training.\n Valid sample_id is stored in self.sample_id_list\n \"\"\"\n self.logger.info('Loading %s samples from %s ...' % (self.mode, self.label_dir))\n # print(\"Num_sample\",self.num_sample)\n for idx in range(0, self.num_sample):\n sample_id = int(self.image_idx_list[idx])\n obj_list = self.filtrate_objects(self.get_label(sample_id))\n if len(obj_list) == 0:\n self.logger.info('No gt classes: %06d' % sample_id)\n continue\n # print(idx)\n self.sample_id_list.append(sample_id)\n\n self.logger.info('Done: filter %s results: %d / %d\\n' % (self.mode, len(self.sample_id_list),\n len(self.image_idx_list)))\n\n def get_label(self, idx):\n if idx < 10000:\n label_file = os.path.join(self.label_dir, '%06d.txt' % idx)\n else:\n label_file = os.path.join(self.aug_label_dir, '%06d.txt' % idx)\n\n assert os.path.exists(label_file)\n return kitti_utils.get_objects_from_label(label_file)\n\n def get_image(self, idx):\n return super().get_image(idx % 10000)\n\n def get_image_shape(self, idx):\n return super().get_image_shape(idx % 10000)\n\n def get_calib(self, idx):\n return super().get_calib(idx % 10000)\n\n def get_road_plane(self, idx):\n return super().get_road_plane(idx % 10000)\n\n @staticmethod\n def get_rpn_features(rpn_feature_dir, idx):\n rpn_feature_file = os.path.join(rpn_feature_dir, '%06d.npy' % idx)\n rpn_xyz_file = os.path.join(rpn_feature_dir, '%06d_xyz.npy' % idx)\n rpn_intensity_file = os.path.join(rpn_feature_dir, '%06d_intensity.npy' % idx)\n if cfg.RCNN.USE_SEG_SCORE:\n rpn_seg_file = os.path.join(rpn_feature_dir, '%06d_rawscore.npy' % idx)\n rpn_seg_score = np.load(rpn_seg_file).reshape(-1)\n rpn_seg_score = torch.sigmoid(torch.from_numpy(rpn_seg_score)).numpy()\n else:\n rpn_seg_file = os.path.join(rpn_feature_dir, '%06d_seg.npy' % idx)\n rpn_seg_score = np.load(rpn_seg_file).reshape(-1)\n return np.load(rpn_xyz_file), np.load(rpn_feature_file), np.load(rpn_intensity_file).reshape(-1), rpn_seg_score\n\n def filtrate_objects(self, obj_list):\n \"\"\"\n Discard objects which are not in self.classes (or its similar classes)\n :param obj_list: list\n :return: list\n \"\"\"\n type_whitelist = self.classes\n if self.mode == 'TRAIN' and cfg.INCLUDE_SIMILAR_TYPE:\n type_whitelist = list(self.classes)\n if 'Car' in self.classes:\n type_whitelist.append('Van')\n if 'Pedestrian' in self.classes: # or 'Cyclist' in self.classes:\n type_whitelist.append('Person_sitting')\n\n valid_obj_list = []\n for obj in obj_list:\n if obj.cls_type not in type_whitelist: # rm Van, 20180928\n continue\n if self.mode == 'TRAIN' and cfg.PC_REDUCE_BY_RANGE and (self.check_pc_range(obj.pos) is False):\n continue\n valid_obj_list.append(obj)\n return valid_obj_list\n\n @staticmethod\n def filtrate_dc_objects(obj_list):\n valid_obj_list = []\n for obj in obj_list:\n if obj.cls_type in ['DontCare']:\n continue\n valid_obj_list.append(obj)\n\n return valid_obj_list\n\n @staticmethod\n def check_pc_range(xyz):\n \"\"\"\n :param xyz: [x, y, z]\n :return:\n \"\"\"\n x_range, y_range, z_range = cfg.PC_AREA_SCOPE\n if (x_range[0] <= xyz[0] <= x_range[1]) and (y_range[0] <= xyz[1] <= y_range[1]) and \\\n (z_range[0] <= xyz[2] <= z_range[1]):\n return True\n return False\n\n @staticmethod\n def get_valid_flag(pts_rect, pts_img, pts_rect_depth, img_shape):\n \"\"\"\n Valid point should be in the image (and in the PC_AREA_SCOPE)\n :param pts_rect:\n :param pts_img:\n :param pts_rect_depth:\n :param img_shape:\n :return:\n \"\"\"\n val_flag_1 = np.logical_and(pts_img[:, 0] >= 0, pts_img[:, 0] < img_shape[1])\n val_flag_2 = np.logical_and(pts_img[:, 1] >= 0, pts_img[:, 1] < img_shape[0])\n val_flag_merge = np.logical_and(val_flag_1, val_flag_2)\n pts_valid_flag = np.logical_and(val_flag_merge, pts_rect_depth >= 0)\n\n if cfg.PC_REDUCE_BY_RANGE:\n x_range, y_range, z_range = cfg.PC_AREA_SCOPE\n pts_x, pts_y, pts_z = pts_rect[:, 0], pts_rect[:, 1], pts_rect[:, 2]\n range_flag = (pts_x >= x_range[0]) & (pts_x <= x_range[1]) \\\n & (pts_y >= y_range[0]) & (pts_y <= y_range[1]) \\\n & (pts_z >= z_range[0]) & (pts_z <= z_range[1])\n pts_valid_flag = pts_valid_flag & range_flag\n return pts_valid_flag\n\n def __len__(self):\n if cfg.RPN.ENABLED:\n return len(self.sample_id_list)\n elif cfg.RCNN.ENABLED:\n if self.mode == 'TRAIN':\n return len(self.sample_id_list)\n else:\n return len(self.image_idx_list)\n else:\n raise NotImplementedError\n\n def __getitem__(self, index):\n if cfg.RPN.ENABLED:\n return self.get_rpn_sample(index)\n elif cfg.RCNN.ENABLED:\n if self.mode == 'TRAIN':\n if cfg.RCNN.ROI_SAMPLE_JIT:\n return self.get_rcnn_sample_jit(index)\n else:\n return self.get_rcnn_training_sample_batch(index)\n else:\n return self.get_proposal_from_file(index)\n else:\n raise NotImplementedError\n\n def get_rpn_sample(self, index):\n sample_id = int(self.sample_id_list[index])\n if sample_id < 10000:\n calib = self.get_calib(sample_id)\n # img = self.get_image(sample_id)\n img_shape = self.get_image_shape(sample_id)\n pts_lidar = self.get_lidar(sample_id)\n\n # get valid point (projected points should be in image)\n pts_rect = calib.lidar_to_rect(pts_lidar[:, 0:3])\n pts_intensity = pts_lidar[:, 3]\n else:\n calib = self.get_calib(sample_id % 10000)\n # img = self.get_image(sample_id % 10000)\n img_shape = self.get_image_shape(sample_id % 10000)\n\n pts_file = os.path.join(self.aug_pts_dir, '%06d.bin' % sample_id)\n assert os.path.exists(pts_file), '%s' % pts_file\n aug_pts = np.fromfile(pts_file, dtype=np.float32).reshape(-1, 4)\n pts_rect, pts_intensity = aug_pts[:, 0:3], aug_pts[:, 3]\n\n pts_img, pts_rect_depth = calib.rect_to_img(pts_rect)\n pts_valid_flag = self.get_valid_flag(pts_rect, pts_img, pts_rect_depth, img_shape)\n\n # pts_rect = pts_rect[pts_valid_flag][:, 0:3]\n pts_rect = pts_rect[:, 0:3]\n # print(len(pts_rect))\n # pts_intensity = pts_intensity[pts_valid_flag]\n\n if cfg.GT_AUG_ENABLED and self.mode == 'TRAIN':\n # all labels for checking overlapping\n all_gt_obj_list = self.filtrate_dc_objects(self.get_label(sample_id))\n all_gt_boxes3d = kitti_utils.objs_to_boxes3d(all_gt_obj_list)\n\n gt_aug_flag = False\n if np.random.rand() < cfg.GT_AUG_APPLY_PROB:\n # augment one scene\n gt_aug_flag, pts_rect, pts_intensity, extra_gt_boxes3d, extra_gt_obj_list = \\\n self.apply_gt_aug_to_one_scene(sample_id, pts_rect, pts_intensity, all_gt_boxes3d)\n\n # generate inputs\n if self.mode == 'TRAIN' or self.random_select:\n if self.npoints < len(pts_rect):\n pts_depth = pts_rect[:, 2]\n pts_near_flag = pts_depth < 40.0\n far_idxs_choice = np.where(pts_near_flag == 0)[0]\n near_idxs = np.where(pts_near_flag == 1)[0]\n near_idxs_choice = np.random.choice(near_idxs, self.npoints - len(far_idxs_choice), replace=False)\n\n choice = np.concatenate((near_idxs_choice, far_idxs_choice), axis=0) \\\n if len(far_idxs_choice) > 0 else near_idxs_choice\n np.random.shuffle(choice)\n else:\n choice = np.arange(0, len(pts_rect), dtype=np.int32)\n if self.npoints > len(pts_rect):\n # print(\"debug\",len(pts_rect))\n extra_choice = np.random.choice(choice, self.npoints - len(pts_rect), replace=False)\n choice = np.concatenate((choice, extra_choice), axis=0)\n np.random.shuffle(choice)\n\n ret_pts_rect = pts_rect[choice, :]\n ret_pts_intensity = pts_intensity[choice] - 0.5 # translate intensity to [-0.5, 0.5]\n else:\n ret_pts_rect = pts_rect\n ret_pts_intensity = pts_intensity - 0.5\n\n pts_features = [ret_pts_intensity.reshape(-1, 1)]\n ret_pts_features = np.concatenate(pts_features, axis=1) if pts_features.__len__() > 1 else pts_features[0]\n\n sample_info = {'sample_id': sample_id, 'random_select': self.random_select}\n\n if self.mode == 'TEST':\n if cfg.RPN.USE_INTENSITY:\n pts_input = np.concatenate((ret_pts_rect, ret_pts_features), axis=1) # (N, C)\n else:\n pts_input = ret_pts_rect\n sample_info['pts_input'] = pts_input\n sample_info['pts_rect'] = ret_pts_rect\n sample_info['pts_features'] = ret_pts_features\n return sample_info\n\n gt_obj_list = self.filtrate_objects(self.get_label(sample_id))\n if cfg.GT_AUG_ENABLED and self.mode == 'TRAIN' and gt_aug_flag:\n gt_obj_list.extend(extra_gt_obj_list)\n gt_boxes3d = kitti_utils.objs_to_boxes3d(gt_obj_list)\n\n gt_alpha = np.zeros((gt_obj_list.__len__()), dtype=np.float32)\n for k, obj in enumerate(gt_obj_list):\n gt_alpha[k] = obj.alpha\n\n # data augmentation\n aug_pts_rect = ret_pts_rect.copy()\n aug_gt_boxes3d = gt_boxes3d.copy()\n if cfg.AUG_DATA and self.mode == 'TRAIN':\n aug_pts_rect, aug_gt_boxes3d, aug_method = self.data_augmentation(aug_pts_rect, aug_gt_boxes3d, gt_alpha,\n sample_id)\n sample_info['aug_method'] = aug_method\n\n # prepare input\n if cfg.RPN.USE_INTENSITY:\n pts_input = np.concatenate((aug_pts_rect, ret_pts_features), axis=1) # (N, C)\n else:\n pts_input = aug_pts_rect\n\n if cfg.RPN.FIXED:\n sample_info['pts_input'] = pts_input\n sample_info['pts_rect'] = aug_pts_rect\n sample_info['pts_features'] = ret_pts_features\n sample_info['gt_boxes3d'] = aug_gt_boxes3d\n return sample_info\n\n # generate training labels\n rpn_cls_label, rpn_reg_label = self.generate_rpn_training_labels(aug_pts_rect, aug_gt_boxes3d)\n sample_info['pts_input'] = pts_input\n sample_info['pts_rect'] = aug_pts_rect\n sample_info['pts_features'] = ret_pts_features\n sample_info['rpn_cls_label'] = rpn_cls_label\n sample_info['rpn_reg_label'] = rpn_reg_label\n sample_info['gt_boxes3d'] = aug_gt_boxes3d\n return sample_info\n\n @staticmethod\n def generate_rpn_training_labels(pts_rect, gt_boxes3d):\n cls_label = np.zeros((pts_rect.shape[0]), dtype=np.int32)\n reg_label = np.zeros((pts_rect.shape[0], 7), dtype=np.float32) # dx, dy, dz, ry, h, w, l\n gt_corners = kitti_utils.boxes3d_to_corners3d(gt_boxes3d, rotate=True)\n extend_gt_boxes3d = kitti_utils.enlarge_box3d(gt_boxes3d, extra_width=0.2)\n extend_gt_corners = kitti_utils.boxes3d_to_corners3d(extend_gt_boxes3d, rotate=True)\n for k in range(gt_boxes3d.shape[0]):\n box_corners = gt_corners[k]\n fg_pt_flag = kitti_utils.in_hull(pts_rect, box_corners)\n fg_pts_rect = pts_rect[fg_pt_flag]\n cls_label[fg_pt_flag] = 1\n\n # enlarge the bbox3d, ignore nearby points\n extend_box_corners = extend_gt_corners[k]\n fg_enlarge_flag = kitti_utils.in_hull(pts_rect, extend_box_corners)\n ignore_flag = np.logical_xor(fg_pt_flag, fg_enlarge_flag)\n cls_label[ignore_flag] = -1\n\n # pixel offset of object center\n center3d = gt_boxes3d[k][0:3].copy() # (x, y, z)\n center3d[1] -= gt_boxes3d[k][3] / 2\n reg_label[fg_pt_flag, 0:3] = center3d - fg_pts_rect # Now y is the true center of 3d box 20180928\n\n # size and angle encoding\n reg_label[fg_pt_flag, 3] = gt_boxes3d[k][3] # h\n reg_label[fg_pt_flag, 4] = gt_boxes3d[k][4] # w\n reg_label[fg_pt_flag, 5] = gt_boxes3d[k][5] # l\n reg_label[fg_pt_flag, 6] = gt_boxes3d[k][6] # ry\n\n return cls_label, reg_label\n\n def rotate_box3d_along_y(self, box3d, rot_angle):\n old_x, old_z, ry = box3d[0], box3d[2], box3d[6]\n old_beta = np.arctan2(old_z, old_x)\n alpha = -np.sign(old_beta) * np.pi / 2 + old_beta + ry\n\n box3d = kitti_utils.rotate_pc_along_y(box3d.reshape(1, 7), rot_angle=rot_angle)[0]\n new_x, new_z = box3d[0], box3d[2]\n new_beta = np.arctan2(new_z, new_x)\n box3d[6] = np.sign(new_beta) * np.pi / 2 + alpha - new_beta\n\n return box3d\n\n def apply_gt_aug_to_one_scene(self, sample_id, pts_rect, pts_intensity, all_gt_boxes3d):\n \"\"\"\n :param pts_rect: (N, 3)\n :param all_gt_boxex3d: (M2, 7)\n :return:\n \"\"\"\n assert self.gt_database is not None\n # extra_gt_num = np.random.randint(10, 15)\n # try_times = 50\n if cfg.GT_AUG_RAND_NUM:\n extra_gt_num = np.random.randint(10, cfg.GT_EXTRA_NUM)\n else:\n extra_gt_num = cfg.GT_EXTRA_NUM\n try_times = 100\n cnt = 0\n cur_gt_boxes3d = all_gt_boxes3d.copy()\n cur_gt_boxes3d[:, 4] += 0.5 # TODO: consider different objects\n cur_gt_boxes3d[:, 5] += 0.5 # enlarge new added box to avoid too nearby boxes\n cur_gt_corners = kitti_utils.boxes3d_to_corners3d(cur_gt_boxes3d)\n\n extra_gt_obj_list = []\n extra_gt_boxes3d_list = []\n new_pts_list, new_pts_intensity_list = [], []\n src_pts_flag = np.ones(pts_rect.shape[0], dtype=np.int32)\n\n road_plane = self.get_road_plane(sample_id)\n a, b, c, d = road_plane\n\n while try_times > 0:\n if cnt > extra_gt_num:\n break\n\n try_times -= 1\n if cfg.GT_AUG_HARD_RATIO > 0:\n p = np.random.rand()\n if p > cfg.GT_AUG_HARD_RATIO:\n # use easy sample\n rand_idx = np.random.randint(0, len(self.gt_database[0]))\n new_gt_dict = self.gt_database[0][rand_idx]\n else:\n # use hard sample\n rand_idx = np.random.randint(0, len(self.gt_database[1]))\n new_gt_dict = self.gt_database[1][rand_idx]\n else:\n rand_idx = np.random.randint(0, self.gt_database.__len__())\n new_gt_dict = self.gt_database[rand_idx]\n\n new_gt_box3d = new_gt_dict['gt_box3d'].copy()\n new_gt_points = new_gt_dict['points'].copy()\n new_gt_intensity = new_gt_dict['intensity'].copy()\n new_gt_obj = new_gt_dict['obj']\n center = new_gt_box3d[0:3]\n if cfg.PC_REDUCE_BY_RANGE and (self.check_pc_range(center) is False):\n continue\n\n if new_gt_points.__len__() < 5: # too few points\n continue\n\n # put it on the road plane\n cur_height = (-d - a * center[0] - c * center[2]) / b\n move_height = new_gt_box3d[1] - cur_height\n new_gt_box3d[1] -= move_height\n new_gt_points[:, 1] -= move_height\n new_gt_obj.pos[1] -= move_height\n\n new_enlarged_box3d = new_gt_box3d.copy()\n new_enlarged_box3d[4] += 0.5\n new_enlarged_box3d[5] += 0.5 # enlarge new added box to avoid too nearby boxes\n\n cnt += 1\n new_corners = kitti_utils.boxes3d_to_corners3d(new_enlarged_box3d.reshape(1, 7))\n iou3d = kitti_utils.get_iou3d(new_corners, cur_gt_corners)\n valid_flag = iou3d.max() < 1e-8\n if not valid_flag:\n continue\n\n enlarged_box3d = new_gt_box3d.copy()\n enlarged_box3d[3] += 2 # remove the points above and below the object\n\n boxes_pts_mask_list = roipool3d_utils.pts_in_boxes3d_cpu(\n torch.from_numpy(pts_rect), torch.from_numpy(enlarged_box3d.reshape(1, 7)))\n pt_mask_flag = (boxes_pts_mask_list[0].numpy() == 1)\n src_pts_flag[pt_mask_flag] = 0 # remove the original points which are inside the new box\n\n new_pts_list.append(new_gt_points)\n new_pts_intensity_list.append(new_gt_intensity)\n cur_gt_boxes3d = np.concatenate((cur_gt_boxes3d, new_enlarged_box3d.reshape(1, 7)), axis=0)\n cur_gt_corners = np.concatenate((cur_gt_corners, new_corners), axis=0)\n extra_gt_boxes3d_list.append(new_gt_box3d.reshape(1, 7))\n extra_gt_obj_list.append(new_gt_obj)\n\n if new_pts_list.__len__() == 0:\n return False, pts_rect, pts_intensity, None, None\n\n extra_gt_boxes3d = np.concatenate(extra_gt_boxes3d_list, axis=0)\n # remove original points and add new points\n pts_rect = pts_rect[src_pts_flag == 1]\n pts_intensity = pts_intensity[src_pts_flag == 1]\n new_pts_rect = np.concatenate(new_pts_list, axis=0)\n new_pts_intensity = np.concatenate(new_pts_intensity_list, axis=0)\n pts_rect = np.concatenate((pts_rect, new_pts_rect), axis=0)\n pts_intensity = np.concatenate((pts_intensity, new_pts_intensity), axis=0)\n\n return True, pts_rect, pts_intensity, extra_gt_boxes3d, extra_gt_obj_list\n\n def data_augmentation(self, aug_pts_rect, aug_gt_boxes3d, gt_alpha, sample_id=None, mustaug=False, stage=1):\n \"\"\"\n :param aug_pts_rect: (N, 3)\n :param aug_gt_boxes3d: (N, 7)\n :param gt_alpha: (N)\n :return:\n \"\"\"\n aug_list = cfg.AUG_METHOD_LIST\n aug_enable = 1 - np.random.rand(3)\n if mustaug is True:\n aug_enable[0] = -1\n aug_enable[1] = -1\n aug_method = []\n if 'rotation' in aug_list and aug_enable[0] < cfg.AUG_METHOD_PROB[0]:\n angle = np.random.uniform(-np.pi / cfg.AUG_ROT_RANGE, np.pi / cfg.AUG_ROT_RANGE)\n aug_pts_rect = kitti_utils.rotate_pc_along_y(aug_pts_rect, rot_angle=angle)\n if stage == 1:\n # xyz change, hwl unchange\n aug_gt_boxes3d = kitti_utils.rotate_pc_along_y(aug_gt_boxes3d, rot_angle=angle)\n\n # calculate the ry after rotation\n x, z = aug_gt_boxes3d[:, 0], aug_gt_boxes3d[:, 2]\n beta = np.arctan2(z, x)\n new_ry = np.sign(beta) * np.pi / 2 + gt_alpha - beta\n aug_gt_boxes3d[:, 6] = new_ry # TODO: not in [-np.pi / 2, np.pi / 2]\n elif stage == 2:\n # for debug stage-2, this implementation has little float precision difference with the above one\n assert aug_gt_boxes3d.shape[0] == 2\n aug_gt_boxes3d[0] = self.rotate_box3d_along_y(aug_gt_boxes3d[0], angle)\n aug_gt_boxes3d[1] = self.rotate_box3d_along_y(aug_gt_boxes3d[1], angle)\n else:\n raise NotImplementedError\n\n aug_method.append(['rotation', angle])\n\n if 'scaling' in aug_list and aug_enable[1] < cfg.AUG_METHOD_PROB[1]:\n scale = np.random.uniform(0.95, 1.05)\n aug_pts_rect = aug_pts_rect * scale\n aug_gt_boxes3d[:, 0:6] = aug_gt_boxes3d[:, 0:6] * scale\n aug_method.append(['scaling', scale])\n\n if 'flip' in aug_list and aug_enable[2] < cfg.AUG_METHOD_PROB[2]:\n # flip horizontal\n aug_pts_rect[:, 0] = -aug_pts_rect[:, 0]\n aug_gt_boxes3d[:, 0] = -aug_gt_boxes3d[:, 0]\n # flip orientation: ry > 0: pi - ry, ry < 0: -pi - ry\n if stage == 1:\n aug_gt_boxes3d[:, 6] = np.sign(aug_gt_boxes3d[:, 6]) * np.pi - aug_gt_boxes3d[:, 6]\n elif stage == 2:\n assert aug_gt_boxes3d.shape[0] == 2\n aug_gt_boxes3d[0, 6] = np.sign(aug_gt_boxes3d[0, 6]) * np.pi - aug_gt_boxes3d[0, 6]\n aug_gt_boxes3d[1, 6] = np.sign(aug_gt_boxes3d[1, 6]) * np.pi - aug_gt_boxes3d[1, 6]\n else:\n raise NotImplementedError\n\n aug_method.append('flip')\n\n return aug_pts_rect, aug_gt_boxes3d, aug_method\n\n def get_rcnn_sample_info(self, roi_info):\n sample_id, gt_box3d = roi_info['sample_id'], roi_info['gt_box3d']\n rpn_xyz, rpn_features, rpn_intensity, seg_mask = self.rpn_feature_list[sample_id]\n\n # augmentation original roi by adding noise\n roi_box3d = self.aug_roi_by_noise(roi_info)\n\n # point cloud pooling based on roi_box3d\n pooled_boxes3d = kitti_utils.enlarge_box3d(roi_box3d.reshape(1, 7), cfg.RCNN.POOL_EXTRA_WIDTH)\n\n boxes_pts_mask_list = roipool3d_utils.pts_in_boxes3d_cpu(torch.from_numpy(rpn_xyz),\n torch.from_numpy(pooled_boxes3d))\n pt_mask_flag = (boxes_pts_mask_list[0].numpy() == 1)\n cur_pts = rpn_xyz[pt_mask_flag].astype(np.float32)\n\n # data augmentation\n aug_pts = cur_pts.copy()\n aug_gt_box3d = gt_box3d.copy().astype(np.float32)\n aug_roi_box3d = roi_box3d.copy()\n if cfg.AUG_DATA and self.mode == 'TRAIN':\n # calculate alpha by ry\n temp_boxes3d = np.concatenate([aug_roi_box3d.reshape(1, 7), aug_gt_box3d.reshape(1, 7)], axis=0)\n temp_x, temp_z, temp_ry = temp_boxes3d[:, 0], temp_boxes3d[:, 2], temp_boxes3d[:, 6]\n temp_beta = np.arctan2(temp_z, temp_x).astype(np.float64)\n temp_alpha = -np.sign(temp_beta) * np.pi / 2 + temp_beta + temp_ry\n\n # data augmentation\n aug_pts, aug_boxes3d, aug_method = self.data_augmentation(aug_pts, temp_boxes3d, temp_alpha, mustaug=True, stage=2)\n aug_roi_box3d, aug_gt_box3d = aug_boxes3d[0], aug_boxes3d[1]\n aug_gt_box3d = aug_gt_box3d.astype(gt_box3d.dtype)\n\n # Pool input points\n valid_mask = 1 # whether the input is valid\n\n if aug_pts.shape[0] == 0:\n pts_features = np.zeros((1, 128), dtype=np.float32)\n input_channel = 3 + int(cfg.RCNN.USE_INTENSITY) + int(cfg.RCNN.USE_MASK) + int(cfg.RCNN.USE_DEPTH)\n pts_input = np.zeros((1, input_channel), dtype=np.float32)\n valid_mask = 0\n else:\n pts_features = rpn_features[pt_mask_flag].astype(np.float32)\n pts_intensity = rpn_intensity[pt_mask_flag].astype(np.float32)\n\n pts_input_list = [aug_pts, pts_intensity.reshape(-1, 1)]\n if cfg.RCNN.USE_INTENSITY:\n pts_input_list = [aug_pts, pts_intensity.reshape(-1, 1)]\n else:\n pts_input_list = [aug_pts]\n\n if cfg.RCNN.USE_MASK:\n if cfg.RCNN.MASK_TYPE == 'seg':\n pts_mask = seg_mask[pt_mask_flag].astype(np.float32)\n elif cfg.RCNN.MASK_TYPE == 'roi':\n pts_mask = roipool3d_utils.pts_in_boxes3d_cpu(torch.from_numpy(aug_pts),\n torch.from_numpy(aug_roi_box3d.reshape(1, 7)))\n pts_mask = (pts_mask[0].numpy() == 1).astype(np.float32)\n else:\n raise NotImplementedError\n\n pts_input_list.append(pts_mask.reshape(-1, 1))\n\n if cfg.RCNN.USE_DEPTH:\n pts_depth = np.linalg.norm(aug_pts, axis=1, ord=2)\n pts_depth_norm = (pts_depth / 70.0) - 0.5\n pts_input_list.append(pts_depth_norm.reshape(-1, 1))\n\n pts_input = np.concatenate(pts_input_list, axis=1) # (N, C)\n\n aug_gt_corners = kitti_utils.boxes3d_to_corners3d(aug_gt_box3d.reshape(-1, 7))\n aug_roi_corners = kitti_utils.boxes3d_to_corners3d(aug_roi_box3d.reshape(-1, 7))\n iou3d = kitti_utils.get_iou3d(aug_roi_corners, aug_gt_corners)\n cur_iou = iou3d[0][0]\n\n # regression valid mask\n reg_valid_mask = 1 if cur_iou >= cfg.RCNN.REG_FG_THRESH and valid_mask == 1 else 0\n\n # classification label\n cls_label = 1 if cur_iou > cfg.RCNN.CLS_FG_THRESH else 0\n if cfg.RCNN.CLS_BG_THRESH < cur_iou < cfg.RCNN.CLS_FG_THRESH or valid_mask == 0:\n cls_label = -1\n\n # canonical transform and sampling\n pts_input_ct, gt_box3d_ct = self.canonical_transform(pts_input, aug_roi_box3d, aug_gt_box3d)\n pts_input_ct, pts_features = self.rcnn_input_sample(pts_input_ct, pts_features)\n\n sample_info = {'sample_id': sample_id,\n 'pts_input': pts_input_ct,\n 'pts_features': pts_features,\n 'cls_label': cls_label,\n 'reg_valid_mask': reg_valid_mask,\n 'gt_boxes3d_ct': gt_box3d_ct,\n 'roi_boxes3d': aug_roi_box3d,\n 'roi_size': aug_roi_box3d[3:6],\n 'gt_boxes3d': aug_gt_box3d}\n\n return sample_info\n\n @staticmethod\n def canonical_transform(pts_input, roi_box3d, gt_box3d):\n roi_ry = roi_box3d[6] % (2 * np.pi) # 0 ~ 2pi\n roi_center = roi_box3d[0:3]\n # shift to center\n pts_input[:, [0, 1, 2]] = pts_input[:, [0, 1, 2]] - roi_center\n gt_box3d_ct = np.copy(gt_box3d)\n gt_box3d_ct[0:3] = gt_box3d_ct[0:3] - roi_center\n # rotate to the direction of head\n gt_box3d_ct = kitti_utils.rotate_pc_along_y(gt_box3d_ct.reshape(1, 7), roi_ry).reshape(7)\n gt_box3d_ct[6] = gt_box3d_ct[6] - roi_ry\n pts_input = kitti_utils.rotate_pc_along_y(pts_input, roi_ry)\n\n return pts_input, gt_box3d_ct\n\n @staticmethod\n def canonical_transform_batch(pts_input, roi_boxes3d, gt_boxes3d):\n \"\"\"\n :param pts_input: (N, npoints, 3 + C)\n :param roi_boxes3d: (N, 7)\n :param gt_boxes3d: (N, 7)\n :return:\n \"\"\"\n roi_ry = roi_boxes3d[:, 6] % (2 * np.pi) # 0 ~ 2pi\n roi_center = roi_boxes3d[:, 0:3]\n # shift to center\n pts_input[:, :, [0, 1, 2]] = pts_input[:, :, [0, 1, 2]] - roi_center.reshape(-1, 1, 3)\n gt_boxes3d_ct = np.copy(gt_boxes3d)\n gt_boxes3d_ct[:, 0:3] = gt_boxes3d_ct[:, 0:3] - roi_center\n # rotate to the direction of head\n gt_boxes3d_ct = kitti_utils.rotate_pc_along_y_torch(torch.from_numpy(gt_boxes3d_ct.reshape(-1, 1, 7)),\n torch.from_numpy(roi_ry)).numpy().reshape(-1, 7)\n gt_boxes3d_ct[:, 6] = gt_boxes3d_ct[:, 6] - roi_ry\n pts_input = kitti_utils.rotate_pc_along_y_torch(torch.from_numpy(pts_input), torch.from_numpy(roi_ry)).numpy()\n\n return pts_input, gt_boxes3d_ct\n\n @staticmethod\n def rcnn_input_sample(pts_input, pts_features):\n choice = np.random.choice(pts_input.shape[0], cfg.RCNN.NUM_POINTS, replace=True)\n\n if pts_input.shape[0] < cfg.RCNN.NUM_POINTS:\n choice[:pts_input.shape[0]] = np.arange(pts_input.shape[0])\n np.random.shuffle(choice)\n pts_input = pts_input[choice]\n pts_features = pts_features[choice]\n\n return pts_input, pts_features\n\n def aug_roi_by_noise(self, roi_info):\n \"\"\"\n add noise to original roi to get aug_box3d\n :param roi_info:\n :return:\n \"\"\"\n roi_box3d, gt_box3d = roi_info['roi_box3d'], roi_info['gt_box3d']\n original_iou = roi_info['iou3d']\n temp_iou = cnt = 0\n pos_thresh = min(cfg.RCNN.REG_FG_THRESH, cfg.RCNN.CLS_FG_THRESH)\n gt_corners = kitti_utils.boxes3d_to_corners3d(gt_box3d.reshape(-1, 7))\n aug_box3d = roi_box3d\n while temp_iou < pos_thresh and cnt < 10:\n if roi_info['type'] == 'gt':\n aug_box3d = self.random_aug_box3d(roi_box3d) # GT, must random\n else:\n if np.random.rand() < 0.2:\n aug_box3d = roi_box3d # p=0.2 to keep the original roi box\n else:\n aug_box3d = self.random_aug_box3d(roi_box3d)\n aug_corners = kitti_utils.boxes3d_to_corners3d(aug_box3d.reshape(-1, 7))\n iou3d = kitti_utils.get_iou3d(aug_corners, gt_corners)\n temp_iou = iou3d[0][0]\n cnt += 1\n if original_iou < pos_thresh: # original bg, break\n break\n return aug_box3d\n\n @staticmethod\n def random_aug_box3d(box3d):\n \"\"\"\n :param box3d: (7) [x, y, z, h, w, l, ry]\n random shift, scale, orientation\n \"\"\"\n if cfg.RCNN.REG_AUG_METHOD == 'single':\n pos_shift = (np.random.rand(3) - 0.5) # [-0.5 ~ 0.5]\n hwl_scale = (np.random.rand(3) - 0.5) / (0.5 / 0.15) + 1.0 #\n angle_rot = (np.random.rand(1) - 0.5) / (0.5 / (np.pi / 12)) # [-pi/12 ~ pi/12]\n\n aug_box3d = np.concatenate([box3d[0:3] + pos_shift, box3d[3:6] * hwl_scale,\n box3d[6:7] + angle_rot])\n return aug_box3d\n elif cfg.RCNN.REG_AUG_METHOD == 'multiple':\n # pos_range, hwl_range, angle_range, mean_iou\n range_config = [[0.2, 0.1, np.pi / 12, 0.7],\n [0.3, 0.15, np.pi / 12, 0.6],\n [0.5, 0.15, np.pi / 9, 0.5],\n [0.8, 0.15, np.pi / 6, 0.3],\n [1.0, 0.15, np.pi / 3, 0.2]]\n idx = np.random.randint(len(range_config))\n\n pos_shift = ((np.random.rand(3) - 0.5) / 0.5) * range_config[idx][0]\n hwl_scale = ((np.random.rand(3) - 0.5) / 0.5) * range_config[idx][1] + 1.0\n angle_rot = ((np.random.rand(1) - 0.5) / 0.5) * range_config[idx][2]\n\n aug_box3d = np.concatenate([box3d[0:3] + pos_shift, box3d[3:6] * hwl_scale, box3d[6:7] + angle_rot])\n return aug_box3d\n elif cfg.RCNN.REG_AUG_METHOD == 'normal':\n x_shift = np.random.normal(loc=0, scale=0.3)\n y_shift = np.random.normal(loc=0, scale=0.2)\n z_shift = np.random.normal(loc=0, scale=0.3)\n h_shift = np.random.normal(loc=0, scale=0.25)\n w_shift = np.random.normal(loc=0, scale=0.15)\n l_shift = np.random.normal(loc=0, scale=0.5)\n ry_shift = ((np.random.rand() - 0.5) / 0.5) * np.pi / 12\n\n aug_box3d = np.array([box3d[0] + x_shift, box3d[1] + y_shift, box3d[2] + z_shift, box3d[3] + h_shift,\n box3d[4] + w_shift, box3d[5] + l_shift, box3d[6] + ry_shift])\n return aug_box3d\n else:\n raise NotImplementedError\n\n def get_proposal_from_file(self, index):\n sample_id = int(self.image_idx_list[index])\n proposal_file = os.path.join(self.rcnn_eval_roi_dir, '%06d.txt' % sample_id)\n roi_obj_list = kitti_utils.get_objects_from_label(proposal_file)\n\n rpn_xyz, rpn_features, rpn_intensity, seg_mask = self.get_rpn_features(self.rcnn_eval_feature_dir, sample_id)\n pts_rect, pts_rpn_features, pts_intensity = rpn_xyz, rpn_features, rpn_intensity\n\n roi_box3d_list, roi_scores = [], []\n for obj in roi_obj_list:\n box3d = np.array([obj.pos[0], obj.pos[1], obj.pos[2], obj.h, obj.w, obj.l, obj.ry], dtype=np.float32)\n roi_box3d_list.append(box3d.reshape(1, 7))\n roi_scores.append(obj.score)\n\n roi_boxes3d = np.concatenate(roi_box3d_list, axis=0) # (N, 7)\n roi_scores = np.array(roi_scores, dtype=np.float32) # (N)\n\n if cfg.RCNN.ROI_SAMPLE_JIT:\n sample_dict = {'sample_id': sample_id,\n 'rpn_xyz': rpn_xyz,\n 'rpn_features': rpn_features,\n 'seg_mask': seg_mask,\n 'roi_boxes3d': roi_boxes3d,\n 'roi_scores': roi_scores,\n 'pts_depth': np.linalg.norm(rpn_xyz, ord=2, axis=1)}\n\n if self.mode != 'TEST':\n gt_obj_list = self.filtrate_objects(self.get_label(sample_id))\n gt_boxes3d = kitti_utils.objs_to_boxes3d(gt_obj_list)\n\n roi_corners = kitti_utils.boxes3d_to_corners3d(roi_boxes3d)\n gt_corners = kitti_utils.boxes3d_to_corners3d(gt_boxes3d)\n iou3d = kitti_utils.get_iou3d(roi_corners, gt_corners)\n if gt_boxes3d.shape[0] > 0:\n gt_iou = iou3d.max(axis=1)\n else:\n gt_iou = np.zeros(roi_boxes3d.shape[0]).astype(np.float32)\n\n sample_dict['gt_boxes3d'] = gt_boxes3d\n sample_dict['gt_iou'] = gt_iou\n return sample_dict\n\n if cfg.RCNN.USE_INTENSITY:\n pts_extra_input_list = [pts_intensity.reshape(-1, 1), seg_mask.reshape(-1, 1)]\n else:\n pts_extra_input_list = [seg_mask.reshape(-1, 1)]\n\n if cfg.RCNN.USE_DEPTH:\n cur_depth = np.linalg.norm(pts_rect, axis=1, ord=2)\n cur_depth_norm = (cur_depth / 70.0) - 0.5\n pts_extra_input_list.append(cur_depth_norm.reshape(-1, 1))\n\n pts_extra_input = np.concatenate(pts_extra_input_list, axis=1)\n pts_input, pts_features = roipool3d_utils.roipool3d_cpu(roi_boxes3d, pts_rect, pts_rpn_features,\n pts_extra_input, cfg.RCNN.POOL_EXTRA_WIDTH,\n sampled_pt_num=cfg.RCNN.NUM_POINTS)\n\n sample_dict = {'sample_id': sample_id,\n 'pts_input': pts_input,\n 'pts_features': pts_features,\n 'roi_boxes3d': roi_boxes3d,\n 'roi_scores': roi_scores,\n 'roi_size': roi_boxes3d[:, 3:6]}\n\n if self.mode == 'TEST':\n return sample_dict\n\n gt_obj_list = self.filtrate_objects(self.get_label(sample_id))\n gt_boxes3d = np.zeros((gt_obj_list.__len__(), 7), dtype=np.float32)\n\n for k, obj in enumerate(gt_obj_list):\n gt_boxes3d[k, 0:3], gt_boxes3d[k, 3], gt_boxes3d[k, 4], gt_boxes3d[k, 5], gt_boxes3d[k, 6] \\\n = obj.pos, obj.h, obj.w, obj.l, obj.ry\n\n if gt_boxes3d.__len__() == 0:\n gt_iou = np.zeros((roi_boxes3d.shape[0]), dtype=np.float32)\n else:\n roi_corners = kitti_utils.boxes3d_to_corners3d(roi_boxes3d)\n gt_corners = kitti_utils.boxes3d_to_corners3d(gt_boxes3d)\n iou3d = kitti_utils.get_iou3d(roi_corners, gt_corners)\n gt_iou = iou3d.max(axis=1)\n sample_dict['gt_boxes3d'] = gt_boxes3d\n sample_dict['gt_iou'] = gt_iou\n\n return sample_dict\n\n def get_rcnn_training_sample_batch(self, index):\n sample_id = int(self.sample_id_list[index])\n rpn_xyz, rpn_features, rpn_intensity, seg_mask = \\\n self.get_rpn_features(self.rcnn_training_feature_dir, sample_id)\n\n # load rois and gt_boxes3d for this sample\n roi_file = os.path.join(self.rcnn_training_roi_dir, '%06d.txt' % sample_id)\n roi_obj_list = kitti_utils.get_objects_from_label(roi_file)\n roi_boxes3d = kitti_utils.objs_to_boxes3d(roi_obj_list)\n # roi_scores = kitti_utils.objs_to_scores(roi_obj_list)\n\n gt_obj_list = self.filtrate_objects(self.get_label(sample_id))\n gt_boxes3d = kitti_utils.objs_to_boxes3d(gt_obj_list)\n\n # calculate original iou\n iou3d = kitti_utils.get_iou3d(kitti_utils.boxes3d_to_corners3d(roi_boxes3d),\n kitti_utils.boxes3d_to_corners3d(gt_boxes3d))\n max_overlaps, gt_assignment = iou3d.max(axis=1), iou3d.argmax(axis=1)\n max_iou_of_gt, roi_assignment = iou3d.max(axis=0), iou3d.argmax(axis=0)\n roi_assignment = roi_assignment[max_iou_of_gt > 0].reshape(-1)\n\n # sample fg, easy_bg, hard_bg\n fg_rois_per_image = int(np.round(cfg.RCNN.FG_RATIO * cfg.RCNN.ROI_PER_IMAGE))\n fg_thresh = min(cfg.RCNN.REG_FG_THRESH, cfg.RCNN.CLS_FG_THRESH)\n fg_inds = np.nonzero(max_overlaps >= fg_thresh)[0]\n fg_inds = np.concatenate((fg_inds, roi_assignment), axis=0) # consider the roi which has max_overlaps with gt as fg\n\n easy_bg_inds = np.nonzero((max_overlaps < cfg.RCNN.CLS_BG_THRESH_LO))[0]\n hard_bg_inds = np.nonzero((max_overlaps < cfg.RCNN.CLS_BG_THRESH) &\n (max_overlaps >= cfg.RCNN.CLS_BG_THRESH_LO))[0]\n\n fg_num_rois = fg_inds.size\n bg_num_rois = hard_bg_inds.size + easy_bg_inds.size\n\n if fg_num_rois > 0 and bg_num_rois > 0:\n # sampling fg\n fg_rois_per_this_image = min(fg_rois_per_image, fg_num_rois)\n rand_num = np.random.permutation(fg_num_rois)\n fg_inds = fg_inds[rand_num[:fg_rois_per_this_image]]\n\n # sampling bg\n bg_rois_per_this_image = cfg.RCNN.ROI_PER_IMAGE - fg_rois_per_this_image\n bg_inds = self.sample_bg_inds(hard_bg_inds, easy_bg_inds, bg_rois_per_this_image)\n\n elif fg_num_rois > 0 and bg_num_rois == 0:\n # sampling fg\n rand_num = np.floor(np.random.rand(cfg.RCNN.ROI_PER_IMAGE ) * fg_num_rois)\n rand_num = torch.from_numpy(rand_num).type_as(gt_boxes3d).long()\n fg_inds = fg_inds[rand_num]\n fg_rois_per_this_image = cfg.RCNN.ROI_PER_IMAGE\n bg_rois_per_this_image = 0\n elif bg_num_rois > 0 and fg_num_rois == 0:\n # sampling bg\n bg_rois_per_this_image = cfg.RCNN.ROI_PER_IMAGE\n bg_inds = self.sample_bg_inds(hard_bg_inds, easy_bg_inds, bg_rois_per_this_image)\n fg_rois_per_this_image = 0\n else:\n import pdb\n pdb.set_trace()\n raise NotImplementedError\n\n # augment the rois by noise\n roi_list, roi_iou_list, roi_gt_list = [], [], []\n if fg_rois_per_this_image > 0:\n fg_rois_src = roi_boxes3d[fg_inds].copy()\n gt_of_fg_rois = gt_boxes3d[gt_assignment[fg_inds]]\n fg_rois, fg_iou3d = self.aug_roi_by_noise_batch(fg_rois_src, gt_of_fg_rois, aug_times=10)\n roi_list.append(fg_rois)\n roi_iou_list.append(fg_iou3d)\n roi_gt_list.append(gt_of_fg_rois)\n\n if bg_rois_per_this_image > 0:\n bg_rois_src = roi_boxes3d[bg_inds].copy()\n gt_of_bg_rois = gt_boxes3d[gt_assignment[bg_inds]]\n bg_rois, bg_iou3d = self.aug_roi_by_noise_batch(bg_rois_src, gt_of_bg_rois, aug_times=1)\n roi_list.append(bg_rois)\n roi_iou_list.append(bg_iou3d)\n roi_gt_list.append(gt_of_bg_rois)\n\n rois = np.concatenate(roi_list, axis=0)\n iou_of_rois = np.concatenate(roi_iou_list, axis=0)\n gt_of_rois = np.concatenate(roi_gt_list, axis=0)\n\n # collect extra features for point cloud pooling\n if cfg.RCNN.USE_INTENSITY:\n pts_extra_input_list = [rpn_intensity.reshape(-1, 1), seg_mask.reshape(-1, 1)]\n else:\n pts_extra_input_list = [seg_mask.reshape(-1, 1)]\n\n if cfg.RCNN.USE_DEPTH:\n pts_depth = (np.linalg.norm(rpn_xyz, ord=2, axis=1) / 70.0) - 0.5\n pts_extra_input_list.append(pts_depth.reshape(-1, 1))\n pts_extra_input = np.concatenate(pts_extra_input_list, axis=1)\n\n pts_input, pts_features, pts_empty_flag = roipool3d_utils.roipool3d_cpu(rois, rpn_xyz, rpn_features,\n pts_extra_input,\n cfg.RCNN.POOL_EXTRA_WIDTH,\n sampled_pt_num=cfg.RCNN.NUM_POINTS,\n canonical_transform=False)\n\n # data augmentation\n if cfg.AUG_DATA and self.mode == 'TRAIN':\n for k in range(rois.__len__()):\n aug_pts = pts_input[k, :, 0:3].copy()\n aug_gt_box3d = gt_of_rois[k].copy()\n aug_roi_box3d = rois[k].copy()\n\n # calculate alpha by ry\n temp_boxes3d = np.concatenate([aug_roi_box3d.reshape(1, 7), aug_gt_box3d.reshape(1, 7)], axis=0)\n temp_x, temp_z, temp_ry = temp_boxes3d[:, 0], temp_boxes3d[:, 2], temp_boxes3d[:, 6]\n temp_beta = np.arctan2(temp_z, temp_x).astype(np.float64)\n temp_alpha = -np.sign(temp_beta) * np.pi / 2 + temp_beta + temp_ry\n\n # data augmentation\n aug_pts, aug_boxes3d, aug_method = self.data_augmentation(aug_pts, temp_boxes3d, temp_alpha,\n mustaug=True, stage=2)\n\n # assign to original data\n pts_input[k, :, 0:3] = aug_pts\n rois[k] = aug_boxes3d[0]\n gt_of_rois[k] = aug_boxes3d[1]\n\n valid_mask = (pts_empty_flag == 0).astype(np.int32)\n\n # regression valid mask\n reg_valid_mask = (iou_of_rois > cfg.RCNN.REG_FG_THRESH).astype(np.int32) & valid_mask\n\n # classification label\n cls_label = (iou_of_rois > cfg.RCNN.CLS_FG_THRESH).astype(np.int32)\n invalid_mask = (iou_of_rois > cfg.RCNN.CLS_BG_THRESH) & (iou_of_rois < cfg.RCNN.CLS_FG_THRESH)\n cls_label[invalid_mask] = -1\n cls_label[valid_mask == 0] = -1\n\n # canonical transform and sampling\n pts_input_ct, gt_boxes3d_ct = self.canonical_transform_batch(pts_input, rois, gt_of_rois)\n\n sample_info = {'sample_id': sample_id,\n 'pts_input': pts_input_ct,\n 'pts_features': pts_features,\n 'cls_label': cls_label,\n 'reg_valid_mask': reg_valid_mask,\n 'gt_boxes3d_ct': gt_boxes3d_ct,\n 'roi_boxes3d': rois,\n 'roi_size': rois[:, 3:6],\n 'gt_boxes3d': gt_of_rois}\n\n return sample_info\n\n def sample_bg_inds(self, hard_bg_inds, easy_bg_inds, bg_rois_per_this_image):\n if hard_bg_inds.size > 0 and easy_bg_inds.size > 0:\n hard_bg_rois_num = int(bg_rois_per_this_image * cfg.RCNN.HARD_BG_RATIO)\n easy_bg_rois_num = bg_rois_per_this_image - hard_bg_rois_num\n\n # sampling hard bg\n rand_num = np.floor(np.random.rand(hard_bg_rois_num) * hard_bg_inds.size).astype(np.int32)\n hard_bg_inds = hard_bg_inds[rand_num]\n # sampling easy bg\n rand_num = np.floor(np.random.rand(easy_bg_rois_num) * easy_bg_inds.size).astype(np.int32)\n easy_bg_inds = easy_bg_inds[rand_num]\n\n bg_inds = np.concatenate([hard_bg_inds, easy_bg_inds], axis=0)\n elif hard_bg_inds.size > 0 and easy_bg_inds.size == 0:\n hard_bg_rois_num = bg_rois_per_this_image\n # sampling hard bg\n rand_num = np.floor(np.random.rand(hard_bg_rois_num) * hard_bg_inds.size).astype(np.int32)\n bg_inds = hard_bg_inds[rand_num]\n elif hard_bg_inds.size == 0 and easy_bg_inds.size > 0:\n easy_bg_rois_num = bg_rois_per_this_image\n # sampling easy bg\n rand_num = np.floor(np.random.rand(easy_bg_rois_num) * easy_bg_inds.size).astype(np.int32)\n bg_inds = easy_bg_inds[rand_num]\n else:\n raise NotImplementedError\n\n return bg_inds\n\n def aug_roi_by_noise_batch(self, roi_boxes3d, gt_boxes3d, aug_times=10):\n \"\"\"\n :param roi_boxes3d: (N, 7)\n :param gt_boxes3d: (N, 7)\n :return:\n \"\"\"\n iou_of_rois = np.zeros(roi_boxes3d.shape[0], dtype=np.float32)\n for k in range(roi_boxes3d.__len__()):\n temp_iou = cnt = 0\n roi_box3d = roi_boxes3d[k]\n gt_box3d = gt_boxes3d[k]\n pos_thresh = min(cfg.RCNN.REG_FG_THRESH, cfg.RCNN.CLS_FG_THRESH)\n gt_corners = kitti_utils.boxes3d_to_corners3d(gt_box3d.reshape(1, 7))\n aug_box3d = roi_box3d\n while temp_iou < pos_thresh and cnt < aug_times:\n if np.random.rand() < 0.2:\n aug_box3d = roi_box3d # p=0.2 to keep the original roi box\n else:\n aug_box3d = self.random_aug_box3d(roi_box3d)\n aug_corners = kitti_utils.boxes3d_to_corners3d(aug_box3d.reshape(1, 7))\n iou3d = kitti_utils.get_iou3d(aug_corners, gt_corners)\n temp_iou = iou3d[0][0]\n cnt += 1\n roi_boxes3d[k] = aug_box3d\n iou_of_rois[k] = temp_iou\n return roi_boxes3d, iou_of_rois\n\n def get_rcnn_sample_jit(self, index):\n sample_id = int(self.sample_id_list[index])\n rpn_xyz, rpn_features, rpn_intensity, seg_mask = \\\n self.get_rpn_features(self.rcnn_training_feature_dir, sample_id)\n\n # load rois and gt_boxes3d for this sample\n roi_file = os.path.join(self.rcnn_training_roi_dir, '%06d.txt' % sample_id)\n roi_obj_list = kitti_utils.get_objects_from_label(roi_file)\n roi_boxes3d = kitti_utils.objs_to_boxes3d(roi_obj_list)\n # roi_scores = kitti_utils.objs_to_scores(roi_obj_list)\n\n gt_obj_list = self.filtrate_objects(self.get_label(sample_id))\n gt_boxes3d = kitti_utils.objs_to_boxes3d(gt_obj_list)\n\n sample_info = {'sample_id': sample_id,\n 'rpn_xyz': rpn_xyz,\n 'rpn_features': rpn_features,\n 'rpn_intensity': rpn_intensity,\n 'seg_mask': seg_mask,\n 'roi_boxes3d': roi_boxes3d,\n 'gt_boxes3d': gt_boxes3d,\n 'pts_depth': np.linalg.norm(rpn_xyz, ord=2, axis=1)}\n\n return sample_info\n\n def collate_batch(self, batch):\n if self.mode != 'TRAIN' and cfg.RCNN.ENABLED and not cfg.RPN.ENABLED:\n assert batch.__len__() == 1\n return batch[0]\n\n batch_size = batch.__len__()\n ans_dict = {}\n\n for key in batch[0].keys():\n if cfg.RPN.ENABLED and key == 'gt_boxes3d' or \\\n (cfg.RCNN.ENABLED and cfg.RCNN.ROI_SAMPLE_JIT and key in ['gt_boxes3d', 'roi_boxes3d']):\n max_gt = 0\n for k in range(batch_size):\n max_gt = max(max_gt, batch[k][key].__len__())\n batch_gt_boxes3d = np.zeros((batch_size, max_gt, 7), dtype=np.float32)\n for i in range(batch_size):\n batch_gt_boxes3d[i, :batch[i][key].__len__(), :] = batch[i][key]\n ans_dict[key] = batch_gt_boxes3d\n continue\n\n if isinstance(batch[0][key], np.ndarray):\n if batch_size == 1:\n ans_dict[key] = batch[0][key][np.newaxis, ...]\n else:\n ans_dict[key] = np.concatenate([batch[k][key][np.newaxis, ...] for k in range(batch_size)], axis=0)\n\n else:\n ans_dict[key] = [batch[k][key] for k in range(batch_size)]\n if isinstance(batch[0][key], int):\n ans_dict[key] = np.array(ans_dict[key], dtype=np.int32)\n elif isinstance(batch[0][key], float):\n ans_dict[key] = np.array(ans_dict[key], dtype=np.float32)\n\n return ans_dict\n\n\nif __name__ == '__main__':\n pass\n"
] |
[
[
"numpy.logical_xor",
"numpy.arctan2",
"numpy.concatenate",
"numpy.round",
"numpy.where",
"numpy.random.randint",
"numpy.arange",
"torch.from_numpy",
"numpy.copy",
"numpy.load",
"numpy.zeros",
"numpy.nonzero",
"numpy.random.choice",
"numpy.random.rand",
"numpy.array",
"numpy.logical_and",
"numpy.fromfile",
"numpy.linalg.norm",
"numpy.random.shuffle",
"numpy.ones",
"numpy.sign",
"numpy.random.normal",
"numpy.random.permutation",
"numpy.random.uniform"
]
] |
andyoneal/fastteradata
|
[
"d8a5edb719b48b6c128ad65d495a1c79d1d29f3f"
] |
[
"fastteradata/file_processors/file_processors.py"
] |
[
"import pandas as pd\nimport numpy as np\nimport pyodbc as odbc\nimport teradata\n\nimport json\nimport os\n\nfrom .io_processors import *\nfrom ..metadata_processors.metadata_processors import *\nfrom ..auth.auth import read_credential_file, load_db_info\n\nauth, auth_dict, env_dict = read_credential_file()\n\ndef connect_teradata(env, connector):\n\n env_n, env_dsn, env_short, usr, passw = load_db_info(env)\n\n if connector == \"pyodbc\":\n conn = odbc.connect('DRIVER={Teradata};VERSION=14.10;'+f\"DBCNAME={env_n};DSN={env_dsn};UID={usr};PWD={passw};QUIETMODE=YES\",autocommit=True)\n return(conn)\n\n elif connector == \"teradata\":\n udaExec = teradata.UdaExec(appName=\"Anomaly Detection\", version='1.0', odbcLibPath=\"/opt/teradata/client/15.10/odbc_64/lib/libodbc.so\", logConsole=False)\n session = udaExec.connect(method='odbc', system=env_n, username=usr, password=passw)\n return(session)\n else:\n raise ValueError(\"Wrong value error: Need to specify connector as either teradata or pyodbc\")\n\n\ndef get_unique_partitions(env, db, table, auth_dict=auth_dict, custom_auth=False, connector=\"teradata\", partition_key=\"\", partition_type=\"\", partition_size=-1):\n\n env_n, env_dsn, env_short, usr, passw = load_db_info(env, custom_auth=custom_auth)\n\n sql = \"\"\n if partition_type == \"year\":\n sql = f\"SELECT DISTINCT EXTRACT(YEAR FROM {partition_key}) as years \\\n from {db}.{table} order by years;\"\n elif partition_type == \"month\":\n sql = f\"SELECT DISTINCT EXTRACT(YEAR FROM {partition_key}) as years, \\\n EXTRACT(MONTH FROM {partition_key}) as months \\\n from {db}.{table} order by years, months;\"\n elif partition_type == \"rowcount\":\n if partition_size == -1:\n raise Exception(\"partition_type set to rowcount, but partition_size not provided.\")\n sql = f\"SELECT COUNT(*) from {db}.{table};\"\n else:\n raise Exception(\"Invalid partition_type: Must either be year, month, or rowcount\")\n\n conn = connect_teradata(env, connector)\n df = pd.read_sql(sql, conn)\n unique_list = []\n if partition_type == \"month\":\n df[\"yearmonth\"] = df[\"years\"].map(str) + \"D\" + df[\"months\"].map(str)\n unique_list = df[\"yearmonth\"].tolist()\n elif partition_type == \"year\":\n unique_list = df[\"years\"].tolist()\n elif partition_type == \"rowcount\":\n rowcnt == df.iat[0,0]\n unique_list = np.arange(stop=rowcnt, step=partition_size).tolist()\n else:\n raise Exception(\"Invalid partition_type: must be year, month, or rowcount\")\n\n return(unique_list)\n\n\n\n\ndef generate_sql_main(export_path, file_name, env_short, usr, passw, db, table, meta_df, columns=[], nrows=-1,\n partition_key=\"\", current_partition=\"\", partition_type=\"\", orderby=[], meta_table=\"\", where_clause=\"\", suppress_text=False, distinct=False):\n #print(\"in generage_sql_main\")\n #print(partition_key)\n log_table = db\n if len(meta_table) > 0:\n log_table, _ = meta_table.split(\".\")\n\n #Step 1\n setup_string = f\".LOGTABLE {log_table}.fexplog; \\n\\n\" + f\".LOGON {env_short}/{usr}, {passw}; \\n\\n\"\n #Step 2\n export_string = \".BEGIN EXPORT; \\n\\n .EXPORT OUTFILE \" + export_path + \"/data/\" + file_name + \" \\n MODE RECORD FORMAT TEXT;\\n\\n\"\n\n #Step 3\n distinct_str = \"\"\n if distinct:\n distinct_str = \"DISTINCT\"\n select_string = f\"SELECT {distinct_str} CAST(\\n\"\n if nrows > 0:\n select_string = f\"SELECT {distinct_str} TOP {nrows} CAST(\\n\"\n #Loop through and fill out the coalesce statements\n tot_chars = 0\n\n meta_df[\"ColumnName\"] = meta_df[\"ColumnName\"].apply(lambda x: x.lower().strip())\n col_list = []\n if len(columns) == 0:\n for i in range(0,len(meta_df)):\n end = False\n if i == len(meta_df) -1:\n end = True\n select_string += coalesce_statement(meta_df.loc[i,\"ColumnName\"], meta_df.loc[i,\"FormattedColumnType\"], end)\n if meta_df.loc[i,\"ColumnType\"] == \"DA\":\n tot_chars += 11\n elif meta_df.loc[i,\"ColumnType\"] != \"DA\" and int(meta_df.loc[i,\"CharType\"]) == 0:\n chs = int(meta_df.loc[i,\"FormattedColumnType\"].split(\"(\")[-1].split(\")\")[0]) + 3\n tot_chars += chs\n else:\n tot_chars += int(meta_df.loc[i,\"ColumnLength\"] + 1)\n col_list.append(meta_df.loc[i,\"ColumnName\"])\n if suppress_text == False:\n print(\"COLUMN LIST\")\n print(col_list)\n print(select_string)\n else:\n for i in range(0,len(columns)):\n end = False\n if i == len(columns) - 1:\n end = True\n sub_set = meta_df[meta_df[\"ColumnName\"] == columns[i].lower()]\n #print(sub_set)\n select_string += coalesce_statement(columns[i], sub_set[\"FormattedColumnType\"].values[0], end)\n if sub_set[\"ColumnType\"].values[0] == \"DA\":\n tot_chars += 11\n elif sub_set[\"ColumnType\"].values[0] != \"DA\" and int(sub_set[\"CharType\"].values[0]) == 0:\n chs = int(sub_set[\"FormattedColumnType\"].values[0].split(\"(\")[-1].split(\")\")[0]) + 3\n tot_chars += chs\n else:\n tot_chars += int(sub_set[\"ColumnLength\"].values[0] + 1)\n col_list.append(columns[i])\n\n if partition_key != \"\" and partition_key not in col_list:\n raise Exception(\"Partition key must be in column list\")\n\n select_string += f\" AS CHAR({tot_chars}))\\n\"\n\n from_string = \"FROM \" + db + \".\" + table + \"\\n\"\n\n where_string = \"\"\n if partition_key != \"\" and current_partition != \"\":\n if partition_type == \"year\":\n where_string = \"WHERE EXTRACT(YEAR FROM \" + partition_key + \") = \" + str(current_partition)\n elif partition_type == \"month\":\n where_string = \"WHERE EXTRACT(YEAR FROM \" + partition_key + \") = \" + str(current_partition.split(\"D\")[0]) + \\\n \" AND \" + \"EXTRACT(MONTH FROM \" + partition_key + \") = \" + str(current_partition.split(\"D\")[1])\n if len(where_clause) > 0:\n where_string += f\" AND {where_clause}\"\n elif partition_type == \"rowcount\":\n if len(where_clause) > 0:\n where_string = f\"WHERE {where_clause}\\n\"\n fields_str = ','.join(col_list)\n where_string = f\"QUALIFY ROW_NUMBER() OVER (ORDER BY {fields_str}) BETWEEN {current_partition[0]} and {current_partition[1]}\";\n else:\n if len(where_clause) > 0:\n where_string = f\"WHERE {where_clause}\"\n\n orderby_string = \"\"\n if len(orderby) > 0:\n #If we have order by columns add those to script (useful for horizontal partition pulls)\n orderby_string = \" ORDER BY \"\n for i, c in enumerate(orderby):\n orderby_string += f\"{c} \"\n if (i + 1) != len(orderby):\n orderby_string += \", \"\n\n end_string = \";\\n.END EXPORT;\\n\\n .LOGOFF;\"\n\n final = setup_string + export_string + select_string + from_string + where_string + orderby_string + end_string\n\n\n return(final, col_list)\n\n\n\n\n\ndef coalesce_statement(var, dtype, end=False):\n end_s = \"\\n\"\n if not end:\n end_s = \"||'|'||\\n\"\n\n if (dtype != \"DATE FORMAT 'YYYY-MM-DD') AS CHAR(10)\") and (\"DECIMAL\" not in dtype):\n coal_s = \"COALESCE(CAST(\" + var + \" AS \" + dtype + \"),'')\" + end_s\n else:\n coal_s = \"COALESCE(CAST(CAST(\" + var + \" AS \" + dtype + \"),'')\" + end_s\n\n return(coal_s)\n\n\ndef parse_sql_single_table(export_path, env, db, table, columns=[], auth_dict=auth_dict,\n custom_auth=False, nrows=-1,connector=\"teradata\",\n partition_key=\"\", partition_type=\"year\", partition_size=100000, execute=True, primary_keys=[], meta_table=\"\",\n where_clause=\"\", suppress_text=False, distinct=False):\n \"\"\"\n Summary:\n Parses the information for a valid database table and writes script to output file\n\n Args:\n export_path (str): Path where you want your script to end up\n file_name (str): Name of the output data file you want to create in a sub /data directory.\n The scripts will be generated with the word \"script\" appended in front of the name.\n env (str): Environment for connecting to. Needs to be a valid value either \"ACT\" or \"PROD\"\n db (str): Database name to connect to\n tbl (str): Table name to connect to\n columns (list(str)): Subset of columns to use, default is all of the columns found in the metadata\n auth_dict (dict): either use default for using a panda admin account, or else if you want to do custom auth,\n you must flag custom_auth = True and pass in (\"usrname\",\"passw\") as such like a tuple into auth_dict\n custom_auth (bool): default False, if you want to pass your own creds in, you must flag this as True and pass in a tuple into the auth dict\n nrows (int): Number of rows you want your script to generate, default is all (*)\n suppress_test: Allows suppression of the sql text generated.\n\n Returns:\n Pandas DataFrame containing columns DatabaseName, TableName, ColumnName, ColumnFormat, ColumnLength, CharType\n \"\"\"\n\n\n env_n, env_dsn, env_short, usr, passw = load_db_info(env, custom_auth=custom_auth)\n #Get metadata\n #print(\"metadata\")\n meta_df, dtype_dict = get_table_metadata(env,db,table, columns = columns, auth_dict=auth_dict, custom_auth=custom_auth, connector=connector, partition_key=partition_key, meta_table=meta_table)\n\n #If we have a partition key, we need to find the unique years for the date key\n #print(\"unique_partitions\")\n\n #Making changes here to accomodate horizontal scaling. To start off, we will just check that if we need to do horizontal scaling, you will not be able to use a partition Key\n did_partition = False #Partition flag to pass through for appropriate processing\n MAX_COLS = 110\n tot_columns = len(meta_df[\"ColumnName\"].apply(lambda x: x.lower().strip()).unique())\n\n unique_partitions = []\n if partition_key != \"\" and tot_columns <= MAX_COLS:\n print(\"Getting Unique Partitions\")\n unique_partitions = get_unique_partitions(env, db, table, auth_dict=auth_dict, custom_auth=custom_auth, connector=connector, partition_key=partition_key, partition_type=partition_type)\n did_partition = True\n elif partition_type == \"rowcount\" and tot_columns <= MAX_COLS:\n if partition_key != \"\":\n raise Exception(\"Partitioning by rowcount does not require a partition_key but one was provided. Depending on which partition_type was intended, partiton_key should be removed or partition_type should be year or month. \")\n print(\"Getting Unique Partitions by Splitting Rows into Batches\")\n unique_partitions = get_unique_partitions(env, db, table, auth_dict=auth_dict, custom_auth=custom_auth, connector=connector, partition_type=\"rowcount\", partition_size=partition_size)\n did_partition = True\n elif (partition_key != \"\" or partition_type == \"rowcount\") and tot_columns > MAX_COLS:\n print(\"Cannot create vertical partition because horizontal partitioning is required. Creating horizontal partitions instead.\")\n\n\n final = \"\"\n col_list = []\n fast_export_scripts = []\n file_name = table\n if did_partition == False and partition_key == \"\" and tot_columns <= MAX_COLS:\n _fname = file_name + \"_export.txt\"\n final, col_list = generate_sql_main(export_path, _fname, env_short, usr, passw, db, table, meta_df, columns=columns, nrows=nrows, meta_table=meta_table, where_clause=where_clause, suppress_text = suppress_text)\n #Save fast export file\n script_path = save_file(export_path, _fname, final)\n fast_export_scripts.append(script_path)\n elif did_partition == True and partition_key != \"\" and tot_columns <= MAX_COLS:\n #process the normal vertical partitioning\n for part in unique_partitions:\n _fname = file_name + \"_\" + str(part) + \"_export.txt\"\n final, col_list = generate_sql_main(export_path, _fname, env_short, usr, passw, db, table, meta_df, columns=columns, nrows=nrows, partition_key=partition_key, current_partition=part, partition_type=partition_type, meta_table=meta_table, where_clause=where_clause, suppress_text = suppress_text)\n #Save fast export file\n script_path = save_file(export_path, _fname, final)\n fast_export_scripts.append(script_path)\n elif did_partition == True and partition_type == \"rowcount\" and tot_columns <= MAX_COLS:\n min_row = 0\n for max_row in unique_partitions:\n _fname = file_name + \"_\" + str(min_row) + \"_\" + str(max_row) + \"_export.txt\"\n final, col_list = generate_sql_main(export_path, _fname, env_short, usr, passw, db, table, meta_df, columns=columns, nrows=nrows, partition_key=partition_key, current_partition=(min_row, max_row-1), partition_type=partition_type, meta_table=meta_table, where_clause=where_clause, suppress_text = suppress_text)\n #Save fast export file\n script_path = save_file(export_path, _fname, final)\n fast_export_scripts.append(script_path)\n min_row = max_row\n elif tot_columns > MAX_COLS:\n if not isinstance(primary_keys, list):\n raise Exception(\"'primary_keys' must be a list, even if a single key\")\n if len(primary_keys) == 0:\n raise Exception(\"Horizontal Partitioning is being attempted without a 'primary_keys' argument. Specify the list of primary_keys to execute this pull.\")\n print(\"MAX_COLS exceeded: creating horizontal paritions to accomodate\")\n def col_lookup(meta_df, i, tot_columns, MAX_COLS):\n low_index = i*MAX_COLS\n high_index = min((i+1)*MAX_COLS, tot_columns)\n\n cols = meta_df[\"ColumnName\"].apply(lambda x: x.lower().strip()).unique().tolist()[low_index:high_index]\n #cols = df2.columns.tolist()[low_index:high_index]\n return(cols)\n\n for i in range(0,(tot_columns // MAX_COLS)+1):\n cols = col_lookup(meta_df, i, tot_columns, MAX_COLS) + primary_keys #use the columns in our iteration and add on the specified primary keys so that we can recombine later\n cols = list(set(cols)) #reduce the columns to unique if one of our primary keys is repeated\n _fname = file_name + \"_\" + str(i) + \"_export.txt\"\n final, this_col_list = generate_sql_main(export_path, _fname, env_short, usr, passw, db, table, meta_df, columns=cols, nrows=nrows, orderby=primary_keys, meta_table=meta_table, where_clause=where_clause, suppress_text = suppress_text, distinct=distinct)\n col_list.append(this_col_list) #Since this case will have multiple col_lists, we create a list of lists to pass through\n #Save fast export file\n script_path = save_file(export_path, _fname, final)\n fast_export_scripts.append(script_path)\n did_partition = True\n\n #Save dtype_dict and cols so we can reference if need be\n import pickle\n with open(f\"{export_path}/data/{table}_dict_types.pkl\", 'wb') as handle:\n pickle.dump(dtype_dict, handle, protocol=pickle.HIGHEST_PROTOCOL)\n with open(f\"{export_path}/data/{table}_columns.pkl\", 'wb') as handle:\n pickle.dump(col_list, handle, protocol=pickle.HIGHEST_PROTOCOL)\n #Check for testing missed columns from metadata\n #Testing purposes, can eventually get rid of\n \"\"\"\n if len(columns) > 0:\n meta_cols = [x.lower().strip() for x in meta_df[\"ColumnName\"].tolist()]\n\n cols_not_found = [x.lower() for x in columns if x.lower() not in meta_cols]\n if len(cols_not_found) > 0:\n print(\"Missing columns needed adding: \")\n print(cols_not_found)\n \"\"\"\n return col_list, fast_export_scripts, did_partition, dtype_dict\n\ndef force_string(df, series):\n try:\n df[series] = df[series].map(lambda x: '{:.0f}'.format(x))\n except:\n pass\n return\n"
] |
[
[
"numpy.arange",
"pandas.read_sql"
]
] |
hirnimeshrampuresoftware/vispy
|
[
"241ec8b9e54e4ed5b460377b81c6a4ea60df5a83",
"241ec8b9e54e4ed5b460377b81c6a4ea60df5a83"
] |
[
"examples/scene/isocurve_for_trisurface_qt.py",
"examples/gloo/animate_shape.py"
] |
[
"# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------------\n# Copyright (c) Vispy Development Team. All Rights Reserved.\n# Distributed under the (new) BSD License. See LICENSE.txt for more info.\n# -----------------------------------------------------------------------------\n# vispy: gallery 2\n\"\"\"\nIsocurve for Triangular Mesh with Qt Interface\n==============================================\n\nThis example demonstrates isocurve for triangular mesh with vertex data and a\nqt interface.\n\n\"\"\"\n\nimport numpy as np\n\nfrom vispy import scene, app\n\nfrom vispy.geometry.generation import create_sphere\nfrom vispy.color.colormap import get_colormaps\n\ntry:\n from sip import setapi\n setapi(\"QVariant\", 2)\n setapi(\"QString\", 2)\nexcept ImportError:\n pass\n\ntry:\n from PyQt4 import QtCore\n from PyQt4.QtCore import Qt\n from PyQt4.QtGui import (QMainWindow, QWidget, QLabel,\n QSpinBox, QComboBox, QGridLayout, QVBoxLayout,\n QSplitter)\nexcept Exception:\n # To switch between PyQt5 and PySide2 bindings just change the from import\n from PyQt5 import QtCore\n from PyQt5.QtCore import Qt\n from PyQt5.QtWidgets import (QMainWindow, QWidget, QLabel,\n QSpinBox, QComboBox, QGridLayout, QVBoxLayout,\n QSplitter)\n\n# Provide automatic signal function selection for PyQtX/PySide2\npyqtsignal = QtCore.pyqtSignal if hasattr(QtCore, 'pyqtSignal') else QtCore.Signal\n\n\nclass ObjectWidget(QWidget):\n \"\"\"\n Widget for editing OBJECT parameters\n \"\"\"\n signal_object_changed = pyqtsignal(name='objectChanged')\n\n def __init__(self, parent=None):\n super(ObjectWidget, self).__init__(parent)\n\n l_nbr_steps = QLabel(\"Nbr Steps \")\n self.nbr_steps = QSpinBox()\n self.nbr_steps.setMinimum(3)\n self.nbr_steps.setMaximum(100)\n self.nbr_steps.setValue(6)\n self.nbr_steps.valueChanged.connect(self.update_param)\n\n l_cmap = QLabel(\"Cmap \")\n self.cmap = sorted(get_colormaps().keys())\n self.combo = QComboBox(self)\n self.combo.addItems(self.cmap)\n self.combo.currentIndexChanged.connect(self.update_param)\n\n gbox = QGridLayout()\n gbox.addWidget(l_cmap, 0, 0)\n gbox.addWidget(self.combo, 0, 1)\n gbox.addWidget(l_nbr_steps, 1, 0)\n gbox.addWidget(self.nbr_steps, 1, 1)\n\n vbox = QVBoxLayout()\n vbox.addLayout(gbox)\n vbox.addStretch(1)\n\n self.setLayout(vbox)\n\n def update_param(self, option):\n self.signal_object_changed.emit()\n\n\nclass MainWindow(QMainWindow):\n\n def __init__(self):\n QMainWindow.__init__(self)\n\n self.resize(700, 500)\n self.setWindowTitle('vispy example ...')\n\n splitter = QSplitter(Qt.Horizontal)\n\n self.canvas = Canvas()\n self.canvas.create_native()\n self.canvas.native.setParent(self)\n\n self.props = ObjectWidget()\n splitter.addWidget(self.props)\n splitter.addWidget(self.canvas.native)\n\n self.setCentralWidget(splitter)\n self.props.signal_object_changed.connect(self.update_view)\n self.update_view()\n\n def update_view(self):\n # banded, nbr_steps, cmap\n self.canvas.set_data(self.props.nbr_steps.value(),\n self.props.combo.currentText())\n\n\nclass Canvas(scene.SceneCanvas):\n\n def __init__(self):\n scene.SceneCanvas.__init__(self, keys=None)\n self.size = 800, 600\n self.unfreeze()\n self.view = self.central_widget.add_view()\n self.radius = 2.0\n self.view.camera = 'turntable'\n mesh = create_sphere(20, 20, radius=self.radius)\n vertices = mesh.get_vertices()\n tris = mesh.get_faces()\n\n cl = np.linspace(-self.radius, self.radius, 6 + 2)[1:-1]\n\n self.iso = scene.visuals.Isoline(vertices=vertices, tris=tris,\n data=vertices[:, 2],\n levels=cl, color_lev='autumn',\n parent=self.view.scene)\n self.freeze()\n\n # Add a 3D axis to keep us oriented\n scene.visuals.XYZAxis(parent=self.view.scene)\n\n def set_data(self, n_levels, cmap):\n self.iso.set_color(cmap)\n cl = np.linspace(-self.radius, self.radius, n_levels + 2)[1:-1]\n self.iso.levels = cl\n\n\n# -----------------------------------------------------------------------------\nif __name__ == '__main__':\n win = MainWindow()\n win.show()\n app.run()\n",
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# vispy: gallery 2:20:2\n\"\"\"\nAnimate a Shape\n===============\n\nExample demonstrating showing a quad using\na Texture2D and VertexBuffer and a timer to control the drawing.\n\n\"\"\"\n\nimport time\nimport numpy as np\n\nfrom vispy import gloo\nfrom vispy import app\n\n\n# Create a texture\nim1 = np.zeros((100, 100, 3), 'float32')\nim1[:50, :, 0] = 1.0\nim1[:, :50, 1] = 1.0\nim1[50:, 50:, 2] = 1.0\n\n# Create vetices and texture coords, combined in one array for high performance\nvertex_data = np.zeros(4, dtype=[('a_position', np.float32, 3),\n ('a_texcoord', np.float32, 2)])\nvertex_data['a_position'] = np.array([[-0.8, -0.8, 0.0], [+0.7, -0.7, 0.0],\n [-0.7, +0.7, 0.0], [+0.8, +0.8, 0.0, ]])\nvertex_data['a_texcoord'] = np.array([[0.0, 0.0], [0.0, 1.0],\n [1.0, 0.0], [1.0, 1.0]])\n\n# Create indices and an ElementBuffer for it\nindices = np.array([0, 1, 2, 1, 2, 3], np.uint16)\nindices_buffer = gloo.IndexBuffer(indices)\nclient_indices_buffer = gloo.IndexBuffer(indices)\n\n\nVERT_SHADER = \"\"\" // simple vertex shader\n\nattribute vec3 a_position;\nattribute vec2 a_texcoord;\nuniform float sizeFactor;\n\nvoid main (void) {\n // Pass tex coords\n gl_TexCoord[0] = vec4(a_texcoord.x, a_texcoord.y, 0.0, 0.0);\n // Calculate position\n gl_Position = sizeFactor*vec4(a_position.x, a_position.y, a_position.z,\n 1.0/sizeFactor);\n}\n\"\"\"\n\nFRAG_SHADER = \"\"\" // simple fragment shader\nuniform sampler2D texture1;\n\nvoid main()\n{\n gl_FragColor = texture2D(texture1, gl_TexCoord[0].st);\n}\n\n\"\"\"\n\n\nclass Canvas(app.Canvas):\n\n def __init__(self):\n app.Canvas.__init__(self, keys='interactive')\n\n # Create program\n self._program = gloo.Program(VERT_SHADER, FRAG_SHADER)\n\n # Create vertex buffer\n self._vbo = gloo.VertexBuffer(vertex_data)\n\n # Set uniforms, samplers, attributes\n # We create one VBO with all vertex data (array of structures)\n # and create two views from it for the attributes.\n self._program['texture1'] = gloo.Texture2D(im1)\n self._program.bind(self._vbo) # This does:\n # self._program['a_position'] = self._vbo['a_position']\n # self._program['a_texcoords'] = self._vbo['a_texcoords']\n\n gloo.set_clear_color('white')\n\n self._timer = app.Timer('auto', connect=self.update, start=True)\n\n self.show()\n\n def on_resize(self, event):\n width, height = event.physical_size\n gloo.set_viewport(0, 0, width, height)\n\n def on_draw(self, event):\n\n # Clear\n gloo.clear()\n\n # Draw\n self._program['sizeFactor'] = 0.5 + np.sin(time.time() * 3) * 0.2\n\n # Draw (pick one!)\n # self._program.draw('triangle_strip')\n self._program.draw('triangles', indices_buffer)\n # self._program.draw('triangles', client_indices_buffer) # Not\n # recommended\n\n\nif __name__ == '__main__':\n canvas = Canvas()\n app.run()\n"
] |
[
[
"numpy.linspace"
],
[
"numpy.array",
"numpy.zeros"
]
] |
mike-gimelfarb/deep-successor-features-for-transfer
|
[
"42a547fdc6c9e34e2e92735d615cdb9db0059aee"
] |
[
"source/agents/sfql.py"
] |
[
"# -*- coding: UTF-8 -*-\nimport numpy as np\n\nfrom agents.agent import Agent\n\n\nclass SFQL(Agent):\n \n def __init__(self, lookup_table, *args, use_gpi=True, **kwargs):\n \"\"\"\n Creates a new tabular successor feature agent.\n \n Parameters\n ----------\n lookup_table : TabularSF\n a tabular successor feature representation\n use_gpi : boolean\n whether or not to use transfer learning (defaults to True)\n \"\"\"\n super(SFQL, self).__init__(*args, **kwargs)\n self.sf = lookup_table\n self.use_gpi = use_gpi\n \n def get_Q_values(self, s, s_enc):\n q, self.c = self.sf.GPI(s_enc, self.task_index, update_counters=self.use_gpi)\n if not self.use_gpi:\n self.c = self.task_index\n return q[:, self.c,:]\n \n def train_agent(self, s, s_enc, a, r, s1, s1_enc, gamma):\n \n # update w\n t = self.task_index\n phi = self.phi(s, a, s1)\n self.sf.update_reward(phi, r, t)\n \n # update SF for the current task t\n if self.use_gpi:\n q1, _ = self.sf.GPI(s1_enc, t)\n q1 = np.max(q1[0,:,:], axis=0)\n else:\n q1 = self.sf.GPE(s1_enc, t, t)[0,:]\n next_action = np.argmax(q1)\n transitions = [(s_enc, a, phi, s1_enc, next_action, gamma)]\n self.sf.update_successor(transitions, t)\n \n # update SF for source task c\n if self.c != t:\n q1 = self.sf.GPE(s1_enc, self.c, self.c)\n next_action = np.argmax(q1)\n transitions = [(s_enc, a, phi, s1_enc, next_action, gamma)]\n self.sf.update_successor(transitions, self.c)\n \n def reset(self):\n super(SFQL, self).reset()\n self.sf.reset()\n \n def add_training_task(self, task):\n super(SFQL, self).add_training_task(task)\n self.sf.add_training_task(task, -1)\n \n def get_progress_strings(self):\n sample_str, reward_str = super(SFQL, self).get_progress_strings()\n gpi_percent = self.sf.GPI_usage_percent(self.task_index)\n w_error = np.linalg.norm(self.sf.fit_w[self.task_index] - self.sf.true_w[self.task_index])\n gpi_str = 'GPI% \\t {:.4f} \\t w_err \\t {:.4f}'.format(gpi_percent, w_error)\n return sample_str, reward_str, gpi_str\n \n"
] |
[
[
"numpy.max",
"numpy.argmax",
"numpy.linalg.norm"
]
] |
ipc-sim/rigid-ipc
|
[
"d839af457236e7363b14c2e482a01d8160fa447e"
] |
[
"tools/fixtures/2D/generate_line_stack.py"
] |
[
"#!/usr/local/bin/python3\n\"\"\"Script to generate a fixture of a box falling on a saw.\"\"\"\n\nimport pathlib\n\nimport numpy\n\nfrom fixture_utils import *\n\n\ndef generate_fixture(args):\n \"\"\"Generate a fixture of a N boxes stacked on top of each other.\"\"\"\n fixture = generate_custom_fixture(args)\n rigid_bodies = fixture[\"rigid_body_problem\"][\"rigid_bodies\"]\n\n # Generate lines\n line = generate_box_body(5, args.thickness, [0, 0], 0, 1)\n delta_y = 0.5 + args.thickness\n y = -args.thickness / 2\n for i in range(args.num_lines):\n y += delta_y\n line[\"position\"] = [0, y]\n rigid_bodies.append(line.copy())\n\n # Add box falling\n y += 10\n box = generate_box_body(0.5, 0.5, [0, 0], 0, 100)\n box[\"position\"] = [0, y]\n box[\"theta\"] = 10 # °\n box[\"velocity\"] = [0, args.impact_velocity, 0]\n rigid_bodies.append(box)\n\n # Add the walls around line stack\n y += 2\n rigid_bodies.append(\n generate_walls_body(5.5, y / 2, numpy.array([0, y / 2]), 0.1))\n\n return fixture\n\n\ndef main():\n \"\"\"Parse command-line arguments to generate the desired fixture.\"\"\"\n parser = create_argument_parser(description=\"generate a stack of lines\",\n default_gravity=[0, 0, 0])\n parser.add_argument(\"--num-lines\",\n type=int,\n default=10,\n help=\"number of lines in the stack\")\n parser.add_argument(\"--thickness\",\n type=float,\n default=1e-2,\n help=\"thickness of each line\")\n parser.add_argument(\"--impact-velocity\",\n type=float,\n default=-100,\n help=\"thickness of each line\")\n args = parser.parse_args()\n\n if args.out_path is None:\n directory = (pathlib.Path(__file__).resolve().parents[1] / \"fixtures\" /\n \"stacking\")\n args.out_path = (\n directory /\n \"line-stack-num_line={:d}-thickness={:g}-v0={:g}.json\".format(\n args.num_lines, args.thickness, args.impact_velocity))\n args.out_path.parent.mkdir(parents=True, exist_ok=True)\n\n print_args(args)\n\n fixture = generate_fixture(args)\n\n save_fixture(fixture, args.out_path)\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"numpy.array"
]
] |
LinLearn/linlearn
|
[
"de5752d47bbe8e2fb62d41b0dcf2526f87545e1c"
] |
[
"linlearn/estimator/hg.py"
] |
[
"# Authors: Stephane Gaiffas <[email protected]>\n# Ibrahim Merad <[email protected]>\n# License: BSD 3 clause\n\n\nfrom collections import namedtuple\nimport numpy as np\nfrom numba import jit, prange\nfrom ._base import Estimator, jit_kwargs\nfrom .._utils import np_float\nfrom math import ceil\n\n\nStateHG = namedtuple(\n \"StateHG\",\n [\n \"sample_gradients\",\n \"gradient\",\n \"loss_derivative\",\n \"partial_derivative\",\n ],\n)\n\nC5 = 0.01\n@jit(**jit_kwargs)\ndef C(p):\n return C5\nprint(\"WARNING : importing implementation of outlier robust gradient by (Prasad et al.) with arbitrary constant C(p)=%.2f\"%C5)\n\n@jit(**jit_kwargs)\ndef SSI(samples, subset_cardinality):\n \"\"\"original name of this function is smallest_subset_interval\"\"\"\n if subset_cardinality < 2:\n raise ValueError(\"subset_cardinality must be at least 2\")\n elif subset_cardinality >= len(samples):\n return samples\n samples.sort()\n differences = samples[subset_cardinality - 1:] - samples[:-subset_cardinality + 1]\n argmin = np.argmin(differences)\n return samples[argmin:argmin + subset_cardinality]\n\n\n# @jit(\"float64[:,:](float64[:,:], float64, float64)\", **jit_kwargs)\n# def alg4(X, eps, delta=0.01):\n# # from Prasad et al. 2018\n# n, p = X.shape\n# if p == 1:\n# X_tilde = SSI(X.flatten(), max(2, ceil(n * (1 - eps - C5 * np.sqrt(np.log(n / delta) / n)) * (1 - eps))))\n# return X_tilde[:, np.newaxis]\n#\n# a = np.array([alg2(X[:, i:i + 1], eps, delta / p) for i in range(p)])\n# dists = ((X - a.reshape((1, p))) ** 2).sum(axis=1)\n# asort = np.argsort(dists)\n# X_tilde = X[asort[:ceil(n * (1 - eps - C(p) * np.sqrt(np.log(n / (p * delta)) * p / n)) * (1 - eps))], :]\n# return X_tilde\n\n\n#@jit(\"float64[:,:](float64[:,:], float64, float64)\", **jit_kwargs)\n@jit(**jit_kwargs)\ndef alg2(X, eps, delta=0.01):\n # from Prasad et al. 2018\n sc_prods = 0\n\n # X_tilde = alg4(X, eps, delta)\n n, p = X.shape\n if p == 1:\n X_tilde = SSI(X.flatten(), max(2, ceil(n * (1 - eps - C5 * np.sqrt(np.log(n / delta) / n)) * (1 - eps))))\n X_tilde = np.expand_dims(X_tilde, 1)# X_tilde[:, np.newaxis]\n else:\n\n a = np.array([alg2(X[:, i:i + 1], eps, delta / p).sum() for i in range(p)])\n dists = ((X - a.reshape((1, p))) ** 2).sum(axis=1)\n asort = np.argsort(dists)\n X_tilde = X[asort[:ceil(n * (1 - eps - C(p) * np.sqrt(np.log(n / (p * delta)) * p / n)) * (1 - eps))], :]\n\n\n n, p = X_tilde.shape\n\n if p == 1:\n return np.array([[np.mean(X_tilde)]])\n\n S = np.cov(X.T)\n\n _, V = np.linalg.eigh(S)\n PV = V[:, :p // 2]\n PW = PV @ PV.T\n\n est1 = np.expand_dims((X_tilde @ PW).sum(axis=0)/X_tilde.shape[0], 0)\n #est1 = np.mean(X_tilde @ PW, axis=0, keepdims=True)\n\n QV = V[:, p // 2:]\n est2 = alg2(X_tilde @ QV, eps, delta)\n est2 = QV.dot(est2.T)\n est2 = est2.reshape((1, p))\n est = est1 + est2\n\n return est\n\n\nclass HG(Estimator):\n def __init__(self, X, y, loss, n_classes, fit_intercept, delta=0.01, eps=0.01):\n super().__init__(X, y, loss, n_classes, fit_intercept)\n self.delta = delta\n self.eps = eps\n\n\n def get_state(self):\n return StateHG(\n sample_gradients=np.empty(\n (self.n_samples, self.n_features + int(self.fit_intercept), self.n_classes),\n dtype=np_float,\n ),\n gradient=np.empty(\n (self.n_features + int(self.fit_intercept), self.n_classes),\n dtype=np_float,\n ),\n loss_derivative=np.empty(self.n_classes, dtype=np_float),\n partial_derivative=np.empty(self.n_classes, dtype=np_float),\n )\n\n def partial_deriv_factory(self):\n raise ValueError(\n \"Hubergrad estimator does not support CGD, use mom estimator instead\"\n )\n\n def grad_factory(self):\n X = self.X\n y = self.y\n loss = self.loss\n deriv_loss = loss.deriv_factory()\n n_samples = self.n_samples\n n_classes = self.n_classes\n n_features = self.n_features\n eps = self.eps\n delta = self.delta\n\n if self.fit_intercept:\n\n @jit(**jit_kwargs)\n def grad(inner_products, state):\n gradient = state.gradient\n sample_gradients = state.sample_gradients\n deriv = state.loss_derivative\n for i in prange(n_samples):\n deriv_loss(y[i], inner_products[i], deriv)\n for k in range(n_classes):\n sample_gradients[i, 0, k] = deriv[k]\n for j in range(n_features):\n for k in range(n_classes):\n sample_gradients[i, j + 1, k] = X[i, j] * deriv[k]\n\n gradient[:] = alg2(sample_gradients.reshape((n_samples, -1)), 2*eps, delta).reshape((gradient.shape))\n return 0\n\n return grad\n else:\n\n @jit(**jit_kwargs)\n def grad(inner_products, state):\n\n gradient = state.gradient\n sample_gradients = state.sample_gradients\n deriv = state.loss_derivative\n for i in prange(n_samples):\n deriv_loss(y[i], inner_products[i], deriv)\n for j in range(n_features):\n for k in range(n_classes):\n sample_gradients[i, j, k] = X[i, j] * deriv[k]\n\n gradient[:] = alg2(sample_gradients.reshape((n_samples, -1)), 2*eps, delta).reshape((gradient.shape))\n return 0\n\n return grad\n"
] |
[
[
"numpy.log",
"numpy.expand_dims",
"numpy.linalg.eigh",
"numpy.cov",
"numpy.argmin",
"numpy.mean",
"numpy.argsort",
"numpy.empty"
]
] |
booltime/nlpaug
|
[
"d21e51bacd170dcd3dddfc34a401f0215f91dbf1"
] |
[
"nlpaug/util/visual/wave.py"
] |
[
"import matplotlib.pyplot as plt\nimport librosa.display\nimport numpy as np\n\n\nclass VisualWave:\n @staticmethod\n def visual(title, audio, sample_rate):\n plt.figure(figsize=(8, 4))\n librosa.display.waveplot(audio, sr=sample_rate)\n plt.title(title)\n plt.tight_layout()\n plt.show()\n"
] |
[
[
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.show",
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure"
]
] |
wk-atmchem/wk-atmchem.github.io
|
[
"f975126a98121203126f88ffd20c18b419bf101a"
] |
[
"python-scripts/plot4O3conc-CMAQ/CMAQproplot.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 3 17:14:54 2020\nRevised version of plotting CMAQ output from Stacy's script'\n@author: Kai Wu\nEmail:[email protected]\n\n\"\"\"\n\n# Libraries\n#--------------\nfrom matplotlib import pyplot as plt ; from matplotlib import colors\nimport numpy as np; import numpy.ma as ma; from matplotlib.patches import Path, PathPatch\nimport pandas as pd; from shapely.geometry import Point, shape, Polygon;import fiona\nfrom shapely.ops import unary_union, cascaded_union; from geopandas.tools import sjoin\nimport geopandas as gpd; import geoplot; import glob; import os; from datetime import timedelta, date;\nfrom netCDF4 import Dataset\nimport scipy.ndimage; from cartopy import crs as ccrs; import cartopy.io.shapereader as shpreader\nimport matplotlib.path as mpath; import seaborn as sns; import cartopy.feature as cfeature\nfrom cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter\nimport proplot as plot\nfrom cartopy.io.shapereader import Reader\n#------------------------------------------\n\n# dir to grid file\ndir='D:/Pythonstudy/grid/27kmchina/' \nll='GRIDCRO2D_2016362.nc' \n\n# dir to model files\ndir_files= 'D:/CMAQ/2017yearCMAQresults/'\n\n#pull files from given directoy\nonlyfiles = next(os.walk(dir_files))[2]\nonlyfiles=sorted(onlyfiles) # so that searching for dates are easier\n\n# pull only CONC files\nfnames = [x for x in onlyfiles if x.startswith(\"COMBINE_ACONC_2017-07-BASE\")]\nnumfiles=(len(fnames))\n\n# check the number of CONC files\nprint(\"the number of COMBINE_ACONC file is\",numfiles)\n\n#get lat lon from grid file\nll=Dataset(dir+ll,'r')\nlat,lon=ll['LAT'][:],ll['LON'][:]\n\n# check the longitude and latitude\n#print(lat,lon)\n\n#pull in files and variables\nncfile= [Dataset(dir_files+fnames[i],'r') for i in range(len(fnames))]\n\n\n#full day conc\nno2 = [np.average(ncfile[i]['NO2'][:],axis=0) for i in range(len(fnames))]\nno2_hourly=np.average(no2,axis=0)\n#hourly conc\n#daytime_hours = [12,13,14,15,16,17,18,19,20,21,22,23,1]\ndaytime_hours = [11,12,13,14,15,16]\nno2_daytime = [ncfile[i]['NO2'][daytime_hours[j]] for j in range(len(daytime_hours)) for i in range(len(fnames))]\nno2_daytime_avg = np.average(no2_daytime,axis=0)\n\nO3 = [np.average(ncfile[i]['O3'][:],axis=0) for i in range(len(fnames))]\nO3_hourly = np.average(O3,axis=0)\n#O3_hourly = [ncfile[i]['O3'][18] for i in range(len(fnames))]\nO3_daytime = [ncfile[i]['O3'][daytime_hours[j]] for j in range(len(daytime_hours)) for i in range(len(fnames))]\nO3_daytime_avg = np.average(O3_daytime,axis=0)\n\nCO = [np.average(ncfile[i]['CO'][:],axis=0) for i in range(len(fnames))]\nCO=np.average(CO,axis=0)\n\n\n# set var for plot\nvar='O3'\ndata=pd.DataFrame(O3_daytime_avg[0])*48/22.4\n#print(data)\n\n#==================================================\n#Set up for projections\ncrs_new = ccrs.PlateCarree(central_longitude=110.0, globe=None)\n#crs_new = ccrs.AlbersEqualArea(central_longitude=110.0, central_latitude=34, \n# false_easting=0.0, false_northing=0.0, \n# standard_parallels=(25.0, 40.0), globe=None)\n\n#crs_new = ccrs.LambertConformal(central_longitude=110.0, central_latitude=34.0, \n# false_easting=0.0, false_northing=0.0, \n# secant_latitudes=None, standard_parallels=(25.0, 40.0), \n# globe=None, cutoff=-30)\n\n# make fig object\nxmin = 70\nxmax = 136\nymin = 15\nymax = 55\n\nxstep = 10\nystep = 10\n\n\n# create your own colormap first\nir_br = plot.Colormap('spectral', name='ir_br',\n# save=True,\n )\n\n# set axis\nf, axs = plot.subplots(proj='pcarree')\n#f, axs = plot.subplots(projection=crs)\n\naxs.format(labels=True,\n lonlines=10,\n latlines=10,\n lonlim=(75, 135),\n latlim=(15, 55),\n geogridlinewidth=0.5)\n \n# lonlim=(lon.min(), lon.max()),\n# latlim=(lat.min(), lat.max()),\n\n# read the shapefile\nchina = shpreader.Reader('D:\\matlabshp\\cn_province.shp')\njs = shpreader.Reader('D:\\matlabshp\\cn_province.shp')\n\n\naxs.add_feature(cfeature.ShapelyFeature(china.geometries(), \n crs_new, \n facecolor='none', \n edgecolor='k',\n linewidth=1.5))\n\n\n# plot the map\ndef add_shape(source, projection):\n return cfeature.ShapelyFeature(Reader(source).geometries(),\n projection, facecolor='none')\n\ndef load_province(projection=ccrs.PlateCarree()):\n source = 'D:\\matlabshp\\cn_province.shp'\n return add_shape(source,projection)\n\n\nprovinces = load_province()\naxs.add_feature(provinces, edgecolor='k', linewidth=.3)\n\n# set levels\ncb_levels = plot.arange(0, 180, 20)\n\n# plot data\nm = axs.contourf(lon[0,0,...],lat[0,0,...], data,\n cmap=ir_br,\n vmin=0, vmax=180,\n levels=100)\n\n# set others\naxs.format(title='')\naxs.colorbar(m, loc='r', values=cb_levels, label='O3 concentration')\n\n\n\n\n# f.savefig('./figures/proplot_pcarree_levels.jpg')\nf.savefig(var+'daytime.png', dpi=600, bbox_inches='tight')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
] |
[
[
"numpy.average",
"pandas.DataFrame"
]
] |
mayanks888/mAP
|
[
"7e6a6c4b916223e737d30c76ebb11a75ed15d984"
] |
[
"scripts/extra/bdd_evaluation/json_to_csv_bdd.py"
] |
[
"import json\nimport os\n\nimport cv2\nimport pandas as pd\n\nfilename = []\nwidth = []\nheight = []\nClass = []\nxmin = []\nymin = []\nxmax = []\nymax = []\nlight_color = []\na = []\nfile_number = 0\n# classes=['bus','light','traffic_sign','person','bike','truck','motor','car','train','Rider']\nclasses=['bus','light','traffic light','person','bike','truck','motor','car','train','Rider',\"traffic sign\"]\n# classes = ['traffic light']\nbblabel = []\nloop = 0\n# jason_path=\"/home/mayank_s/codebase/others/centernet/mayank/CenterNet/exp/ctdet/default/results.json\"\njason_path = \"/home/mayank_s/datasets/bdd/bdd100k_labels_release/bdd100k/labels/bdd100k_labels_images_val.json\"\nimage_path = \"/home/mayank_s/datasets/bdd/bdd100k_images/bdd100k/images/100k/val\"\n\nif 1:\n data = open(jason_path, 'r')\n data1 = data.read()\n data.close()\n Json = json.loads(data1)\n # filename.append(Json['name'])\n # for obj in root.iter('object'):\n # for ki in Json['frames'][0]['objects']:\n for ki in Json:\n loop += 1\n # print(\"count run\", loop)\n # object_name=ki['category']\n file_name = ki['name']\n # ________________________________________________________________________\n Image_com_path = os.path.join(image_path, file_name)\n exists = os.path.isfile(Image_com_path)\n if exists:\n # if image_name.split('.')==k.split('.'):\n my_image = cv2.imread(Image_com_path, 1)\n # _______________________________________________________________________\n\n for dat_obj in ki['labels']:\n object_name = dat_obj['category']\n\n # if ki['attributes']['timeofday'] == \"daytime\":\n if object_name in classes:\n light_color = ki['labels'][0]['attributes']['trafficLightColor']\n xmin = int(dat_obj['box2d']['x1'])\n xmax = int(dat_obj['box2d']['x2'])\n ymin = int(dat_obj['box2d']['y1'])\n ymax = int(dat_obj['box2d']['y2'])\n width = my_image.shape[1]\n height = my_image.shape[0]\n # coordinate = [xmin, ymin, xmax, ymax, class_num]\n # object_name=object_name+\"_\"+light_color\n # object_name = \"traffic_light\"\n data_label = [file_name, width, height, object_name, xmin, ymin, xmax, ymax]\n # data_label = [file_name, width, height, object_name, xmin, ymin, xmax, ymax]\n if not ((xmin == xmax) and (ymin == ymax)):\n bblabel.append(data_label)\n print(file_name)\n # print()\n else:\n print(\"file_name\")\n # except IOError:\n # print(\"error at loop:{lp} and image:{dt}\".format(lp=loop,dt=dat))\n # print('error1')\n # except:\n # print(\"error at loop:{lp} and image:{dt}\".format(lp=loop, dt=dat))\n # print('error2')\n # # print('ERROR...object detecion failed for Filename: {fn} , Check file type '.format(fn=filename), '\\n')\n # else:\n # print(\"successfull for \", dat)\n\ncolumns = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax']\n\n# pd1=pd.DataFrame(a,columns=columns)\n# df=pd.DataFrame(bblabel)\n# df.to_csv('out.csv')\n# pd1.to_csv('output_bb.csv')\n\ndf = pd.DataFrame(bblabel, columns=columns)\ndf.to_csv('BBD_groundtruth_val.csv',index=False)\n"
] |
[
[
"pandas.DataFrame"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.