repo_name
stringlengths 6
130
| hexsha
sequence | file_path
sequence | code
sequence | apis
sequence | possible_versions
list |
---|---|---|---|---|---|
young24/LFP-simulation-in-turtle-brain | [
"cd801dc02804d027b7c245b0f0ca9c8b00f8d450",
"cd801dc02804d027b7c245b0f0ca9c8b00f8d450"
] | [
"simulation-code/old_functions/average_rotated_trials.py",
"simulation-code/old_functions/Main_Sim_with_Kernel.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 12 09:12:00 2016\nAverage the spatial influence of the morphology\n@author: young\n\"\"\"\nimport os\nfrom os.path import join\nimport pylab as plt\nimport numpy as np\n\ndef average_data_in_dif_folder(dirName,dataName,z_pos,numRotation,idxSection):\n yfileName = dirName+'_0/'+dataName+str(z_pos)+'.npy'\n y=np.load(yfileName)\n y=y[idxSection]\n for i in range(1,numRotation,1):\n yfileName = dirName+'_'+str(i)+'/'+dataName+str(z_pos)+'.npy'\n temp_y = np.load(yfileName)\n temp_y = temp_y[idxSection]\n y = y + temp_y\n y = y/numRotation\n return y\n \nif __name__ == '__main__':\n\n numRotation = 8\n \n dirName = 'sim_results'\n xfileName = dirName+'_0/'+'tvec.npy'\n x=np.load(xfileName)\n \n fig = plt.figure(figsize=[10, 10])\n # Extracellular_potential\n ax1 = plt.subplot(311, ylabel='$\\mu$V',\n title='Extracellular\\npotential')\n # share x only\n ax2 = plt.subplot(312, sharex=ax1, ylabel='mV',\n title='Membrane potential')\n ax3 = plt.subplot(313, sharex=ax1, xlabel='ms', ylabel='nA',\n title='Return currents')\n \n legendList = []\n for z_pos in range(20,301,10):\n legendList.append('z:'+str(z_pos)+'$\\mu$m')\n \n dataName='phi_z'\n y1 = average_data_in_dif_folder(dirName,dataName,z_pos,numRotation,idxSection=2) # centre electrode\n ax1.plot(x, y1)\n dataName='phi_z'+str(z_pos)+'.npy'\n np.save(join('averaged_result_for_real_neuron', dataName), y1)\n \n dataName='vmem_z'\n y2 = average_data_in_dif_folder(dirName,dataName,z_pos,numRotation,idxSection=0) # soma index = 0\n ax2.plot(x, y2)\n dataName='vmem_z'+str(z_pos)+'.npy'\n np.save(join('averaged_result_for_real_neuron', dataName), y2)\n \n dataName='imem_z'\n y3 = average_data_in_dif_folder(dirName,dataName,z_pos,numRotation,idxSection=0)\n ax3.plot(x, y3)\n dataName='imem_z'+str(z_pos)+'.npy'\n np.save(join('averaged_result_for_real_neuron', dataName), y3)\n \n plt.legend(legendList, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n plt.savefig('averaged_z_profile', bbox_inches='tight')\n\n ",
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 08 13:46:08 2016\nMain_Sim_with_Kernel\n@author: superuser\n\"\"\"\nimport os\nfrom os.path import join\nimport time\nimport multiprocessing\nimport numpy as np\nfrom scipy.interpolate import RegularGridInterpolator\n\ndef make_2D_to_3D(data,xLen,yLen):\n 'make linear xy index into 2d index'\n data3D = np.zeros((xLen,yLen,np.shape(data)[1]))\n for x in range(0,xLen):\n for y in range(0,yLen):\n data3D[x,y,:] = data[x*yLen+y,:]\n return data3D\n \ndef calc_LFP(t):\n print(t) # show the progress\n xLen = 11\n yLen = 11\n lengthMEA = 500\n zMin = -110\n zMax = 220\n zShift = 20 # z shift between stimulated neuron and cell layer\n x = np.linspace(-lengthMEA,lengthMEA,xLen)\n y = np.linspace(-lengthMEA,lengthMEA,yLen)\n z = np.linspace(zMin,zMax,34)\n \n kernelData = np.load('../Data/Python/kernelData_soma_z120.npy')\n axonSyn = np.load('../Data/Python/axonSyn.npy')\n \n LFPonMEA = np.zeros((xLen,yLen))\n data = kernelData[:,t,:]\n data3D = make_2D_to_3D(data,xLen,yLen)\n LFP = RegularGridInterpolator((x, y, z), data3D)\n \n interval = 100\n for x_idx in range(0,xLen):\n for y_idx in range(0,yLen):\n sumLFP = 0\n for pos in axonSyn:\n if (-lengthMEA<=((x_idx-(xLen-1)/2)*interval-pos[0])<=lengthMEA and\n -lengthMEA<=((y_idx-(xLen-1)/2)*interval-pos[1])<=lengthMEA and\n zMin<=pos[2]-zShift<=zMax): \n sumLFP += LFP([(x_idx-(xLen-1)/2)*interval-pos[0],\n (y_idx-(yLen-1)/2)*interval-pos[1],pos[2]-zShift])\n LFPonMEA[x_idx,y_idx] = sumLFP\n folder = 'LFPonMEA'\n if not os.path.isdir(folder):\n os.mkdir(folder)\n np.save(join(folder, 'LFPonMEAt'+str(t)+'.npy'),LFPonMEA)\n \ndef make_files_together(xLen,yLen):\n 'stack different time files into a single file'\n LFPonMEA = np.zeros((xLen,yLen,401))\n for t in range(0,401):\n LFPonMEA[:,:,t] = np.load('LFPonMEA/LFPonMEAt'+str(t)+'.npy')\n \n return LFPonMEA\n \n\nif __name__ == '__main__':\n start = time.time()\n pool = multiprocessing.Pool(processes=4)\n \n t = range(0,401)\n pool.map(calc_LFP, t)\n \n pool.close()\n pool.join()\n \n xLen = 11 # keep consistent with before ones\n yLen = 11\n LFPonMEA = make_files_together(xLen,yLen)\n np.save('LFPonMEA.npy',LFPonMEA)\n \n \n end = time.time()\n print(end-start)\n\n \n "
] | [
[
"numpy.load"
],
[
"numpy.linspace",
"scipy.interpolate.RegularGridInterpolator",
"numpy.save",
"numpy.shape",
"numpy.load",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.14",
"1.6",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
KDDComplexNetworkAnalysis/ndlib | [
"2d05df8cd67de142ef068cc051969f86e51dfbc6"
] | [
"ndlib/test/test_ndlib.py"
] | [
"from __future__ import absolute_import\n\nimport unittest\nimport random\nimport future.utils\nimport networkx as nx\nimport igraph as ig\nimport numpy as np\n\nimport ndlib.models.ModelConfig as mc\nimport ndlib.models.epidemics as epd\nimport ndlib.models.opinions as opn\nimport ndlib.utils as ut\n\n__author__ = 'Giulio Rossetti'\n__license__ = \"BSD-2-Clause\"\n__email__ = \"[email protected]\"\n\n\ndef get_graph(er=False):\n if not er:\n g = nx.complete_graph(100)\n else:\n g = nx.erdos_renyi_graph(1000, 0.1)\n gi = ig.Graph(directed=False)\n gi.add_vertices(list(g.nodes()))\n gi.add_edges(list(g.edges()))\n gs = [g, gi]\n return gs\n\n\ndef get_directed_graph(er=False):\n if not er:\n g = nx.complete_graph(100)\n else:\n g = nx.erdos_renyi_graph(1000, 0.1)\n g = g.to_directed()\n gi = ig.Graph(directed=True)\n gi.add_vertices(list(g.nodes()))\n gi.add_edges(list(g.edges()))\n gs = [g, gi]\n return gs\n\n\nclass NdlibTest(unittest.TestCase):\n\n def test_utldr(self):\n for g in get_graph():\n model = epd.UTLDRModel(g)\n config = mc.Configuration()\n\n # Undetected\n config.add_model_parameter(\"sigma\", 0.05)\n config.add_model_parameter(\"beta\", {\"M\": 0.25, \"F\": 0})\n config.add_model_parameter(\"gamma\", 0.05)\n config.add_model_parameter(\"omega\", 0.01)\n config.add_model_parameter(\"p\", 0.04)\n config.add_model_parameter(\"lsize\", 0.2)\n\n # Testing\n config.add_model_parameter(\"phi_e\", 0.03)\n config.add_model_parameter(\"phi_i\", 0.1)\n config.add_model_parameter(\"kappa_e\", 0.03)\n config.add_model_parameter(\"kappa_i\", 0.1)\n config.add_model_parameter(\"gamma_t\", 0.08)\n config.add_model_parameter(\"gamma_f\", 0.1)\n config.add_model_parameter(\"omega_t\", 0.01)\n config.add_model_parameter(\"omega_f\", 0.08)\n config.add_model_parameter(\"epsilon_e\", 1)\n config.add_model_parameter(\"icu_b\", 10)\n config.add_model_parameter(\"iota\", 0.20)\n config.add_model_parameter(\"z\", 0.2)\n config.add_model_parameter(\"s\", 0.05)\n\n # Lockdown\n config.add_model_parameter(\"lambda\", 0.8)\n config.add_model_parameter(\"epsilon_l\", 5)\n config.add_model_parameter(\"mu\", 0.05)\n config.add_model_parameter(\"p_l\", 0.04)\n\n # Vaccination\n config.add_model_parameter(\"v\", 0.15)\n config.add_model_parameter(\"f\", 0.02)\n\n # node activity level\n if isinstance(g, nx.Graph):\n nodes = g.nodes\n else:\n nodes = g.vs['name']\n\n ngender = ['M', 'F']\n work = ['school', 'PA', 'hospital', 'none']\n for i in nodes:\n config.add_node_configuration(\"activity\", i, 1)\n config.add_node_configuration(\"work\", i, np.random.choice(work, 2))\n config.add_node_configuration(\"segment\", i, np.random.choice(ngender, 1)[0])\n\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n households = {0: [1, 2, 3, 4], 5: [6, 7]}\n\n model.set_lockdown(households, ['PA', 'school'])\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n model.unset_lockdown(['PA'])\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n model.set_lockdown(households)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n model.unset_lockdown(['school'])\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_algorithmic_bias_model(self):\n\n for g in get_graph():\n model = opn.AlgorithmicBiasModel(g, seed=0)\n config = mc.Configuration()\n config.add_model_parameter(\"epsilon\", 0.32)\n config.add_model_parameter(\"gamma\", 1)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_voter_model(self):\n for g in get_graph():\n model = opn.VoterModel(g, seed=0)\n config = mc.Configuration()\n config.add_model_parameter(\"fraction_infected\", 0.2)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_sznajd_model(self):\n for g in get_graph():\n model = opn.SznajdModel(g)\n config = mc.Configuration()\n config.add_model_parameter(\"fraction_infected\", 0.2)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n\n for g in get_directed_graph():\n model = opn.SznajdModel(g)\n config = mc.Configuration()\n config.add_model_parameter(\"fraction_infected\", 0.2)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_majorityrule_model(self):\n for g in get_graph():\n model = opn.MajorityRuleModel(g)\n config = mc.Configuration()\n config.add_model_parameter(\"q\", 3)\n config.add_model_parameter(\"fraction_infected\", 0.2)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_qvoter_model(self):\n for g in get_graph():\n model = opn.QVoterModel(g)\n config = mc.Configuration()\n config.add_model_parameter(\"q\", 5)\n config.add_model_parameter(\"fraction_infected\", 0.6)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_cognitive_model(self):\n for g in get_graph():\n model = opn.CognitiveOpDynModel(g, seed=0)\n config = mc.Configuration()\n config.add_model_parameter(\"I\", 0.15)\n config.add_model_parameter(\"B_range_min\", 0)\n config.add_model_parameter(\"B_range_max\", 1)\n config.add_model_parameter(\"T_range_min\", 0)\n config.add_model_parameter(\"T_range_max\", 1)\n config.add_model_parameter(\"R_fraction_negative\", 1.0 / 3)\n config.add_model_parameter(\"R_fraction_neutral\", 1.0 / 3)\n config.add_model_parameter(\"R_fraction_positive\", 1.0 / 3)\n model.set_initial_status(config)\n\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_si_model(self):\n for g in get_graph(True):\n model = epd.SIModel(g)\n config = mc.Configuration()\n config.add_model_parameter('beta', 0.5)\n config.add_model_parameter(\"fraction_infected\", 0.1)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_sir_model(self):\n for g in get_graph(True):\n model = epd.SIRModel(g)\n config = mc.Configuration()\n config.add_model_parameter('beta', 0.5)\n config.add_model_parameter('gamma', 0.2)\n config.add_model_parameter(\"percentage_infected\", 0.1)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_seir_model(self):\n\n for g in get_graph(True):\n model = epd.SEIRModel(g)\n config = mc.Configuration()\n config.add_model_parameter('beta', 0.5)\n config.add_model_parameter('gamma', 0.2)\n config.add_model_parameter('alpha', 0.05)\n config.add_model_parameter(\"fraction_infected\", 0.1)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n\n for g in get_directed_graph(True):\n model = epd.SEIRModel(g)\n config = mc.Configuration()\n config.add_model_parameter('beta', 0.5)\n config.add_model_parameter('gamma', 0.8)\n config.add_model_parameter('alpha', 0.5)\n config.add_model_parameter(\"fraction_infected\", 0.1)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_seirct_model(self):\n\n for g in get_graph(True):\n model = epd.SEIRctModel(g)\n config = mc.Configuration()\n config.add_model_parameter('beta', 0.5)\n config.add_model_parameter('gamma', 0.2)\n config.add_model_parameter('alpha', 0.05)\n config.add_model_parameter(\"fraction_infected\", 0.1)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n\n for g in get_directed_graph(True):\n model = epd.SEIRctModel(g)\n config = mc.Configuration()\n config.add_model_parameter('beta', 0.5)\n config.add_model_parameter('gamma', 0.8)\n config.add_model_parameter('alpha', 0.5)\n config.add_model_parameter(\"fraction_infected\", 0.1)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_swir_model(self):\n for g in get_graph(True):\n model = epd.SWIRModel(g)\n config = mc.Configuration()\n config.add_model_parameter('kappa', 0.5)\n config.add_model_parameter('mu', 0.2)\n config.add_model_parameter('nu', 0.05)\n config.add_model_parameter(\"fraction_infected\", 0.1)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n\n def test_seis_model(self):\n for g in get_graph(True):\n model = epd.SEISModel(g)\n config = mc.Configuration()\n config.add_model_parameter('beta', 0.5)\n config.add_model_parameter('lambda', 0.2)\n config.add_model_parameter('alpha', 0.05)\n config.add_model_parameter(\"fraction_infected\", 0.1)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n\n for g in get_directed_graph(True):\n model = epd.SEISModel(g)\n config = mc.Configuration()\n config.add_model_parameter('beta', 0.5)\n config.add_model_parameter('lambda', 0.8)\n config.add_model_parameter('alpha', 0.5)\n config.add_model_parameter(\"fraction_infected\", 0.1)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_seis_model(self):\n for g in get_graph(True):\n model = epd.SEISctModel(g)\n config = mc.Configuration()\n config.add_model_parameter('beta', 0.5)\n config.add_model_parameter('lambda', 0.2)\n config.add_model_parameter('alpha', 0.05)\n config.add_model_parameter(\"fraction_infected\", 0.1)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n\n for g in get_directed_graph(True):\n model = epd.SEISctModel(g)\n config = mc.Configuration()\n config.add_model_parameter('beta', 0.5)\n config.add_model_parameter('lambda', 0.8)\n config.add_model_parameter('alpha', 0.5)\n config.add_model_parameter(\"fraction_infected\", 0.1)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_sis_model(self):\n for g in get_graph(True):\n model = epd.SISModel(g)\n config = mc.Configuration()\n config.add_model_parameter('beta', 0.5)\n config.add_model_parameter('lambda', 0.2)\n config.add_model_parameter(\"fraction_infected\", 0.1)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_kertesz_model(self):\n for g in get_graph():\n model = epd.KerteszThresholdModel(g)\n config = mc.Configuration()\n config.add_model_parameter('adopter_rate', 0.4)\n config.add_model_parameter('percentage_blocked', 0.1)\n config.add_model_parameter('fraction_infected', 0.1)\n\n threshold = 0.2\n if isinstance(g, nx.Graph):\n nodes = g.nodes\n else:\n nodes = g.vs['name']\n for i in nodes:\n config.add_node_configuration(\"threshold\", i, threshold)\n\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_multiple_si_model(self):\n for g in get_graph(True):\n model = epd.SIModel(g)\n config = mc.Configuration()\n config.add_model_parameter('beta', 0.01)\n config.add_model_parameter(\"fraction_infected\", 0.1)\n model.set_initial_status(config)\n executions = ut.multi_runs(model, execution_number=10, iteration_number=50)\n self.assertEqual(len(executions), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_threshold_model(self):\n for g in get_graph(True):\n model = epd.ThresholdModel(g)\n config = mc.Configuration()\n config.add_model_parameter('fraction_infected', 0.1)\n\n threshold = 0.2\n if isinstance(g, nx.Graph):\n nodes = g.nodes\n else:\n nodes = g.vs['name']\n for i in nodes:\n config.add_node_configuration(\"threshold\", i, threshold)\n\n \n\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_generalisedthreshold_model(self):\n for g in get_graph(True):\n model = epd.GeneralisedThresholdModel(g)\n config = mc.Configuration()\n config.add_model_parameter('fraction_infected', 0.1)\n config.add_model_parameter('tau', 5)\n config.add_model_parameter('mu', 5)\n\n threshold = 0.2\n if isinstance(g, nx.Graph):\n nodes = g.nodes\n else:\n nodes = g.vs['name']\n for i in nodes:\n config.add_node_configuration(\"threshold\", i, threshold)\n model.set_initial_status(config)\n\n iterations = model.iteration_bunch(50)\n self.assertEqual(len(iterations), 50)\n iterations = model.iteration_bunch(50, node_status=False)\n self.assertEqual(len(iterations), 50)\n\n\n def test_GeneralThresholdModel(self):\n for g in get_graph(True):\n model = epd.GeneralThresholdModel(g)\n config = mc.Configuration()\n config.add_model_parameter('fraction_infected', 0.1)\n\n threshold = 0.2\n weight = 0.2\n if isinstance(g, nx.Graph):\n nodes = g.nodes\n edges = g.edges\n else:\n nodes = g.vs['name']\n edges = [(g.vs[e.tuple[0]]['name'], g.vs[e.tuple[1]]['name']) for e in g.es]\n\n\n for i in nodes:\n config.add_node_configuration(\"threshold\", i, threshold)\n for e in edges:\n config.add_edge_configuration(\"weight\", e, weight)\n\n\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n\n def test_profile_threshold_model(self):\n for g in get_graph(True):\n model = epd.ProfileThresholdModel(g)\n config = mc.Configuration()\n config.add_model_parameter('percentage_infected', 0.1)\n\n threshold = 0.2\n profile = 0.1\n if isinstance(g, nx.Graph):\n nodes = g.nodes\n else:\n nodes = g.vs['name']\n for i in nodes:\n config.add_node_configuration(\"threshold\", i, threshold)\n config.add_node_configuration(\"profile\", i, profile)\n\n model.set_initial_status(config)\n\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n\n model = epd.ProfileThresholdModel(g)\n config = mc.Configuration()\n config.add_model_parameter('percentage_infected', 0.1)\n config.add_model_parameter(\"blocked\", 0.1)\n config.add_model_parameter(\"adopter_rate\", 0.001)\n\n threshold = 0.2\n profile = 0.1\n if isinstance(g, nx.Graph):\n nodes = g.nodes\n else:\n nodes = g.vs['name']\n for i in nodes:\n config.add_node_configuration(\"threshold\", i, threshold)\n config.add_node_configuration(\"profile\", i, profile)\n\n model.set_initial_status(config)\n\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_profile_model(self):\n for g in get_graph(True):\n model = epd.ProfileModel(g)\n config = mc.Configuration()\n config.add_model_parameter('fraction_infected', 0.1)\n\n profile = 0.1\n if isinstance(g, nx.Graph):\n nodes = g.nodes\n else:\n nodes = g.vs['name']\n for i in nodes:\n config.add_node_configuration(\"profile\", i, profile)\n\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n\n model = epd.ProfileModel(g)\n config = mc.Configuration()\n config.add_model_parameter('fraction_infected', 0.1)\n config.add_model_parameter(\"blocked\", 0.1)\n config.add_model_parameter(\"adopter_rate\", 0.001)\n\n profile = 0.1\n if isinstance(g, nx.Graph):\n nodes = g.nodes\n else:\n nodes = g.vs['name']\n for i in nodes:\n config.add_node_configuration(\"profile\", i, profile)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_independent_cascade_model(self):\n\n for g in get_graph(True):\n model = epd.IndependentCascadesModel(g)\n config = mc.Configuration()\n config.add_model_parameter('percentage_infected', 0.1)\n threshold = 0.1\n\n if isinstance(g, nx.Graph):\n for e in g.edges:\n config.add_edge_configuration(\"threshold\", e, threshold)\n else:\n edges = [(g.vs[e.tuple[0]]['name'], g.vs[e.tuple[1]]['name']) for e in g.es]\n for e in edges:\n config.add_edge_configuration(\"threshold\", e, threshold)\n\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_ICE(self):\n for g in get_graph(True):\n model = epd.ICEModel(g)\n config = mc.Configuration()\n config.add_model_parameter('percentage_infected', 0.1)\n if isinstance(g, nx.Graph):\n node_to_com = {n: random.choice([0, 1])for n in g.nodes()}\n for i in g.nodes():\n config.add_node_configuration(\"com\", i, node_to_com[i])\n else:\n node_to_com = {n: random.choice([0, 1]) for n in g.vs['name']}\n for i in g.vs['name']:\n config.add_node_configuration(\"com\", i, node_to_com[i])\n\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_ICP(self):\n\n threshold = 0.1\n\n for g in get_graph(True):\n model = epd.ICPModel(g)\n config = mc.Configuration()\n config.add_model_parameter('percentage_infected', 0.1)\n if isinstance(g, nx.Graph):\n node_to_com = {n: random.choice([0, 1])for n in g.nodes()}\n for i in g.nodes():\n config.add_node_configuration(\"com\", i, node_to_com[i])\n for e in g.edges:\n config.add_edge_configuration(\"threshold\", e, threshold)\n else:\n node_to_com = {n: random.choice([0, 1]) for n in g.vs['name']}\n for i in g.vs['name']:\n config.add_node_configuration(\"com\", i, node_to_com[i])\n edges = [(g.vs[e.tuple[0]]['name'], g.vs[e.tuple[1]]['name']) for e in g.es]\n for e in edges:\n config.add_edge_configuration(\"threshold\", e, threshold)\n\n config.add_model_parameter('permeability', 0.1)\n\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n\n def test_ICEP(self):\n\n\n for g in get_graph(True):\n model = epd.ICEPModel(g)\n config = mc.Configuration()\n config.add_model_parameter('percentage_infected', 0.1)\n if isinstance(g, nx.Graph):\n node_to_com = {n: random.choice([0, 1])for n in g.nodes()}\n for i in g.nodes():\n config.add_node_configuration(\"com\", i, node_to_com[i])\n else:\n node_to_com = {n: random.choice([0, 1]) for n in g.vs['name']}\n for i in g.vs['name']:\n config.add_node_configuration(\"com\", i, node_to_com[i])\n\n\n config.add_model_parameter('permeability', 0.1)\n\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n iterations = model.iteration_bunch(10, node_status=False)\n self.assertEqual(len(iterations), 10)\n\n def test_kertesz_model_predefined_blocked(self):\n for g in get_graph(True):\n model = epd.KerteszThresholdModel(g)\n config = mc.Configuration()\n config.add_model_parameter('adopter_rate', 0.4)\n predefined_blocked = [0, 1, 2, 3, 4, 5]\n config.add_model_initial_configuration(\"Blocked\", predefined_blocked)\n config.add_model_parameter('percentage_infected', 0.1)\n\n threshold = 0.2\n if isinstance(g, nx.Graph):\n nodes = g.nodes\n else:\n nodes = g.vs['name']\n for i in nodes:\n config.add_node_configuration(\"threshold\", i, threshold)\n\n model.set_initial_status(config)\n iteration = model.iteration()\n blocked = [x for x, v in future.utils.iteritems(iteration['status']) if v == -1]\n self.assertEqual(blocked, predefined_blocked)\n\n def test_initial_infected(self):\n for g in get_graph(True):\n model = epd.SISModel(g)\n config = mc.Configuration()\n config.add_model_parameter('beta', 0.5)\n config.add_model_parameter('lambda', 0.2)\n predefined_infected = [0, 1, 2, 3, 4, 5]\n config.add_model_initial_configuration(\"Infected\", predefined_infected)\n model.set_initial_status(config)\n inft = [k for k, v in future.utils.iteritems(model.status) if v == 1]\n self.assertAlmostEqual(inft, predefined_infected)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n\n def test_optional_parameters(self):\n\n for g in get_graph(True):\n model = epd.ThresholdModel(g)\n config = mc.Configuration()\n config.add_model_parameter('fraction_infected', 0.1)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n if isinstance(g, nx.Graph):\n config.add_node_set_configuration(\"test\", {n: 1 for n in g.nodes})\n config.add_edge_set_configuration(\"etest\", {e: 1 for e in g.edges})\n else:\n config.add_node_set_configuration(\"test\", {n: 1 for n in g.vs['name']})\n edges = [(g.vs[e.tuple[0]]['name'], g.vs[e.tuple[1]]['name']) for e in g.es]\n config.add_edge_set_configuration(\"etest\", {e: 1 for e in edges})\n\n self.assertEqual(len(iterations), 10)\n\n model = epd.KerteszThresholdModel(g)\n config = mc.Configuration()\n config.add_model_parameter('adopter_rate', 0.4)\n predefined_blocked = [0, 1, 2, 3, 4, 5]\n config.add_model_initial_configuration(\"Blocked\", predefined_blocked)\n config.add_model_parameter('percentage_infected', 0.1)\n model.set_initial_status(config)\n iteration = model.iteration()\n blocked = [x for x, v in future.utils.iteritems(iteration[\"status\"]) if v == -1]\n self.assertEqual(blocked, predefined_blocked)\n\n model = epd.IndependentCascadesModel(g)\n config = mc.Configuration()\n config.add_model_parameter('percentage_infected', 0.1)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n\n model = epd.ProfileModel(g)\n config = mc.Configuration()\n config.add_model_parameter('percentage_infected', 0.1)\n\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n\n model = epd.ProfileThresholdModel(g)\n config = mc.Configuration()\n config.add_model_parameter('fraction_infected', 0.1)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n\n model = epd.ThresholdModel(g)\n config = mc.Configuration()\n config.add_model_parameter('fraction_infected', 0.1)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n\n model = epd.KerteszThresholdModel(g)\n config = mc.Configuration()\n config.add_model_parameter('adopter_rate', 0.4)\n config.add_model_parameter('percentage_blocked', 0.1)\n config.add_model_parameter('fraction_infected', 0.1)\n model.set_initial_status(config)\n iterations = model.iteration_bunch(10)\n self.assertEqual(len(iterations), 10)\n\n def test_config(self):\n for g in get_graph(True):\n model = epd.ThresholdModel(g)\n config = mc.Configuration()\n config.add_model_parameter('fraction_infected', 0.1)\n config.add_model_initial_configuration(\"Infected\", [1, 2, 3])\n config.add_node_set_configuration(\"partial\", {1: 1, 2: 2})\n try:\n model.set_initial_status(config)\n except:\n pass\n\n if isinstance(g, nx.Graph):\n edges = list(g.edges)\n nodes = list(g.nodes)\n else:\n edges = [(g.vs[e.tuple[0]]['name'], g.vs[e.tuple[1]]['name']) for e in g.es]\n nodes = g.vs['name']\n\n config.add_edge_set_configuration(\"partial\", {e: 1 for e in edges[:10]})\n try:\n model.set_initial_status(config)\n except:\n pass\n\n config.add_node_set_configuration(\"partial\", {n: 1 for n in nodes})\n config.add_edge_set_configuration(\"partial\", {e: 1 for e in edges})\n model.set_initial_status(config)\n\n for g in get_graph():\n model = opn.MajorityRuleModel(g)\n config = mc.Configuration()\n config.add_model_parameter(\"percentage_infected\", 0.2)\n try:\n model.set_initial_status(config)\n except:\n pass\n\n for g in get_graph(True):\n model = epd.IndependentCascadesModel(g)\n config = mc.Configuration()\n config.add_model_parameter('percentage_infected', 0.1)\n try:\n model.set_initial_status(config)\n except:\n pass\n\n for g in get_graph(True):\n model = epd.ThresholdModel(g)\n config = mc.Configuration()\n config.add_model_parameter('percentage_infected', 0.1)\n try:\n model.set_initial_status(config)\n except:\n pass\n"
] | [
[
"numpy.random.choice"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
H0R4T1U/SRI | [
"ed0891c595551929ce649b38f722ed2a8b7a696d"
] | [
"Service/website_service.py"
] | [
"from selenium import webdriver\nfrom bs4 import BeautifulSoup\nimport pandas as pd\n\nfrom Domain.website import Website\nfrom selenium.webdriver.firefox.options import Options\n\nfrom Repository.file_repository import FileRepository\n\n\nclass WebsiteService:\n def __init__(self, website_repository: FileRepository):\n self.__website_repository = website_repository\n\n def get_all(self):\n return self.__website_repository.get_all()\n\n def add(self,name, url, container_class, classes):\n website = Website(name,url, container_class, classes)\n self.__website_repository.add(website)\n\n def get_files_from_file(self):\n self.__website_repository.read_file()\n\n def scrap(self):\n options = Options()\n options.headless = True\n\n driver = webdriver.Firefox(options=options)\n\n websites = self.get_all()\n for website in websites:\n data = {}\n df = pd.DataFrame()\n driver.get(website.url)\n\n content = driver.page_source\n soup = BeautifulSoup(content, features=\"html.parser\")\n\n for div in soup.find_all('div', class_=website.container_class):\n for ScrapedClass in website.classes:\n try:\n data[f\"{ScrapedClass}\"] = div.find('div', class_=ScrapedClass).text\n except:\n data[f\"{ScrapedClass}\"] = \"null\"\n df = df.append(data, ignore_index=True)\n\n df.to_csv(f'{website.name}.csv', index=False, encoding='utf-8')\n\n driver.quit()"
] | [
[
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
TomerHanochi/Tetris | [
"5be6c02b27164d0b3897006e5d1476b3e8546533"
] | [
"tetris/ai/population.py"
] | [
"from __future__ import annotations\nfrom random import random\n\nimport numpy as np\n\nfrom tetris.ai.network import Network\n\n\nclass Population:\n def __init__(self, size: int = 500, old_pop: Population = None,\n parent_candidates_pct: float = .1, offspring_pct: float = .3,\n mutation_chance: float = .05, mutation_pwr: float = .2) -> None:\n \"\"\"\n Represents a list of networks that can evolve over time using a genetic algorithm.\n The population starts with random networks, and each generation the fittest networks\n are combined to produce child networks.\n Afterwards the weakest networks are replaced by the children.\n :param size: the size of the initial population.\n :param old_pop: an old population on which we create a new population using the algorithm\n described above.\n :param parent_candidates_pct: the percent of the total number of networks that we use to\n choose the number of parent candidates.\n :param offspring_pct: the percent of the total number of networks that we use to choose\n the number of offspring.\n :param mutation_chance: the chance for a child to mutate.\n :param mutation_pwr: the amount the child will mutate by, random number in the.\n [-mutation_pwr, mutation_pwr] range.\n \"\"\"\n if old_pop is None:\n self.__networks = [Network() for _ in range(size)]\n self.__fitnesses = [0 for _ in range(size)]\n else:\n self.__networks = self.crossover(networks=old_pop.networks,\n fitnesses=old_pop.fitnesses)\n self.__fitnesses = [0 for _ in range(len(self.networks))]\n\n self.offspring_pct = offspring_pct\n self.parent_candidates_pct = parent_candidates_pct\n self.mutation_chance = mutation_chance\n self.mutation_pwr = mutation_pwr\n\n def offspring(self, networks: list[Network], fitnesses: list[float]) -> list[Network]:\n \"\"\"\n Each iteration, we pick a random percent of the total networks. The two fittest networks\n among them will become the parent networks.\n We decide the weights for the child network as:\n child_weights = weights1 * fitness1 + weights2 * fitness2\n It then has a chance to mutate. Mutation causes a random part of the weights to increase by\n a random number in the [-mutation_pwr, mutation_pwr] range.\n It is then normalized, resulting in a weight vector that is between the two parents, but\n closer to the fitter one.\n :param networks: a list of networks to produce offspring from.\n :param fitnesses: a list of fitnesses corresponding to the network.\n :return: a list of child networks.\n \"\"\"\n num_of_offspring = int(len(networks) * self.offspring_pct)\n num_of_parent_candidates = int(len(networks) * self.parent_candidates_pct)\n offspring = list()\n for _ in range(num_of_offspring):\n # the indecies of the random parent candidates\n parent_candidates_indices = np.random.choice(len(networks), num_of_parent_candidates,\n replace=False)\n # the parents and their corresponding fitnesses\n parent_candidates = np.array([networks[index] for index in parent_candidates_indices])\n parent_fitnesses = np.array([fitnesses[index] for index in parent_candidates_indices])\n\n # the two fittest parents\n parent_indices = np.argpartition(parent_fitnesses, -2)[-2:]\n p1, p2 = parent_candidates[parent_indices]\n f1, f2 = parent_fitnesses[parent_indices]\n child = Network(weights=p1.weights * f1 + p2.weights * f2)\n if random() < self.mutation_chance:\n child.mutate(self.mutation_pwr)\n offspring.append(child)\n return offspring\n\n def crossover(self, networks: list[Network], fitnesses: list[float]) -> list[Network]:\n \"\"\"\n The crossover is the replacement of weak networks with possibly stronger networks.\n For each offspring we remove the weakest network, and replace it with the offspring.\n :param networks: a list of networks to produce offspring from.\n :param fitnesses: a list of fitnesses corresponding to the network.\n :return: a list of networks with the same size as networks.\n \"\"\"\n offspring = self.offspring(networks, fitnesses)\n num_of_offspring = len(offspring)\n weakest_indices = np.argpartition(fitnesses, -num_of_offspring)[-num_of_offspring:]\n new_networks = [\n network for i, network in enumerate(networks) if i not in weakest_indices\n ]\n new_networks.extend(offspring)\n return new_networks\n\n @property\n def networks(self) -> list[Network]:\n return self.__networks\n\n @property\n def fitnesses(self) -> list[float]:\n return self.__fitnesses\n\n @fitnesses.setter\n def fitnesses(self, fitnesses: list[float]) -> None:\n if isinstance(fitnesses, list):\n if len(fitnesses) == len(self.fitnesses):\n self.__fitnesses = fitnesses\n else:\n raise ValueError(f'Expected len {len(self.__fitnesses)}, got len {len(fitnesses)}')\n else:\n raise TypeError(f'Expected list, got {fitnesses.__class__.__name__}')\n\n def __iter__(self) -> iter:\n return iter(self.networks)\n"
] | [
[
"numpy.array",
"numpy.argpartition"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
zhlinup/Relay-FL | [
"3a64d75108295412ed438f95ef2cf0da6c87bdbd"
] | [
"train_script.py"
] | [
"# -*- coding: utf-8 -*-\r\n\r\nimport numpy as np\r\n\r\nnp.set_printoptions(precision=6, threshold=1e3)\r\nimport torch\r\n\r\nfrom torchvision import datasets, transforms\r\nimport copy\r\nimport torch.nn as nn\r\nfrom torch.utils.data import DataLoader\r\n\r\n\r\ndef mnist_iid(dataset, K, M):\r\n dict_users, all_idxs = {}, [i for i in range(len(dataset))]\r\n\r\n for i in range(M):\r\n dict_users[i] = set(np.random.choice(all_idxs, int(K[i]), replace=False))\r\n all_idxs = list(set(all_idxs) - dict_users[i])\r\n return dict_users\r\n\r\n\r\ndef load_fmnist_iid(K):\r\n transform = transforms.Compose([transforms.ToTensor(),\r\n transforms.Normalize((0.1307,), (0.3081,))\r\n ])\r\n dataset_train = datasets.FashionMNIST('./data/FASHION_MNIST/', download=True, train=True, transform=transform)\r\n dataset_test = datasets.FashionMNIST('./data/FASHION_MNIST/', download=True, train=False, transform=transform)\r\n\r\n loader = DataLoader(dataset_train, batch_size=len(dataset_train), shuffle=False)\r\n images, labels = next(enumerate(loader))[1]\r\n images, labels = images.numpy(), labels.numpy()\r\n D_k = int(len(labels) / K)\r\n\r\n train_images = []\r\n train_labels = []\r\n dict_users = {i: np.array([], dtype='int64') for i in range(K)}\r\n all_idxs = np.arange(len(labels))\r\n\r\n D = np.zeros(K)\r\n for i in range(K):\r\n dict_users[i] = set(np.random.choice(all_idxs, int(D_k), replace=False))\r\n all_idxs = list(set(all_idxs) - dict_users[i])\r\n train_images.append(images[list(dict_users[i])])\r\n train_labels.append(labels[list(dict_users[i])])\r\n D[i] = len(dict_users[i])\r\n\r\n test_loader = DataLoader(dataset_test, batch_size=len(dataset_test), shuffle=True)\r\n test_images, test_labels = next(enumerate(test_loader))[1]\r\n\r\n return train_images, train_labels, test_images.numpy(), test_labels.numpy(), D\r\n\r\n\r\ndef load_fmnist_noniid(K, NUM_SHARDS):\r\n transform = transforms.Compose([transforms.ToTensor(),\r\n transforms.Normalize((0.1307,), (0.3081,))\r\n ])\r\n dataset_train = datasets.FashionMNIST('./data/FASHION_MNIST/', download=True, train=True, transform=transform)\r\n dataset_test = datasets.FashionMNIST('./data/FASHION_MNIST/', download=True, train=False, transform=transform)\r\n\r\n loader = DataLoader(dataset_train, batch_size=len(dataset_train), shuffle=False)\r\n images, labels = next(enumerate(loader))[1]\r\n images, labels = images.numpy(), labels.numpy()\r\n\r\n train_images = []\r\n train_labels = []\r\n\r\n # PART = 10\r\n PART = 1\r\n\r\n num_shards = K * NUM_SHARDS * PART\r\n num_imgs = int(len(images) / num_shards)\r\n idx_shard = [i for i in range(num_shards)]\r\n dict_users = {i: np.array([], dtype='int64') for i in range(K)}\r\n all_idxs = np.arange(len(labels))\r\n\r\n # sort labels\r\n idxs_labels = np.vstack((all_idxs, labels))\r\n idxs_labels = idxs_labels[:, idxs_labels[1, :].argsort()]\r\n all_idxs = idxs_labels[0, :]\r\n\r\n idx_shard = idx_shard[::PART]\r\n\r\n D = np.zeros(K)\r\n for i in range(K):\r\n rand_set = set(np.random.choice(idx_shard, NUM_SHARDS, replace=False))\r\n idx_shard = list(set(idx_shard) - rand_set)\r\n for rand in rand_set:\r\n dict_users[i] = np.concatenate((dict_users[i], all_idxs[rand * num_imgs:(rand + 1) * num_imgs]), axis=0)\r\n train_images.append(images[dict_users[i]])\r\n train_labels.append(labels[dict_users[i]])\r\n D[i] = len(dict_users[i])\r\n\r\n test_loader = DataLoader(dataset_test, batch_size=len(dataset_test), shuffle=True)\r\n test_images, test_labels = next(enumerate(test_loader))[1]\r\n\r\n return train_images, train_labels, test_images.numpy(), test_labels.numpy(), D\r\n\r\n\r\ndef local_update(setup, d, model1, train_images, train_labels, idx, batch_size):\r\n initital_weight = copy.deepcopy(model1.state_dict())\r\n\r\n model = copy.deepcopy(model1)\r\n model.train()\r\n\r\n loss_function = nn.CrossEntropyLoss()\r\n\r\n optimizer = torch.optim.SGD(model.parameters(), lr=setup.lr, momentum=setup.momentum)\r\n\r\n # optimizer = torch.optim.Adam(model.parameters(), lr=setup.lr)\r\n\r\n epoch_loss = []\r\n images = np.array_split(train_images[idx], len(train_images[idx]) // batch_size)\r\n labels = np.array_split(train_labels[idx], len(train_labels[idx]) // batch_size)\r\n\r\n for epoch in range(setup.local_ep):\r\n batch_loss = []\r\n for b_idx in range(len(images)):\r\n model.zero_grad()\r\n\r\n log_probs = model(torch.tensor(images[b_idx].copy(), device=setup.device))\r\n local_loss = loss_function(log_probs, torch.tensor(labels[b_idx].copy(), device=setup.device))\r\n\r\n local_loss.backward()\r\n optimizer.step()\r\n if setup.verbose == 2:\r\n print('User: {}, Epoch: {}, Batch No: {}/{} Loss: {:.6f}'.format(idx,\r\n epoch, b_idx + 1, len(images),\r\n local_loss.item()))\r\n batch_loss.append(local_loss.item())\r\n epoch_loss.append(sum(batch_loss) / len(batch_loss))\r\n\r\n copyw = copy.deepcopy(model.state_dict())\r\n gradient2 = np.array([[]])\r\n w2 = np.array([[]])\r\n for item in copyw.keys():\r\n gradient2 = np.hstack((gradient2, np.reshape((initital_weight[item] - copyw[item]).cpu().numpy(),\r\n [1, -1]) / setup.lr))\r\n\r\n w2 = np.hstack((w2, np.reshape((copyw[item] - initital_weight[item]).cpu().numpy(),\r\n [1, -1])))\r\n\r\n return w2, sum(epoch_loss) / len(epoch_loss), gradient2\r\n\r\n\r\ndef test_model(model, setup, test_images, test_labels):\r\n model.eval()\r\n loss, total, correct = 0.0, 0.0, 0.0\r\n\r\n images = torch.tensor(test_images).to(setup.device)\r\n labels = torch.tensor(test_labels).to(setup.device)\r\n outputs = model(images).to(setup.device)\r\n loss_function = nn.CrossEntropyLoss()\r\n batch_loss = loss_function(outputs, labels)\r\n loss += batch_loss.item()\r\n _, pred_labels = torch.max(outputs, 1)\r\n pred_labels = pred_labels.view(-1)\r\n\r\n correct += torch.sum(torch.eq(pred_labels, labels)).item()\r\n total += len(labels)\r\n accuracy = correct / total\r\n\r\n if setup.verbose:\r\n print('Average loss: {:.4f} \\nAccuracy: {}/{} ({:.2f}%)\\n'.format(\r\n loss, int(correct), int(total), 100.0 * accuracy))\r\n return accuracy, loss\r\n"
] | [
[
"torch.nn.CrossEntropyLoss",
"torch.max",
"numpy.random.choice",
"torch.eq",
"numpy.set_printoptions",
"torch.tensor",
"numpy.concatenate",
"numpy.array",
"numpy.zeros",
"numpy.vstack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
edublancas/sklearn-model-evaluation | [
"1f35d5bcc689a5f4d54c14fde60abf09af9fc374"
] | [
"tests/test_classifier_evaluator.py"
] | [
"from sklearn_evaluation import ClassifierEvaluator\n\n# import matplotlib.pyplot as plt\nfrom sklearn import datasets\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\n\n\ndef test_can_plot():\n data = datasets.make_classification(200,\n 10,\n n_informative=5,\n class_sep=0.65)\n X = data[0]\n y = data[1]\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)\n\n est = RandomForestClassifier()\n est.fit(X_train, y_train)\n\n evaluator = ClassifierEvaluator(est, y_true=y_test, X=X_test)\n\n evaluator.confusion_matrix()\n"
] | [
[
"sklearn.datasets.make_classification",
"sklearn.model_selection.train_test_split",
"sklearn.ensemble.RandomForestClassifier"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
arifmudi/Python-Machine-Learning-By-Example-Third-Edition | [
"7bdc45df2b519e3c0a929b03f0ac6fe30e028382",
"7bdc45df2b519e3c0a929b03f0ac6fe30e028382"
] | [
"chapter5/encoding.py",
"chapter14/installation.py"
] | [
"'''\nSource codes for Python Machine Learning By Example 3rd Edition (Packt Publishing)\nChapter 5 Predicting Online Ads Click-through with Logistic Regression\nAuthor: Yuxi (Hayden) Liu ([email protected])\n'''\n\nfrom sklearn.feature_extraction import DictVectorizer\n\n\nX_dict = [{'interest': 'tech', 'occupation': 'professional'},\n {'interest': 'fashion', 'occupation': 'student'},\n {'interest': 'fashion', 'occupation': 'professional'},\n {'interest': 'sports', 'occupation': 'student'},\n {'interest': 'tech', 'occupation': 'student'},\n {'interest': 'tech', 'occupation': 'retired'},\n {'interest': 'sports', 'occupation': 'professional'}]\n\ndict_one_hot_encoder = DictVectorizer(sparse=False)\nX_encoded = dict_one_hot_encoder.fit_transform(X_dict)\nprint(X_encoded)\n\nprint(dict_one_hot_encoder.vocabulary_)\n\n\nnew_dict = [{'interest': 'sports', 'occupation': 'retired'}]\nnew_encoded = dict_one_hot_encoder.transform(new_dict)\nprint(new_encoded)\n\nprint(dict_one_hot_encoder.inverse_transform(new_encoded))\n\n\n# new category not encountered before\nnew_dict = [{'interest': 'unknown_interest', 'occupation': 'retired'},\n {'interest': 'tech', 'occupation': 'unseen_occupation'}]\nnew_encoded = dict_one_hot_encoder.transform(new_dict)\nprint(new_encoded)\n\n\n\nimport pandas as pd\ndf = pd.DataFrame({'score': ['low',\n 'high',\n 'medium',\n 'medium',\n 'low']})\nprint(df)\n\nmapping = {'low':1, 'medium':2, 'high':3}\ndf['score'] = df['score'].replace(mapping)\n\nprint(df)",
"'''\nSource codes for Python Machine Learning By Example 3rd Edition (Packt Publishing)\nChapter 14 Making Decision in Complex Environments with Reinforcement Learning\nAuthor: Yuxi (Hayden) Liu ([email protected])\n'''\n\n\nimport torch\n\nx = torch.empty(3, 4)\n\nprint(x)\n\nfrom gym import envs\nprint(envs.registry.all())\n"
] | [
[
"sklearn.feature_extraction.DictVectorizer",
"pandas.DataFrame"
],
[
"torch.empty"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Elon-Abulafia/PipeRT | [
"fba46d67a6dd546a9d70c3d854c3b7d3910f82ba"
] | [
"pipert/contrib/routines/face_detection.py"
] | [
"import torch\nfrom pipert import Routine\nfrom pipert.core.message import Message\nfrom pipert.core.routine import RoutineTypes\nfrom pipert.utils.structures import Instances, Boxes\nfrom queue import Empty\nimport time\nimport cv2\nimport pkg_resources\n\n\nclass FaceDetection(Routine):\n routine_type = RoutineTypes.PROCESSING\n\n def __init__(self, in_queue, out_queue, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.in_queue = in_queue\n self.out_queue = out_queue\n self.face_cas = None\n\n def main_logic(self, *args, **kwargs):\n try:\n frame_msg = self.in_queue.get(block=False)\n frame = frame_msg.get_payload()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n faces = self.face_cas.detectMultiScale(\n gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(20, 20)\n )\n if len(faces):\n faces = torch.from_numpy(faces)\n faces[:, 2:] += faces[:, :2]\n # print(faces.size(), faces)\n new_instances = Instances(frame.shape[:2])\n new_instances.set(\"pred_boxes\", Boxes(faces))\n new_instances.set(\"pred_classes\", torch.zeros(faces.size(0)).int())\n else:\n new_instances = Instances(frame.shape[:2])\n new_instances.set(\"pred_classes\", [])\n\n try:\n self.out_queue.get(block=False)\n self.state.dropped += 1\n except Empty:\n pass\n pred_msg = Message(new_instances, frame_msg.source_address)\n self.out_queue.put(pred_msg, block=False)\n\n return True\n\n except Empty:\n time.sleep(0)\n return False\n\n def setup(self, *args, **kwargs):\n haar_xml = pkg_resources.resource_filename('cv2', 'data/haarcascade_frontalface_default.xml')\n self.face_cas = cv2.CascadeClassifier(haar_xml)\n self.state.dropped = 0\n\n def cleanup(self, *args, **kwargs):\n pass\n\n @staticmethod\n def get_constructor_parameters():\n dicts = Routine.get_constructor_parameters()\n dicts.update({\n \"in_queue\": \"QueueIn\",\n \"out_queue\": \"QueueOut\",\n })\n return dicts\n\n def does_routine_use_queue(self, queue):\n return (self.in_queue == queue) or (self.out_queue == queue)\n\n"
] | [
[
"torch.from_numpy"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
bvsk35/Hopping_Bot | [
"5a8c7d4fdb4ae0a5ddf96002deb3c9ba1116c216",
"5a8c7d4fdb4ae0a5ddf96002deb3c9ba1116c216"
] | [
"GPS_Berkley/experiments/mjc_disc_cost_pilqr_example/hyperparams.py",
"GPS_Berkley/experiments/box2d_pointmass_pigps_example/hyperparams.py"
] | [
"\"\"\" Hyperparameters for MJC 2D navigation with discontinous target region. \"\"\"\nfrom __future__ import division\n\nfrom datetime import datetime\nimport os.path\n\nimport numpy as np\n\nfrom gps import __file__ as gps_filepath\nfrom gps.agent.mjc.agent_mjc import AgentMuJoCo\nfrom gps.algorithm.algorithm_traj_opt_pilqr import AlgorithmTrajOptPILQR\nfrom gps.algorithm.cost.cost_state import CostState\nfrom gps.algorithm.cost.cost_binary_region import CostBinaryRegion\nfrom gps.algorithm.cost.cost_sum import CostSum\nfrom gps.algorithm.dynamics.dynamics_lr_prior import DynamicsLRPrior\nfrom gps.algorithm.dynamics.dynamics_prior_gmm import DynamicsPriorGMM\nfrom gps.algorithm.traj_opt.traj_opt_pilqr import TrajOptPILQR\nfrom gps.algorithm.policy.lin_gauss_init import init_lqr\nfrom gps.proto.gps_pb2 import JOINT_ANGLES, JOINT_VELOCITIES, \\\n END_EFFECTOR_POINTS, END_EFFECTOR_POINT_VELOCITIES, ACTION\nfrom gps.gui.config import generate_experiment_info\n\n\nSENSOR_DIMS = {\n JOINT_ANGLES: 2,\n JOINT_VELOCITIES: 2,\n END_EFFECTOR_POINTS: 3,\n END_EFFECTOR_POINT_VELOCITIES: 3,\n ACTION: 2,\n}\n\nBASE_DIR = '/'.join(str.split(gps_filepath, '/')[:-2])\nEXP_DIR = BASE_DIR + '/../experiments/mjc_disc_cost_pilqr_example/'\n\n\ncommon = {\n 'experiment_name': 'my_experiment' + '_' + \\\n datetime.strftime(datetime.now(), '%m-%d-%y_%H-%M'),\n 'experiment_dir': EXP_DIR,\n 'data_files_dir': EXP_DIR + 'data_files/',\n 'target_filename': EXP_DIR + 'target.npz',\n 'log_filename': EXP_DIR + 'log.txt',\n 'conditions': 1,\n}\n\nif not os.path.exists(common['data_files_dir']):\n os.makedirs(common['data_files_dir'])\n\nagent = {\n 'type': AgentMuJoCo,\n 'filename': './mjc_models/pointmass_disc_cost.xml',\n 'x0': [np.array([1., 0., 0., 0.])],\n 'dt': 0.05,\n 'substeps': 5,\n 'conditions': common['conditions'],\n 'T': 100,\n 'sensor_dims': SENSOR_DIMS,\n 'state_include': [JOINT_ANGLES, JOINT_VELOCITIES,\n END_EFFECTOR_POINTS, END_EFFECTOR_POINT_VELOCITIES],\n 'obs_include': [JOINT_ANGLES, JOINT_VELOCITIES,\n END_EFFECTOR_POINTS, END_EFFECTOR_POINT_VELOCITIES],\n 'camera_pos': np.array([5., 6., 6.5, 0., 0., 0.]),\n 'smooth_noise_var': 3.,\n}\n\nalgorithm = {\n 'type': AlgorithmTrajOptPILQR,\n 'conditions': common['conditions'],\n 'iterations': 20,\n 'step_rule': 'res_percent',\n 'step_rule_res_ratio_inc': 0.05,\n 'step_rule_res_ratio_dec': 0.2,\n}\n\nalgorithm['init_traj_distr'] = {\n 'type': init_lqr,\n 'init_var': 20.,\n 'dt': agent['dt'],\n 'T': agent['T'],\n}\n\nstate_cost = {\n 'type': CostState,\n 'data_types' : {\n END_EFFECTOR_POINTS: {\n 'wp': np.ones(SENSOR_DIMS[END_EFFECTOR_POINTS]),\n 'target_state': np.array([3., 0, 0]),\n },\n },\n}\n\nbinary_region_cost = {\n 'type': CostBinaryRegion,\n 'data_types' : {\n END_EFFECTOR_POINTS: {\n 'wp': np.ones(SENSOR_DIMS[END_EFFECTOR_POINTS]),\n 'target_state': np.array([2.5, 0.5, 0]),\n 'max_distance': 0.3,\n 'outside_cost': 0.,\n 'inside_cost': -3.,\n },\n },\n}\n\nalgorithm['cost'] = {\n 'type': CostSum,\n 'costs': [state_cost, binary_region_cost],\n 'weights': [1., 10.],\n}\n\nalgorithm['dynamics'] = {\n 'type': DynamicsLRPrior,\n 'regularization': 1e-6,\n 'prior': {\n 'type': DynamicsPriorGMM,\n 'max_clusters': 2,\n 'min_samples_per_cluster': 40,\n 'max_samples': 20,\n }\n}\n\nalgorithm['traj_opt'] = {\n 'type': TrajOptPILQR,\n 'kl_threshold': 1.0,\n}\n\nalgorithm['policy_opt'] = {}\n\nconfig = {\n 'iterations': algorithm['iterations'],\n 'num_samples': 20,\n 'verbose_trials': 1,\n 'common': common,\n 'agent': agent,\n 'gui_on': True,\n 'algorithm': algorithm,\n}\n\ncommon['info'] = generate_experiment_info(config)\n",
"\"\"\" Hyperparameters for Box2d Point Mass task with PIGPS.\"\"\"\nfrom __future__ import division\n\nimport os.path\nfrom datetime import datetime\nimport numpy as np\n\nfrom gps import __file__ as gps_filepath\nfrom gps.agent.box2d.agent_box2d import AgentBox2D\nfrom gps.agent.box2d.point_mass_world import PointMassWorld\nfrom gps.algorithm.algorithm_pigps import AlgorithmPIGPS\nfrom gps.algorithm.algorithm_pigps import AlgorithmMDGPS\nfrom gps.algorithm.cost.cost_state import CostState\nfrom gps.algorithm.cost.cost_action import CostAction\nfrom gps.algorithm.cost.cost_sum import CostSum\nfrom gps.algorithm.dynamics.dynamics_lr_prior import DynamicsLRPrior\nfrom gps.algorithm.dynamics.dynamics_prior_gmm import DynamicsPriorGMM\nfrom gps.algorithm.policy_opt.policy_opt_caffe import PolicyOptCaffe\nfrom gps.algorithm.traj_opt.traj_opt_pi2 import TrajOptPI2\nfrom gps.algorithm.policy.policy_prior import PolicyPrior\nfrom gps.algorithm.policy.lin_gauss_init import init_pd\nfrom gps.proto.gps_pb2 import END_EFFECTOR_POINTS, END_EFFECTOR_POINT_VELOCITIES, ACTION\nfrom gps.gui.config import generate_experiment_info\nfrom gps.algorithm.traj_opt.traj_opt_lqr_python import TrajOptLQRPython\n\nSENSOR_DIMS = {\n END_EFFECTOR_POINTS: 3,\n END_EFFECTOR_POINT_VELOCITIES: 3,\n ACTION: 2\n}\n\nBASE_DIR = '/'.join(str.split(gps_filepath, '/')[:-2])\nEXP_DIR = BASE_DIR + '/../experiments/box2d_pointmass_pigps_example/'\n\ncommon = {\n 'experiment_name': 'box2d_pointmass_pigps_example' + '_' + \\\n datetime.strftime(datetime.now(), '%m-%d-%y_%H-%M'),\n 'experiment_dir': EXP_DIR,\n 'data_files_dir': EXP_DIR + 'data_files/',\n 'target_filename': EXP_DIR + 'target.npz',\n 'log_filename': EXP_DIR + 'log.txt',\n 'conditions': 4,\n}\n\nif not os.path.exists(common['data_files_dir']):\n os.makedirs(common['data_files_dir'])\n\nagent = {\n 'type': AgentBox2D,\n 'target_state' : np.array([5, 20, 0]),\n \"world\" : PointMassWorld,\n 'render' : False,\n 'x0': [np.array([0, 5, 0, 0, 0, 0]),\n np.array([0, 10, 0, 0, 0, 0]),\n np.array([10, 5, 0, 0, 0, 0]),\n np.array([10, 10, 0, 0, 0, 0]),\n ],\n 'rk': 0,\n 'dt': 0.05,\n 'substeps': 1,\n 'conditions': common['conditions'],\n 'pos_body_idx': np.array([]),\n 'pos_body_offset': np.array([]),\n 'T': 100,\n 'sensor_dims': SENSOR_DIMS,\n 'state_include': [END_EFFECTOR_POINTS, END_EFFECTOR_POINT_VELOCITIES],\n 'obs_include': [END_EFFECTOR_POINTS, END_EFFECTOR_POINT_VELOCITIES],\n 'smooth_noise_var': 3.0,\n}\n\nalgorithm = {\n 'type': AlgorithmPIGPS,\n 'conditions': common['conditions'],\n 'policy_sample_mode': 'replace',\n 'sample_on_policy': True,\n}\n\nalgorithm['init_traj_distr'] = {\n 'type': init_pd,\n 'init_var': 1.0,\n 'pos_gains': 0.0,\n 'dQ': SENSOR_DIMS[ACTION],\n 'dt': agent['dt'],\n 'T': agent['T'],\n}\n\naction_cost = {\n 'type': CostAction,\n 'wu': np.array([5e-5, 5e-5])\n}\n\nstate_cost = {\n 'type': CostState,\n 'data_types' : {\n END_EFFECTOR_POINTS: {\n 'wp': np.ones(SENSOR_DIMS[END_EFFECTOR_POINTS]),\n 'target_state': agent[\"target_state\"],\n },\n },\n}\n\nalgorithm['cost'] = {\n 'type': CostSum,\n 'costs': [action_cost, state_cost],\n 'weights': [1.0, 1.0],\n}\n\nalgorithm['traj_opt'] = {\n 'type': TrajOptPI2,\n 'kl_threshold': 2.0,\n 'covariance_damping': 2.0,\n 'min_temperature': 0.001,\n}\n\nalgorithm['policy_opt'] = {\n 'type': PolicyOptCaffe,\n 'weights_file_prefix': EXP_DIR + 'policy',\n 'taiterations': 10000,\n 'network_arch_params': {\n 'n_layers': 2,\n 'dim_hidden': [20],\n },\n}\n\nalgorithm['policy_prior'] = {\n 'type': PolicyPrior,\n}\n\nconfig = {\n 'iterations': 20,\n 'num_samples': 30,\n 'common': common,\n 'verbose_trials': 1,\n 'verbose_policy_trials': 0,\n 'agent': agent,\n 'gui_on': True,\n 'algorithm': algorithm,\n}\n\ncommon['info'] = generate_experiment_info(config)\n"
] | [
[
"numpy.array",
"numpy.ones"
],
[
"numpy.array",
"numpy.ones"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jylinman/tensorflow | [
"5248d111c3aeaf9f560cd77bff0f183f38e31e0b",
"5248d111c3aeaf9f560cd77bff0f183f38e31e0b",
"5248d111c3aeaf9f560cd77bff0f183f38e31e0b",
"5248d111c3aeaf9f560cd77bff0f183f38e31e0b",
"5248d111c3aeaf9f560cd77bff0f183f38e31e0b",
"5248d111c3aeaf9f560cd77bff0f183f38e31e0b",
"5248d111c3aeaf9f560cd77bff0f183f38e31e0b",
"5248d111c3aeaf9f560cd77bff0f183f38e31e0b",
"5248d111c3aeaf9f560cd77bff0f183f38e31e0b"
] | [
"tensorflow/python/kernel_tests/py_func_test.py",
"tensorflow/python/kernel_tests/dense_update_ops_no_tsan_test.py",
"tensorflow/models/rnn/translate/translate.py",
"tensorflow/python/ops/control_flow_ops_test.py",
"tensorflow/python/kernel_tests/bcast_ops_test.py",
"tensorflow/python/training/gradient_descent.py",
"tensorflow/models/image/cifar10/cifar10_multi_gpu_train.py",
"tensorflow/python/kernel_tests/io_ops_test.py",
"tensorflow/python/kernel_tests/dense_update_ops_test.py"
] | [
"# Copyright 2015 Google Inc. 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 py_func op.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nfrom six.moves import xrange # pylint: disable=redefined-builtin\nimport tensorflow as tf\n\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.ops import script_ops\n\n\nclass PyOpTest(tf.test.TestCase):\n\n def testBasic(self):\n\n def my_func(x, y):\n return np.sinh(x) + np.cosh(y)\n\n # scalar\n with self.test_session():\n x = tf.constant(1.0, tf.float32)\n y = tf.constant(2.0, tf.float32)\n z = tf.py_func(my_func, [x, y], [tf.float32])\n self.assertEqual(z[0].eval(), my_func(1.0, 2.0).astype(np.float32))\n\n # array\n with self.test_session():\n x = tf.constant([1.0, 2.0], tf.float64)\n y = tf.constant([2.0, 3.0], tf.float64)\n z = tf.py_func(my_func, [x, y], [tf.float64])\n self.assertAllEqual(\n z[0].eval(),\n my_func([1.0, 2.0], [2.0, 3.0]).astype(np.float64))\n\n # a bit exotic type (complex64)\n with self.test_session():\n x = tf.constant(1+2j, tf.complex64)\n y = tf.constant(3+4j, tf.complex64)\n z, = tf.py_func(my_func, [x, y], [tf.complex64])\n self.assertAllClose(z.eval(), my_func(1+2j, 3+4j))\n\n # a bit excotic function (rfft)\n with self.test_session():\n x = tf.constant([1., 2., 3., 4.], tf.float32)\n def rfft(x):\n return np.fft.rfft(x).astype(np.complex64)\n y, = tf.py_func(rfft, [x], [tf.complex64])\n self.assertAllClose(y.eval(), np.fft.rfft([1., 2., 3., 4.]))\n\n # returns a python literal.\n with self.test_session():\n def literal(x):\n return 1.0 if x == 0.0 else 0.0\n x = tf.constant(0.0, tf.float64)\n y, = tf.py_func(literal, [x], [tf.float64])\n self.assertAllClose(y.eval(), 1.0)\n\n def testStrings(self):\n\n def read_fixed_length_numpy_strings():\n return np.array([b\" there\"])\n\n def read_and_return_strings(x, y):\n return x + y\n\n with self.test_session():\n x = tf.constant([b\"hello\", b\"hi\"], tf.string)\n y, = tf.py_func(read_fixed_length_numpy_strings, [], [tf.string])\n z, = tf.py_func(read_and_return_strings, [x, y], [tf.string])\n self.assertListEqual(list(z.eval()), [b\"hello there\", b\"hi there\"])\n\n def testLarge(self):\n with self.test_session() as sess:\n x = tf.zeros([1000000], dtype=np.float32)\n y = tf.py_func(lambda x: x + 1, [x], [tf.float32])\n z = tf.py_func(lambda x: x * 2, [x], [tf.float32])\n for _ in xrange(100):\n sess.run([y[0].op, z[0].op])\n\n def testNoInput(self):\n with self.test_session():\n x, = tf.py_func(lambda: 42.0, [], [tf.float64])\n self.assertAllClose(x.eval(), 42.0)\n\n def testCleanup(self):\n for _ in xrange(1000):\n g = tf.Graph()\n with g.as_default():\n c = tf.constant([1.], tf.float32)\n _ = tf.py_func(lambda x: x + 1, [c], [tf.float32])\n self.assertTrue(script_ops._py_funcs.size() < 100)\n\n def testError(self):\n with self.test_session():\n\n def bad1():\n # Structured numpy arrays aren't supported.\n return np.array([], dtype=[(\"foo\", np.float32)])\n\n def bad2():\n # Non-string python objects aren't supported.\n return tf.float32\n\n y, = tf.py_func(bad1, [], [tf.string])\n z, = tf.py_func(bad2, [], [tf.float64])\n with self.assertRaisesRegexp(errors.UnimplementedError,\n \"Unsupported numpy type\"):\n y.eval()\n with self.assertRaisesRegexp(errors.UnimplementedError,\n \"Unsupported object type\"):\n z.eval()\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n",
"# Copyright 2015 Google Inc. 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\n\"\"\"Tests for state updating ops that may have benign race conditions.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\n\nclass AssignOpTest(tf.test.TestCase):\n\n # NOTE(mrry): We exclude thess tests from the TSAN TAP target, because they\n # contain benign and deliberate data races when multiple threads update\n # the same parameters without a lock.\n def testParallelUpdateWithoutLocking(self):\n with self.test_session() as sess:\n ones_t = tf.fill([1024, 1024], 1.0)\n p = tf.Variable(tf.zeros([1024, 1024]))\n adds = [tf.assign_add(p, ones_t, use_locking=False)\n for _ in range(20)]\n tf.initialize_all_variables().run()\n\n def run_add(add_op):\n sess.run(add_op)\n threads = [self.checkedThread(target=run_add, args=(add_op,))\n for add_op in adds]\n for t in threads:\n t.start()\n for t in threads:\n t.join()\n\n vals = p.eval()\n ones = np.ones((1024, 1024)).astype(np.float32)\n self.assertTrue((vals >= ones).all())\n self.assertTrue((vals <= ones * 20).all())\n\n def testParallelAssignWithoutLocking(self):\n with self.test_session() as sess:\n ones_t = tf.fill([1024, 1024], float(1))\n p = tf.Variable(tf.zeros([1024, 1024]))\n assigns = [tf.assign(p, tf.mul(ones_t, float(i)), False)\n for i in range(1, 21)]\n tf.initialize_all_variables().run()\n\n def run_assign(assign_op):\n sess.run(assign_op)\n threads = [self.checkedThread(target=run_assign, args=(assign_op,))\n for assign_op in assigns]\n for t in threads:\n t.start()\n for t in threads:\n t.join()\n\n vals = p.eval()\n\n # Assert every element is taken from one of the assignments.\n self.assertTrue((vals > 0).all())\n self.assertTrue((vals <= 20).all())\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n",
"# Copyright 2015 Google Inc. 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\n\"\"\"Binary for training translation models and decoding from them.\n\nRunning this program without --decode will download the WMT corpus into\nthe directory specified as --data_dir and tokenize it in a very basic way,\nand then start training a model saving checkpoints to --train_dir.\n\nRunning with --decode starts an interactive loop so you can see how\nthe current checkpoint translates English sentences into French.\n\nSee the following papers for more information on neural translation models.\n * http://arxiv.org/abs/1409.3215\n * http://arxiv.org/abs/1409.0473\n * http://arxiv.org/abs/1412.2007\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\nimport os\nimport random\nimport sys\nimport time\n\nimport numpy as np\nfrom six.moves import xrange # pylint: disable=redefined-builtin\nimport tensorflow as tf\n\nfrom tensorflow.models.rnn.translate import data_utils\nfrom tensorflow.models.rnn.translate import seq2seq_model\n\n\ntf.app.flags.DEFINE_float(\"learning_rate\", 0.5, \"Learning rate.\")\ntf.app.flags.DEFINE_float(\"learning_rate_decay_factor\", 0.99,\n \"Learning rate decays by this much.\")\ntf.app.flags.DEFINE_float(\"max_gradient_norm\", 5.0,\n \"Clip gradients to this norm.\")\ntf.app.flags.DEFINE_integer(\"batch_size\", 64,\n \"Batch size to use during training.\")\ntf.app.flags.DEFINE_integer(\"size\", 1024, \"Size of each model layer.\")\ntf.app.flags.DEFINE_integer(\"num_layers\", 3, \"Number of layers in the model.\")\ntf.app.flags.DEFINE_integer(\"en_vocab_size\", 40000, \"English vocabulary size.\")\ntf.app.flags.DEFINE_integer(\"fr_vocab_size\", 40000, \"French vocabulary size.\")\ntf.app.flags.DEFINE_string(\"data_dir\", \"/tmp\", \"Data directory\")\ntf.app.flags.DEFINE_string(\"train_dir\", \"/tmp\", \"Training directory.\")\ntf.app.flags.DEFINE_integer(\"max_train_data_size\", 0,\n \"Limit on the size of training data (0: no limit).\")\ntf.app.flags.DEFINE_integer(\"steps_per_checkpoint\", 200,\n \"How many training steps to do per checkpoint.\")\ntf.app.flags.DEFINE_boolean(\"decode\", False,\n \"Set to True for interactive decoding.\")\ntf.app.flags.DEFINE_boolean(\"self_test\", False,\n \"Run a self-test if this is set to True.\")\n\nFLAGS = tf.app.flags.FLAGS\n\n# We use a number of buckets and pad to the closest one for efficiency.\n# See seq2seq_model.Seq2SeqModel for details of how they work.\n_buckets = [(5, 10), (10, 15), (20, 25), (40, 50)]\n\n\ndef read_data(source_path, target_path, max_size=None):\n \"\"\"Read data from source and target files and put into buckets.\n\n Args:\n source_path: path to the files with token-ids for the source language.\n target_path: path to the file with token-ids for the target language;\n it must be aligned with the source file: n-th line contains the desired\n output for n-th line from the source_path.\n max_size: maximum number of lines to read, all other will be ignored;\n if 0 or None, data files will be read completely (no limit).\n\n Returns:\n data_set: a list of length len(_buckets); data_set[n] contains a list of\n (source, target) pairs read from the provided data files that fit\n into the n-th bucket, i.e., such that len(source) < _buckets[n][0] and\n len(target) < _buckets[n][1]; source and target are lists of token-ids.\n \"\"\"\n data_set = [[] for _ in _buckets]\n with tf.gfile.GFile(source_path, mode=\"r\") as source_file:\n with tf.gfile.GFile(target_path, mode=\"r\") as target_file:\n source, target = source_file.readline(), target_file.readline()\n counter = 0\n while source and target and (not max_size or counter < max_size):\n counter += 1\n if counter % 100000 == 0:\n print(\" reading data line %d\" % counter)\n sys.stdout.flush()\n source_ids = [int(x) for x in source.split()]\n target_ids = [int(x) for x in target.split()]\n target_ids.append(data_utils.EOS_ID)\n for bucket_id, (source_size, target_size) in enumerate(_buckets):\n if len(source_ids) < source_size and len(target_ids) < target_size:\n data_set[bucket_id].append([source_ids, target_ids])\n break\n source, target = source_file.readline(), target_file.readline()\n return data_set\n\n\ndef create_model(session, forward_only):\n \"\"\"Create translation model and initialize or load parameters in session.\"\"\"\n model = seq2seq_model.Seq2SeqModel(\n FLAGS.en_vocab_size, FLAGS.fr_vocab_size, _buckets,\n FLAGS.size, FLAGS.num_layers, FLAGS.max_gradient_norm, FLAGS.batch_size,\n FLAGS.learning_rate, FLAGS.learning_rate_decay_factor,\n forward_only=forward_only)\n ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir)\n if ckpt and tf.gfile.Exists(ckpt.model_checkpoint_path):\n print(\"Reading model parameters from %s\" % ckpt.model_checkpoint_path)\n model.saver.restore(session, ckpt.model_checkpoint_path)\n else:\n print(\"Created model with fresh parameters.\")\n session.run(tf.initialize_all_variables())\n return model\n\n\ndef train():\n \"\"\"Train a en->fr translation model using WMT data.\"\"\"\n # Prepare WMT data.\n print(\"Preparing WMT data in %s\" % FLAGS.data_dir)\n en_train, fr_train, en_dev, fr_dev, _, _ = data_utils.prepare_wmt_data(\n FLAGS.data_dir, FLAGS.en_vocab_size, FLAGS.fr_vocab_size)\n\n with tf.Session() as sess:\n # Create model.\n print(\"Creating %d layers of %d units.\" % (FLAGS.num_layers, FLAGS.size))\n model = create_model(sess, False)\n\n # Read data into buckets and compute their sizes.\n print (\"Reading development and training data (limit: %d).\"\n % FLAGS.max_train_data_size)\n dev_set = read_data(en_dev, fr_dev)\n train_set = read_data(en_train, fr_train, FLAGS.max_train_data_size)\n train_bucket_sizes = [len(train_set[b]) for b in xrange(len(_buckets))]\n train_total_size = float(sum(train_bucket_sizes))\n\n # A bucket scale is a list of increasing numbers from 0 to 1 that we'll use\n # to select a bucket. Length of [scale[i], scale[i+1]] is proportional to\n # the size if i-th training bucket, as used later.\n train_buckets_scale = [sum(train_bucket_sizes[:i + 1]) / train_total_size\n for i in xrange(len(train_bucket_sizes))]\n\n # This is the training loop.\n step_time, loss = 0.0, 0.0\n current_step = 0\n previous_losses = []\n while True:\n # Choose a bucket according to data distribution. We pick a random number\n # in [0, 1] and use the corresponding interval in train_buckets_scale.\n random_number_01 = np.random.random_sample()\n bucket_id = min([i for i in xrange(len(train_buckets_scale))\n if train_buckets_scale[i] > random_number_01])\n\n # Get a batch and make a step.\n start_time = time.time()\n encoder_inputs, decoder_inputs, target_weights = model.get_batch(\n train_set, bucket_id)\n _, step_loss, _ = model.step(sess, encoder_inputs, decoder_inputs,\n target_weights, bucket_id, False)\n step_time += (time.time() - start_time) / FLAGS.steps_per_checkpoint\n loss += step_loss / FLAGS.steps_per_checkpoint\n current_step += 1\n\n # Once in a while, we save checkpoint, print statistics, and run evals.\n if current_step % FLAGS.steps_per_checkpoint == 0:\n # Print statistics for the previous epoch.\n perplexity = math.exp(loss) if loss < 300 else float('inf')\n print (\"global step %d learning rate %.4f step-time %.2f perplexity \"\n \"%.2f\" % (model.global_step.eval(), model.learning_rate.eval(),\n step_time, perplexity))\n # Decrease learning rate if no improvement was seen over last 3 times.\n if len(previous_losses) > 2 and loss > max(previous_losses[-3:]):\n sess.run(model.learning_rate_decay_op)\n previous_losses.append(loss)\n # Save checkpoint and zero timer and loss.\n checkpoint_path = os.path.join(FLAGS.train_dir, \"translate.ckpt\")\n model.saver.save(sess, checkpoint_path, global_step=model.global_step)\n step_time, loss = 0.0, 0.0\n # Run evals on development set and print their perplexity.\n for bucket_id in xrange(len(_buckets)):\n encoder_inputs, decoder_inputs, target_weights = model.get_batch(\n dev_set, bucket_id)\n _, eval_loss, _ = model.step(sess, encoder_inputs, decoder_inputs,\n target_weights, bucket_id, True)\n eval_ppx = math.exp(eval_loss) if eval_loss < 300 else float('inf')\n print(\" eval: bucket %d perplexity %.2f\" % (bucket_id, eval_ppx))\n sys.stdout.flush()\n\n\ndef decode():\n with tf.Session() as sess:\n # Create model and load parameters.\n model = create_model(sess, True)\n model.batch_size = 1 # We decode one sentence at a time.\n\n # Load vocabularies.\n en_vocab_path = os.path.join(FLAGS.data_dir,\n \"vocab%d.en\" % FLAGS.en_vocab_size)\n fr_vocab_path = os.path.join(FLAGS.data_dir,\n \"vocab%d.fr\" % FLAGS.fr_vocab_size)\n en_vocab, _ = data_utils.initialize_vocabulary(en_vocab_path)\n _, rev_fr_vocab = data_utils.initialize_vocabulary(fr_vocab_path)\n\n # Decode from standard input.\n sys.stdout.write(\"> \")\n sys.stdout.flush()\n sentence = sys.stdin.readline()\n while sentence:\n # Get token-ids for the input sentence.\n token_ids = data_utils.sentence_to_token_ids(sentence, en_vocab)\n # Which bucket does it belong to?\n bucket_id = min([b for b in xrange(len(_buckets))\n if _buckets[b][0] > len(token_ids)])\n # Get a 1-element batch to feed the sentence to the model.\n encoder_inputs, decoder_inputs, target_weights = model.get_batch(\n {bucket_id: [(token_ids, [])]}, bucket_id)\n # Get output logits for the sentence.\n _, _, output_logits = model.step(sess, encoder_inputs, decoder_inputs,\n target_weights, bucket_id, True)\n # This is a greedy decoder - outputs are just argmaxes of output_logits.\n outputs = [int(np.argmax(logit, axis=1)) for logit in output_logits]\n # If there is an EOS symbol in outputs, cut them at that point.\n if data_utils.EOS_ID in outputs:\n outputs = outputs[:outputs.index(data_utils.EOS_ID)]\n # Print out French sentence corresponding to outputs.\n print(\" \".join([rev_fr_vocab[output] for output in outputs]))\n print(\"> \", end=\"\")\n sys.stdout.flush()\n sentence = sys.stdin.readline()\n\n\ndef self_test():\n \"\"\"Test the translation model.\"\"\"\n with tf.Session() as sess:\n print(\"Self-test for neural translation model.\")\n # Create model with vocabularies of 10, 2 small buckets, 2 layers of 32.\n model = seq2seq_model.Seq2SeqModel(10, 10, [(3, 3), (6, 6)], 32, 2,\n 5.0, 32, 0.3, 0.99, num_samples=8)\n sess.run(tf.initialize_all_variables())\n\n # Fake data set for both the (3, 3) and (6, 6) bucket.\n data_set = ([([1, 1], [2, 2]), ([3, 3], [4]), ([5], [6])],\n [([1, 1, 1, 1, 1], [2, 2, 2, 2, 2]), ([3, 3, 3], [5, 6])])\n for _ in xrange(5): # Train the fake model for 5 steps.\n bucket_id = random.choice([0, 1])\n encoder_inputs, decoder_inputs, target_weights = model.get_batch(\n data_set, bucket_id)\n model.step(sess, encoder_inputs, decoder_inputs, target_weights,\n bucket_id, False)\n\n\ndef main(_):\n if FLAGS.self_test:\n self_test()\n elif FLAGS.decode:\n decode()\n else:\n train()\n\nif __name__ == \"__main__\":\n tf.app.run()\n",
"# Copyright 2015 Google Inc. 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\n\"\"\"Tests for control_flow_ops.py.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.core.framework import graph_pb2\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.framework.test_util import TensorFlowTestCase\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import standard_ops as tf\nfrom tensorflow.python.platform import googletest\n\n\nclass GroupTestCase(TensorFlowTestCase):\n\n def _StripNode(self, nd):\n snode = graph_pb2.NodeDef(name=nd.name, op=nd.op, input=nd.input)\n if nd.device:\n snode.device = nd.device\n return snode\n\n def _StripGraph(self, gd):\n \"\"\"Copy gd keeping only, node.name, node.op, node.input, and node.device.\"\"\"\n return graph_pb2.GraphDef(node=[self._StripNode(nd) for nd in gd.node])\n\n def testGroup_NoDevices(self):\n with ops.Graph().as_default() as g:\n a = tf.constant(0, name=\"a\")\n b = tf.constant(0, name=\"b\")\n c = tf.constant(0, name=\"c\")\n tf.group(a.op, b.op, c.op, name=\"root\")\n gd = g.as_graph_def()\n self.assertProtoEquals(\"\"\"\n node { name: \"a\" op: \"Const\"}\n node { name: \"b\" op: \"Const\"}\n node { name: \"c\" op: \"Const\"}\n node { name: \"root\" op: \"NoOp\" input: \"^a\" input: \"^b\" input: \"^c\" }\n \"\"\", self._StripGraph(gd))\n\n def testGroup_OneDevice(self):\n with ops.Graph().as_default() as g:\n with g.device(\"/task:0\"):\n a = tf.constant(0, name=\"a\")\n b = tf.constant(0, name=\"b\")\n tf.group(a.op, b.op, name=\"root\")\n gd = g.as_graph_def()\n self.assertProtoEquals(\"\"\"\n node { name: \"a\" op: \"Const\" device: \"/task:0\" }\n node { name: \"b\" op: \"Const\" device: \"/task:0\" }\n node { name: \"root\" op: \"NoOp\" input: \"^a\" input: \"^b\" device: \"/task:0\" }\n \"\"\", self._StripGraph(gd))\n\n def testGroup_MultiDevice(self):\n with ops.Graph().as_default() as g:\n with g.device(\"/task:0\"):\n a = tf.constant(0, name=\"a\")\n b = tf.constant(0, name=\"b\")\n with g.device(\"/task:1\"):\n c = tf.constant(0, name=\"c\")\n d = tf.constant(0, name=\"d\")\n with g.device(\"/task:2\"):\n tf.group(a.op, b.op, c.op, d.op, name=\"root\")\n gd = g.as_graph_def()\n self.assertProtoEquals(\"\"\"\n node { name: \"a\" op: \"Const\" device: \"/task:0\"}\n node { name: \"b\" op: \"Const\" device: \"/task:0\"}\n node { name: \"c\" op: \"Const\" device: \"/task:1\"}\n node { name: \"d\" op: \"Const\" device: \"/task:1\"}\n node { name: \"root/NoOp\" op: \"NoOp\" input: \"^a\" input: \"^b\"\n device: \"/task:0\" }\n node { name: \"root/NoOp_1\" op: \"NoOp\" input: \"^c\" input: \"^d\"\n device: \"/task:1\" }\n node { name: \"root\" op: \"NoOp\" input: \"^root/NoOp\" input: \"^root/NoOp_1\"\n device: \"/task:2\" }\n \"\"\", self._StripGraph(gd))\n\n\nclass ShapeTestCase(TensorFlowTestCase):\n\n def testShape(self):\n with ops.Graph().as_default():\n tensor = tf.constant([1.0, 2.0])\n self.assertEquals([2], tensor.get_shape())\n self.assertEquals([2],\n control_flow_ops.with_dependencies(\n [tf.constant(1.0)], tensor).get_shape())\n\n\nif __name__ == \"__main__\":\n googletest.main()\n",
"# Copyright 2015 Google Inc. 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\n\"\"\"Tests for tensorflow.kernels.bcast_ops.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nfrom tensorflow.python.ops.gen_array_ops import _broadcast_gradient_args\n\n\nclass BcastOpsTest(tf.test.TestCase):\n\n def _GetGradientArgs(self, xs, ys):\n with self.test_session() as sess:\n return sess.run(_broadcast_gradient_args(xs, ys))\n\n def testBasic(self):\n r0, r1 = self._GetGradientArgs([2, 3, 5], [1])\n self.assertAllEqual(r0, [])\n self.assertAllEqual(r1, [0, 1, 2])\n\n r0, r1 = self._GetGradientArgs([1], [2, 3, 5])\n self.assertAllEqual(r0, [0, 1, 2])\n self.assertAllEqual(r1, [])\n\n r0, r1 = self._GetGradientArgs([2, 3, 5], [5])\n self.assertAllEqual(r0, [])\n self.assertAllEqual(r1, [0, 1])\n\n r0, r1 = self._GetGradientArgs([5], [2, 3, 5])\n self.assertAllEqual(r0, [0, 1])\n self.assertAllEqual(r1, [])\n\n r0, r1 = self._GetGradientArgs([2, 3, 5], [3, 5])\n self.assertAllEqual(r0, [])\n self.assertAllEqual(r1, [0])\n\n r0, r1 = self._GetGradientArgs([3, 5], [2, 3, 5])\n self.assertAllEqual(r0, [0])\n self.assertAllEqual(r1, [])\n\n r0, r1 = self._GetGradientArgs([2, 3, 5], [3, 1])\n self.assertAllEqual(r0, [])\n self.assertAllEqual(r1, [0, 2])\n\n r0, r1 = self._GetGradientArgs([3, 1], [2, 3, 5])\n self.assertAllEqual(r0, [0, 2])\n self.assertAllEqual(r1, [])\n\n r0, r1 = self._GetGradientArgs([2, 1, 5], [3, 1])\n self.assertAllEqual(r0, [1])\n self.assertAllEqual(r1, [0, 2])\n\n r0, r1 = self._GetGradientArgs([3, 1], [2, 1, 5])\n self.assertAllEqual(r0, [0, 2])\n self.assertAllEqual(r1, [1])\n\n def testZeroDims(self):\n r0, r1 = self._GetGradientArgs([2, 0, 3, 0, 5], [3, 0, 5])\n self.assertAllEqual(r0, [])\n self.assertAllEqual(r1, [0, 1])\n\n r0, r1 = self._GetGradientArgs([3, 0, 5], [2, 0, 3, 0, 5])\n self.assertAllEqual(r0, [0, 1])\n self.assertAllEqual(r1, [])\n\n r0, r1 = self._GetGradientArgs([2, 0, 3, 0, 5], [3, 1, 5])\n self.assertAllEqual(r0, [])\n self.assertAllEqual(r1, [0, 1, 3])\n\n r0, r1 = self._GetGradientArgs([3, 1, 5], [2, 0, 3, 0, 5])\n self.assertAllEqual(r0, [0, 1, 3])\n self.assertAllEqual(r1, [])\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n",
"# Copyright 2015 Google Inc. 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\n\"\"\"GradientDescent for TensorFlow.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import constant_op\n# pylint: disable=unused-import\nfrom tensorflow.python.ops import math_ops\n# pylint: enable=unused-import\nfrom tensorflow.python.training import optimizer\nfrom tensorflow.python.training import training_ops\n\n\nclass GradientDescentOptimizer(optimizer.Optimizer):\n \"\"\"Optimizer that implements the gradient descent algorithm.\n\n @@__init__\n \"\"\"\n\n def __init__(self, learning_rate, use_locking=False, name=\"GradientDescent\"):\n \"\"\"Construct a new gradient descent optimizer.\n\n Args:\n learning_rate: A Tensor or a floating point value. The learning\n rate to use.\n use_locking: If True use locks for update operations.\n name: Optional name prefix for the operations created when applying\n gradients. Defaults to \"GradientDescent\".\n \"\"\"\n super(GradientDescentOptimizer, self).__init__(use_locking, name)\n self._learning_rate = learning_rate\n\n def _apply_dense(self, grad, var):\n return training_ops.apply_gradient_descent(\n var,\n self._learning_rate_tensor,\n grad,\n use_locking=self._use_locking).op\n\n def _apply_sparse(self, grad, var):\n delta = ops.IndexedSlices(grad.values * self._learning_rate_tensor,\n grad.indices, grad.dense_shape)\n return var.scatter_sub(delta, use_locking=self._use_locking)\n\n def _prepare(self):\n self._learning_rate_tensor = ops.convert_to_tensor(self._learning_rate,\n name=\"learning_rate\")\n",
"# Copyright 2015 Google Inc. 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\n\"\"\"A binary to train CIFAR-10 using multiple GPU's with synchronous updates.\n\nAccuracy:\ncifar10_multi_gpu_train.py achieves ~86% accuracy after 100K steps (256\nepochs of data) as judged by cifar10_eval.py.\n\nSpeed: With batch_size 128.\n\nSystem | Step Time (sec/batch) | Accuracy\n--------------------------------------------------------------------\n1 Tesla K20m | 0.35-0.60 | ~86% at 60K steps (5 hours)\n1 Tesla K40m | 0.25-0.35 | ~86% at 100K steps (4 hours)\n2 Tesla K20m | 0.13-0.20 | ~84% at 30K steps (2.5 hours)\n3 Tesla K20m | 0.13-0.18 | ~84% at 30K steps\n4 Tesla K20m | ~0.10 | ~84% at 30K steps\n\nUsage:\nPlease see the tutorial and website for how to download the CIFAR-10\ndata set, compile the program and train the model.\n\nhttp://tensorflow.org/tutorials/deep_cnn/\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom datetime import datetime\nimport os.path\nimport re\nimport time\n\nimport numpy as np\nfrom six.moves import xrange # pylint: disable=redefined-builtin\nimport tensorflow as tf\nfrom tensorflow.models.image.cifar10 import cifar10\n\nFLAGS = tf.app.flags.FLAGS\n\ntf.app.flags.DEFINE_string('train_dir', '/tmp/cifar10_train',\n \"\"\"Directory where to write event logs \"\"\"\n \"\"\"and checkpoint.\"\"\")\ntf.app.flags.DEFINE_integer('max_steps', 1000000,\n \"\"\"Number of batches to run.\"\"\")\ntf.app.flags.DEFINE_integer('num_gpus', 1,\n \"\"\"How many GPUs to use.\"\"\")\ntf.app.flags.DEFINE_boolean('log_device_placement', False,\n \"\"\"Whether to log device placement.\"\"\")\n\n\ndef tower_loss(scope):\n \"\"\"Calculate the total loss on a single tower running the CIFAR model.\n\n Args:\n scope: unique prefix string identifying the CIFAR tower, e.g. 'tower_0'\n\n Returns:\n Tensor of shape [] containing the total loss for a batch of data\n \"\"\"\n # Get images and labels for CIFAR-10.\n images, labels = cifar10.distorted_inputs()\n\n # Build inference Graph.\n logits = cifar10.inference(images)\n\n # Build the portion of the Graph calculating the losses. Note that we will\n # assemble the total_loss using a custom function below.\n _ = cifar10.loss(logits, labels)\n\n # Assemble all of the losses for the current tower only.\n losses = tf.get_collection('losses', scope)\n\n # Calculate the total loss for the current tower.\n total_loss = tf.add_n(losses, name='total_loss')\n\n # Compute the moving average of all individual losses and the total loss.\n loss_averages = tf.train.ExponentialMovingAverage(0.9, name='avg')\n loss_averages_op = loss_averages.apply(losses + [total_loss])\n\n # Attach a scalar summary to all individual losses and the total loss; do the\n # same for the averaged version of the losses.\n for l in losses + [total_loss]:\n # Remove 'tower_[0-9]/' from the name in case this is a multi-GPU training\n # session. This helps the clarity of presentation on tensorboard.\n loss_name = re.sub('%s_[0-9]*/' % cifar10.TOWER_NAME, '', l.op.name)\n # Name each loss as '(raw)' and name the moving average version of the loss\n # as the original loss name.\n tf.scalar_summary(loss_name +' (raw)', l)\n tf.scalar_summary(loss_name, loss_averages.average(l))\n\n with tf.control_dependencies([loss_averages_op]):\n total_loss = tf.identity(total_loss)\n return total_loss\n\n\ndef average_gradients(tower_grads):\n \"\"\"Calculate the average gradient for each shared variable across all towers.\n\n Note that this function provides a synchronization point across all towers.\n\n Args:\n tower_grads: List of lists of (gradient, variable) tuples. The outer list\n is over individual gradients. The inner list is over the gradient\n calculation for each tower.\n Returns:\n List of pairs of (gradient, variable) where the gradient has been averaged\n across all towers.\n \"\"\"\n average_grads = []\n for grad_and_vars in zip(*tower_grads):\n # Note that each grad_and_vars looks like the following:\n # ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN))\n grads = []\n for g, _ in grad_and_vars:\n # Add 0 dimension to the gradients to represent the tower.\n expanded_g = tf.expand_dims(g, 0)\n\n # Append on a 'tower' dimension which we will average over below.\n grads.append(expanded_g)\n\n # Average over the 'tower' dimension.\n grad = tf.concat(0, grads)\n grad = tf.reduce_mean(grad, 0)\n\n # Keep in mind that the Variables are redundant because they are shared\n # across towers. So .. we will just return the first tower's pointer to\n # the Variable.\n v = grad_and_vars[0][1]\n grad_and_var = (grad, v)\n average_grads.append(grad_and_var)\n return average_grads\n\n\ndef train():\n \"\"\"Train CIFAR-10 for a number of steps.\"\"\"\n with tf.Graph().as_default(), tf.device('/cpu:0'):\n # Create a variable to count the number of train() calls. This equals the\n # number of batches processed * FLAGS.num_gpus.\n global_step = tf.get_variable(\n 'global_step', [],\n initializer=tf.constant_initializer(0), trainable=False)\n\n # Calculate the learning rate schedule.\n num_batches_per_epoch = (cifar10.NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN /\n FLAGS.batch_size)\n decay_steps = int(num_batches_per_epoch * cifar10.NUM_EPOCHS_PER_DECAY)\n\n # Decay the learning rate exponentially based on the number of steps.\n lr = tf.train.exponential_decay(cifar10.INITIAL_LEARNING_RATE,\n global_step,\n decay_steps,\n cifar10.LEARNING_RATE_DECAY_FACTOR,\n staircase=True)\n\n # Create an optimizer that performs gradient descent.\n opt = tf.train.GradientDescentOptimizer(lr)\n\n # Calculate the gradients for each model tower.\n tower_grads = []\n for i in xrange(FLAGS.num_gpus):\n with tf.device('/gpu:%d' % i):\n with tf.name_scope('%s_%d' % (cifar10.TOWER_NAME, i)) as scope:\n # Calculate the loss for one tower of the CIFAR model. This function\n # constructs the entire CIFAR model but shares the variables across\n # all towers.\n loss = tower_loss(scope)\n\n # Reuse variables for the next tower.\n tf.get_variable_scope().reuse_variables()\n\n # Retain the summaries from the final tower.\n summaries = tf.get_collection(tf.GraphKeys.SUMMARIES, scope)\n\n # Calculate the gradients for the batch of data on this CIFAR tower.\n grads = opt.compute_gradients(loss)\n\n # Keep track of the gradients across all towers.\n tower_grads.append(grads)\n\n # We must calculate the mean of each gradient. Note that this is the\n # synchronization point across all towers.\n grads = average_gradients(tower_grads)\n\n # Add a summary to track the learning rate.\n summaries.append(tf.scalar_summary('learning_rate', lr))\n\n # Add histograms for gradients.\n for grad, var in grads:\n if grad:\n summaries.append(\n tf.histogram_summary(var.op.name + '/gradients', grad))\n\n # Apply the gradients to adjust the shared variables.\n apply_gradient_op = opt.apply_gradients(grads, global_step=global_step)\n\n # Add histograms for trainable variables.\n for var in tf.trainable_variables():\n summaries.append(tf.histogram_summary(var.op.name, var))\n\n # Track the moving averages of all trainable variables.\n variable_averages = tf.train.ExponentialMovingAverage(\n cifar10.MOVING_AVERAGE_DECAY, global_step)\n variables_averages_op = variable_averages.apply(tf.trainable_variables())\n\n # Group all updates to into a single train op.\n train_op = tf.group(apply_gradient_op, variables_averages_op)\n\n # Create a saver.\n saver = tf.train.Saver(tf.all_variables())\n\n # Build the summary operation from the last tower summaries.\n summary_op = tf.merge_summary(summaries)\n\n # Build an initialization operation to run below.\n init = tf.initialize_all_variables()\n\n # Start running operations on the Graph. allow_soft_placement must be set to\n # True to build towers on GPU, as some of the ops do not have GPU\n # implementations.\n sess = tf.Session(config=tf.ConfigProto(\n allow_soft_placement=True,\n log_device_placement=FLAGS.log_device_placement))\n sess.run(init)\n\n # Start the queue runners.\n tf.train.start_queue_runners(sess=sess)\n\n summary_writer = tf.train.SummaryWriter(FLAGS.train_dir,\n graph_def=sess.graph_def)\n\n for step in xrange(FLAGS.max_steps):\n start_time = time.time()\n _, loss_value = sess.run([train_op, loss])\n duration = time.time() - start_time\n\n assert not np.isnan(loss_value), 'Model diverged with loss = NaN'\n\n if step % 10 == 0:\n num_examples_per_step = FLAGS.batch_size * FLAGS.num_gpus\n examples_per_sec = num_examples_per_step / duration\n sec_per_batch = duration / FLAGS.num_gpus\n\n format_str = ('%s: step %d, loss = %.2f (%.1f examples/sec; %.3f '\n 'sec/batch)')\n print (format_str % (datetime.now(), step, loss_value,\n examples_per_sec, sec_per_batch))\n\n if step % 100 == 0:\n summary_str = sess.run(summary_op)\n summary_writer.add_summary(summary_str, step)\n\n # Save the model checkpoint periodically.\n if step % 1000 == 0 or (step + 1) == FLAGS.max_steps:\n checkpoint_path = os.path.join(FLAGS.train_dir, 'model.ckpt')\n saver.save(sess, checkpoint_path, global_step=step)\n\n\ndef main(argv=None): # pylint: disable=unused-argument\n cifar10.maybe_download_and_extract()\n if tf.gfile.Exists(FLAGS.train_dir):\n tf.gfile.DeleteRecursively(FLAGS.train_dir)\n tf.gfile.MakeDirs(FLAGS.train_dir)\n train()\n\n\nif __name__ == '__main__':\n tf.app.run()\n",
"# -*- coding: utf-8 -*-\n# Copyright 2015 Google Inc. 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\n\"\"\"Tests for tensorflow.python.ops.io_ops.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tempfile\n\nimport tensorflow as tf\n\n\nclass IoOpsTest(tf.test.TestCase):\n\n def testReadFile(self):\n cases = ['', 'Some contents', 'Неки садржаји на српском']\n for contents in cases:\n contents = tf.compat.as_bytes(contents)\n temp = tempfile.NamedTemporaryFile(prefix='ReadFileTest')\n open(temp.name, 'wb').write(contents)\n with self.test_session():\n read = tf.read_file(temp.name)\n self.assertEqual([], read.get_shape())\n self.assertEqual(read.eval(), contents)\n\n def _subset(self, files, indices):\n return set(tf.compat.as_bytes(files[i].name)\n for i in range(len(files)) if i in indices)\n\n def testMatchingFiles(self):\n cases = ['ABcDEF.GH', 'ABzDEF.GH', 'ABasdfjklDEF.GH', 'AB3DEF.GH',\n 'AB4DEF.GH', 'ABDEF.GH', 'XYZ']\n files = [tempfile.NamedTemporaryFile(prefix=c) for c in cases]\n\n with self.test_session():\n # Test exact match without wildcards.\n for f in files:\n self.assertEqual(tf.matching_files(f.name).eval(),\n tf.compat.as_bytes(f.name))\n\n # We will look for files matching \"ABxDEF.GH*\" where \"x\" is some wildcard.\n pos = files[0].name.find(cases[0])\n pattern = files[0].name[:pos] + 'AB%sDEF.GH*'\n\n self.assertEqual(set(tf.matching_files(pattern % 'z').eval()),\n self._subset(files, [1]))\n self.assertEqual(set(tf.matching_files(pattern % '?').eval()),\n self._subset(files, [0, 1, 3, 4]))\n self.assertEqual(set(tf.matching_files(pattern % '*').eval()),\n self._subset(files, [0, 1, 2, 3, 4, 5]))\n self.assertEqual(set(tf.matching_files(pattern % '[cxz]').eval()),\n self._subset(files, [0, 1]))\n self.assertEqual(set(tf.matching_files(pattern % '[0-9]').eval()),\n self._subset(files, [3, 4]))\n\n\nif __name__ == '__main__':\n tf.test.main()\n",
"# Copyright 2015 Google Inc. 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\n\"\"\"Tests for tensorflow.ops.tf.Assign*.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\n\nclass AssignOpTest(tf.test.TestCase):\n\n def _initAssignFetch(self, x, y, use_gpu=False):\n \"\"\"Initialize a param to init and update it with y.\"\"\"\n super(AssignOpTest, self).setUp()\n with self.test_session(use_gpu=use_gpu):\n p = tf.Variable(x)\n assign = tf.assign(p, y)\n p.initializer.run()\n new_value = assign.eval()\n return p.eval(), new_value\n\n def _initAssignAddFetch(self, x, y, use_gpu=False):\n \"\"\"Initialize a param to init, and compute param += y.\"\"\"\n with self.test_session(use_gpu=use_gpu):\n p = tf.Variable(x)\n add = tf.assign_add(p, y)\n p.initializer.run()\n new_value = add.eval()\n return p.eval(), new_value\n\n def _initAssignSubFetch(self, x, y, use_gpu=False):\n \"\"\"Initialize a param to init, and compute param -= y.\"\"\"\n with self.test_session(use_gpu=use_gpu):\n p = tf.Variable(x)\n sub = tf.assign_sub(p, y)\n p.initializer.run()\n new_value = sub.eval()\n return p.eval(), new_value\n\n def _testTypes(self, vals):\n for dtype in [np.float32, np.float64, np.int32, np.int64]:\n x = np.zeros(vals.shape).astype(dtype)\n y = vals.astype(dtype)\n var_value, op_value = self._initAssignFetch(x, y, use_gpu=False)\n self.assertAllEqual(y, var_value)\n self.assertAllEqual(y, op_value)\n var_value, op_value = self._initAssignAddFetch(x, y, use_gpu=False)\n self.assertAllEqual(x + y, var_value)\n self.assertAllEqual(x + y, op_value)\n var_value, op_value = self._initAssignSubFetch(x, y, use_gpu=False)\n self.assertAllEqual(x - y, var_value)\n self.assertAllEqual(x - y, op_value)\n if tf.test.is_built_with_cuda() and dtype in [np.float32, np.float64]:\n var_value, op_value = self._initAssignFetch(x, y, use_gpu=True)\n self.assertAllEqual(y, var_value)\n self.assertAllEqual(y, op_value)\n var_value, op_value = self._initAssignAddFetch(x, y, use_gpu=True)\n self.assertAllEqual(x + y, var_value)\n self.assertAllEqual(x + y, op_value)\n var_value, op_value = self._initAssignSubFetch(x, y, use_gpu=False)\n self.assertAllEqual(x - y, var_value)\n self.assertAllEqual(x - y, op_value)\n\n def testBasic(self):\n self._testTypes(np.arange(0, 20).reshape([4, 5]))\n\n def testAssignNonStrictShapeChecking(self):\n with self.test_session():\n data = tf.fill([1024, 1024], 0)\n p = tf.Variable([1])\n a = tf.assign(p, data, validate_shape=False)\n a.op.run()\n self.assertAllEqual(p.eval(), data.eval())\n\n # Assign to yet another shape\n data2 = tf.fill([10, 10], 1)\n a2 = tf.assign(p, data2, validate_shape=False)\n a2.op.run()\n self.assertAllEqual(p.eval(), data2.eval())\n\n def testInitRequiredAssignAdd(self):\n with self.test_session():\n p = tf.Variable(tf.fill([1024, 1024], 1),\n tf.int32)\n a = tf.assign_add(p, tf.fill([1024, 1024], 0))\n with self.assertRaisesOpError(\"use uninitialized\"):\n a.op.run()\n\n def testInitRequiredAssignSub(self):\n with self.test_session():\n p = tf.Variable(tf.fill([1024, 1024], 1),\n tf.int32)\n a = tf.assign_sub(p, tf.fill([1024, 1024], 0))\n with self.assertRaisesOpError(\"use uninitialized\"):\n a.op.run()\n\n # NOTE(mrry): See also\n # dense_update_ops_no_tsan_test.AssignOpTest, which contains a benign\n # data race and must run without TSAN.\n def testParallelUpdateWithLocking(self):\n with self.test_session() as sess:\n zeros_t = tf.fill([1024, 1024], 0.0)\n ones_t = tf.fill([1024, 1024], 1.0)\n p = tf.Variable(zeros_t)\n adds = [tf.assign_add(p, ones_t, use_locking=True)\n for _ in range(20)]\n p.initializer.run()\n\n def run_add(add_op):\n sess.run(add_op)\n threads = [\n self.checkedThread(target=run_add, args=(add_op,)) for add_op in adds]\n for t in threads:\n t.start()\n for t in threads:\n t.join()\n\n vals = p.eval()\n ones = np.ones((1024, 1024)).astype(np.float32)\n self.assertAllEqual(vals, ones * 20)\n\n # NOTE(mrry): See also\n # dense_update_ops_no_tsan_test.[...].testParallelAssignWithoutLocking,\n # which contains a benign data race and must run without TSAN.\n def testParallelAssignWithLocking(self):\n with self.test_session() as sess:\n zeros_t = tf.fill([1024, 1024], 0.0)\n ones_t = tf.fill([1024, 1024], 1.0)\n p = tf.Variable(zeros_t)\n assigns = [tf.assign(p, tf.mul(ones_t, float(i)),\n use_locking=True)\n for i in range(1, 21)]\n p.initializer.run()\n\n def run_assign(assign_op):\n sess.run(assign_op)\n threads = [self.checkedThread(target=run_assign, args=(assign_op,))\n for assign_op in assigns]\n for t in threads:\n t.start()\n for t in threads:\n t.join()\n\n vals = p.eval()\n\n # Assert every element is the same, and taken from one of the assignments.\n self.assertTrue(vals[0, 0] > 0)\n self.assertTrue(vals[0, 0] <= 20)\n self.assertAllEqual(vals, np.ones([1024, 1024]) * vals[0, 0])\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n"
] | [
[
"tensorflow.Graph",
"tensorflow.constant",
"numpy.cosh",
"numpy.fft.rfft",
"tensorflow.zeros",
"tensorflow.test.main",
"numpy.sinh",
"tensorflow.python.ops.script_ops._py_funcs.size",
"numpy.array",
"tensorflow.py_func"
],
[
"tensorflow.fill",
"tensorflow.assign_add",
"tensorflow.zeros",
"tensorflow.test.main",
"numpy.ones",
"tensorflow.initialize_all_variables"
],
[
"tensorflow.models.rnn.translate.seq2seq_model.Seq2SeqModel",
"tensorflow.train.get_checkpoint_state",
"tensorflow.models.rnn.translate.data_utils.prepare_wmt_data",
"tensorflow.gfile.Exists",
"tensorflow.gfile.GFile",
"tensorflow.app.flags.DEFINE_integer",
"numpy.random.random_sample",
"tensorflow.initialize_all_variables",
"tensorflow.models.rnn.translate.data_utils.initialize_vocabulary",
"tensorflow.app.flags.DEFINE_string",
"numpy.argmax",
"tensorflow.app.flags.DEFINE_float",
"tensorflow.Session",
"tensorflow.models.rnn.translate.data_utils.sentence_to_token_ids",
"tensorflow.app.flags.DEFINE_boolean",
"tensorflow.app.run"
],
[
"tensorflow.python.ops.standard_ops.group",
"tensorflow.core.framework.graph_pb2.NodeDef",
"tensorflow.python.framework.ops.Graph",
"tensorflow.python.ops.standard_ops.constant",
"tensorflow.python.platform.googletest.main"
],
[
"tensorflow.python.ops.gen_array_ops._broadcast_gradient_args",
"tensorflow.test.main"
],
[
"tensorflow.python.framework.ops.IndexedSlices",
"tensorflow.python.framework.ops.convert_to_tensor",
"tensorflow.python.training.training_ops.apply_gradient_descent"
],
[
"tensorflow.device",
"tensorflow.concat",
"tensorflow.gfile.DeleteRecursively",
"tensorflow.control_dependencies",
"tensorflow.gfile.Exists",
"tensorflow.train.ExponentialMovingAverage",
"tensorflow.gfile.MakeDirs",
"tensorflow.app.flags.DEFINE_string",
"tensorflow.models.image.cifar10.cifar10.loss",
"tensorflow.app.flags.DEFINE_boolean",
"tensorflow.group",
"tensorflow.add_n",
"tensorflow.merge_summary",
"tensorflow.all_variables",
"tensorflow.Graph",
"tensorflow.get_collection",
"tensorflow.app.flags.DEFINE_integer",
"tensorflow.train.exponential_decay",
"tensorflow.ConfigProto",
"tensorflow.initialize_all_variables",
"tensorflow.models.image.cifar10.cifar10.inference",
"tensorflow.name_scope",
"tensorflow.trainable_variables",
"tensorflow.models.image.cifar10.cifar10.distorted_inputs",
"tensorflow.app.run",
"numpy.isnan",
"tensorflow.identity",
"tensorflow.train.GradientDescentOptimizer",
"tensorflow.models.image.cifar10.cifar10.maybe_download_and_extract",
"tensorflow.reduce_mean",
"tensorflow.train.start_queue_runners",
"tensorflow.scalar_summary",
"tensorflow.expand_dims",
"tensorflow.train.SummaryWriter",
"tensorflow.constant_initializer",
"tensorflow.histogram_summary",
"tensorflow.get_variable_scope"
],
[
"tensorflow.compat.as_bytes",
"tensorflow.matching_files",
"tensorflow.test.main",
"tensorflow.read_file"
],
[
"tensorflow.fill",
"tensorflow.assign_add",
"tensorflow.Variable",
"numpy.arange",
"tensorflow.test.is_built_with_cuda",
"tensorflow.assign",
"tensorflow.test.main",
"numpy.ones",
"tensorflow.assign_sub",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.8",
"1.10",
"1.12",
"2.7",
"2.6",
"1.4",
"1.13",
"2.3",
"2.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.2",
"1.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"0.12"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
cat-astrophic/pollution_growth | [
"3f245a8dd957bce5aebec41a8b984f0d7aab036d"
] | [
"pollution_A_data_maker.py"
] | [
"# This script creates the competition intensity values for the weighted total trade networks\r\n\r\n# Importing required modules\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\n# Reading in the data\r\n\r\nmain_data = pd.read_csv('C:/Users/User/Documents/Data/Pollution/pollution_data.csv')\r\n\r\n# Creating a list of all nations\r\n\r\nnations = sorted(main_data.Country.unique().tolist())\r\n\r\n# Initializing some dataframes\r\n\r\nCO2_df = pd.DataFrame()\r\nCH4_df = pd.DataFrame()\r\nNOX_df = pd.DataFrame()\r\nGHG_df = pd.DataFrame()\r\n\r\n# Defining two helper functions for subsetting nations to only those with viable data\r\n\r\n# This fucntion restricts nations to those with trade network data\r\n\r\ndef emissions_lists(xxx_nations, ccc_nations, nations):\r\n \r\n for c in nations:\r\n \r\n if c not in ccc_nations: # this will be comp_nations in our case\r\n \r\n xxx_nations.remove(c)\r\n \r\n return xxx_nations\r\n\r\n# This function further restricts nations to those with intensity data\r\n\r\ndef extant_intensity(ydat, listy, emission):\r\n \r\n listy2 = [l for l in listy]\r\n \r\n for n in listy2:\r\n \r\n if (ydat[emission][ydat.Country.tolist().index(n)] > 0) == False:\r\n \r\n listy.remove(n)\r\n \r\n return listy\r\n \r\n# A list of years to iterate through\r\n\r\nyrs = [i for i in range(1970,2015)]\r\n\r\n# The main loop\r\n\r\nfor y in yrs:\r\n \r\n # Cute message\r\n \r\n print('Creating data for year ' + str(y) + '.......')\r\n \r\n # Refresh lists of nations to pare down\r\n \r\n comp_nations = sorted(main_data.Country.unique().tolist())\r\n co2_nations = sorted(main_data.Country.unique().tolist())\r\n ch4_nations = sorted(main_data.Country.unique().tolist())\r\n nox_nations = sorted(main_data.Country.unique().tolist())\r\n ghg_nations = sorted(main_data.Country.unique().tolist())\r\n \r\n # Load W matrix for year y\r\n \r\n A_co2 = pd.read_csv('C:/Users/User/Documents/Data/Pollution/Networks/A_' + str(y) + '.csv')\r\n A_ch4 = pd.read_csv('C:/Users/User/Documents/Data/Pollution/Networks/A_' + str(y) + '.csv')\r\n A_nox = pd.read_csv('C:/Users/User/Documents/Data/Pollution/Networks/A_' + str(y) + '.csv')\r\n A_ghg = pd.read_csv('C:/Users/User/Documents/Data/Pollution/Networks/A_' + str(y) + '.csv')\r\n \r\n # Determining which countries have all data for current year\r\n \r\n # Subset to current year\r\n \r\n ydata = main_data[main_data['Year'] == y].reset_index().drop('index', axis = 1)\r\n \r\n # Check that each country engaged in competitive behavior\r\n \r\n for n in nations:\r\n \r\n if (n in A_co2.columns.tolist()) == False:\r\n \r\n comp_nations.remove(n)\r\n \r\n elif sum(A_co2[n]) == 0:\r\n \r\n comp_nations.remove(n)\r\n \r\n # Creating a beginning for emissions lists\r\n \r\n co2_nations = emissions_lists(co2_nations, comp_nations, nations)\r\n ch4_nations = emissions_lists(ch4_nations, comp_nations, nations)\r\n nox_nations = emissions_lists(nox_nations, comp_nations, nations)\r\n ghg_nations = emissions_lists(ghg_nations, comp_nations, nations)\r\n \r\n # Further paring down emissions lists based on the existence of intensities data\r\n \r\n co2_nations = extant_intensity(ydata, co2_nations, 'co2_intensity')\r\n ch4_nations = extant_intensity(ydata, ch4_nations, 'ch4_intensity')\r\n nox_nations = extant_intensity(ydata, nox_nations, 'nox_intensity')\r\n ghg_nations = extant_intensity(ydata, ghg_nations, 'ghg_intensity')\r\n \r\n # Remove extra rows and columns from TC - for each intensity\r\n \r\n co2_indices = A_co2.columns.tolist()\r\n ch4_indices = A_ch4.columns.tolist()\r\n nox_indices = A_nox.columns.tolist()\r\n ghg_indices = A_ghg.columns.tolist()\r\n \r\n co2_indices.reverse()\r\n ch4_indices.reverse()\r\n nox_indices.reverse()\r\n ghg_indices.reverse()\r\n \r\n for col in co2_indices:\r\n \r\n if col not in co2_nations:\r\n \r\n A_co2 = A_co2.drop(A_co2.columns.tolist().index(col), axis = 0)\r\n A_co2 = A_co2.drop(col, axis = 1)\r\n \r\n for col in ch4_indices:\r\n \r\n if col not in ch4_nations:\r\n \r\n A_ch4 = A_ch4.drop(A_ch4.columns.tolist().index(col), axis = 0)\r\n A_ch4 = A_ch4.drop(col, axis = 1)\r\n \r\n for col in nox_indices:\r\n \r\n if col not in nox_nations:\r\n \r\n A_nox = A_nox.drop(A_nox.columns.tolist().index(col), axis = 0)\r\n A_nox = A_nox.drop(col, axis = 1)\r\n \r\n for col in ghg_indices:\r\n \r\n if col not in ghg_nations:\r\n \r\n A_ghg = A_ghg.drop(A_ghg.columns.tolist().index(col), axis = 0)\r\n A_ghg = A_ghg.drop(col, axis = 1)\r\n \r\n # Normalize TC - for each intensity\r\n \r\n # This creates a row normalized matrix -- normalized exports!\r\n \r\n co2_sums = [sum(A_co2.iloc[row]) for row in range(len(A_co2))]\r\n ch4_sums = [sum(A_ch4.iloc[row]) for row in range(len(A_ch4))]\r\n nox_sums = [sum(A_nox.iloc[row]) for row in range(len(A_nox))]\r\n ghg_sums = [sum(A_ghg.iloc[row]) for row in range(len(A_ghg))]\r\n \r\n M_co2 = np.matrix(A_co2)\r\n M_ch4 = np.matrix(A_ch4)\r\n M_nox = np.matrix(A_nox)\r\n M_ghg = np.matrix(A_ghg)\r\n \r\n for row in range(len(co2_sums)):\r\n \r\n M_co2[row,:] = M_co2[row,:] / co2_sums[row]\r\n \r\n for row in range(len(ch4_sums)):\r\n \r\n M_ch4[row,:] = M_ch4[row,:] / ch4_sums[row]\r\n \r\n for row in range(len(nox_sums)):\r\n \r\n M_nox[row,:] = M_nox[row,:] / nox_sums[row]\r\n \r\n for row in range(len(ghg_sums)):\r\n \r\n M_ghg[row,:] = M_ghg[row,:] / ghg_sums[row]\r\n \r\n # Create vector of actual emissions intensities\r\n \r\n co2_ints = np.matrix([ydata.co2_intensity[ydata.Country.tolist().index(n)] for n in co2_nations]).T\r\n ch4_ints = np.matrix([ydata.ch4_intensity[ydata.Country.tolist().index(n)] for n in ch4_nations]).T\r\n nox_ints = np.matrix([ydata.nox_intensity[ydata.Country.tolist().index(n)] for n in nox_nations]).T\r\n ghg_ints = np.matrix([ydata.ghg_intensity[ydata.Country.tolist().index(n)] for n in ghg_nations]).T\r\n \r\n # Multpliy matrix X vector - for each intensity\r\n \r\n co2_data = np.matmul(M_co2,co2_ints)\r\n ch4_data = np.matmul(M_ch4,ch4_ints)\r\n nox_data = np.matmul(M_nox,nox_ints)\r\n ghg_data = np.matmul(M_ghg,ghg_ints)\r\n \r\n # Append to DataFrame\r\n \r\n current_year = [y for c in co2_nations]\r\n next_year = [y+1 for c in co2_nations]\r\n co2_d = [x[0] for x in co2_data.tolist()]\r\n temp_co2 = pd.DataFrame({'Current Year':current_year, 'Next Year':next_year,\r\n 'Nation':co2_nations, 'CO2 Data':co2_d})\r\n CO2_df = pd.concat([CO2_df, temp_co2], axis = 0)\r\n \r\n current_year = [y for c in ch4_nations]\r\n next_year = [y+1 for c in ch4_nations]\r\n ch4_d = [x[0] for x in ch4_data.tolist()]\r\n temp_ch4 = pd.DataFrame({'Current Year':current_year, 'Next Year':next_year,\r\n 'Nation':ch4_nations, 'CH4 Data':ch4_d})\r\n CH4_df = pd.concat([CH4_df, temp_ch4], axis = 0)\r\n \r\n current_year = [y for c in nox_nations]\r\n next_year = [y+1 for c in nox_nations]\r\n nox_d = [x[0] for x in nox_data.tolist()]\r\n temp_nox = pd.DataFrame({'Current Year':current_year, 'Next Year':next_year,\r\n 'Nation':nox_nations, 'NOX Data':nox_d})\r\n NOX_df = pd.concat([NOX_df, temp_nox], axis = 0)\r\n \r\n current_year = [y for c in ghg_nations]\r\n next_year = [y+1 for c in ghg_nations]\r\n ghg_d = [x[0] for x in ghg_data.tolist()]\r\n temp_ghg = pd.DataFrame({'Current Year':current_year, 'Next Year':next_year,\r\n 'Nation':ghg_nations, 'GHG Data':ghg_d})\r\n GHG_df = pd.concat([GHG_df, temp_ghg], axis = 0)\r\n \r\n# Write dataframe to file\r\n\r\nCO2_df.to_csv('C:/Users/User/Documents/Data/Pollution/A_DATA_CO2.csv', index = False)\r\nCH4_df.to_csv('C:/Users/User/Documents/Data/Pollution/A_DATA_CH4.csv', index = False)\r\nNOX_df.to_csv('C:/Users/User/Documents/Data/Pollution/A_DATA_NOX.csv', index = False)\r\nGHG_df.to_csv('C:/Users/User/Documents/Data/Pollution/A_DATA_GHG.csv', index = False)\r\n \r\n"
] | [
[
"numpy.matrix",
"pandas.concat",
"pandas.read_csv",
"numpy.matmul",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
brianchung0803/GMA | [
"5c5647ae248f77f47d5b5cf0281933635b37e631"
] | [
"core/utils/augmentor.py"
] | [
"import numpy as np\nimport random\nimport math\nfrom PIL import Image\n\nimport cv2\ncv2.setNumThreads(0)\ncv2.ocl.setUseOpenCL(False)\n\nimport torch\nfrom torchvision.transforms import ColorJitter\nimport torch.nn.functional as F\n\n\nclass FlowAugmentor:\n def __init__(self, crop_size, min_scale=-0.2, max_scale=0.5, do_flip=True):\n \n # spatial augmentation params\n self.crop_size = crop_size\n self.min_scale = min_scale\n self.max_scale = max_scale\n self.spatial_aug_prob = 0.8\n self.stretch_prob = 0.8\n self.max_stretch = 0.2\n\n # flip augmentation params\n self.do_flip = do_flip\n self.h_flip_prob = 0.5\n self.v_flip_prob = 0.1\n\n # photometric augmentation params\n self.photo_aug = ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4, hue=0.5/3.14)\n self.asymmetric_color_aug_prob = 0.2\n self.eraser_aug_prob = 0.5\n\n def color_transform(self, img1, img2):\n \"\"\" Photometric augmentation \"\"\"\n\n # asymmetric\n if np.random.rand() < self.asymmetric_color_aug_prob:\n img1 = np.array(self.photo_aug(Image.fromarray(img1)), dtype=np.uint8)\n img2 = np.array(self.photo_aug(Image.fromarray(img2)), dtype=np.uint8)\n\n # symmetric\n else:\n image_stack = np.concatenate([img1, img2], axis=0)\n image_stack = np.array(self.photo_aug(Image.fromarray(image_stack)), dtype=np.uint8)\n img1, img2 = np.split(image_stack, 2, axis=0)\n\n return img1, img2\n\n def eraser_transform(self, img1, img2, bounds=[50, 100]):\n \"\"\" Occlusion augmentation \"\"\"\n\n ht, wd = img1.shape[:2]\n if np.random.rand() < self.eraser_aug_prob:\n mean_color = np.mean(img2.reshape(-1, 3), axis=0)\n for _ in range(np.random.randint(1, 3)):\n x0 = np.random.randint(0, wd)\n y0 = np.random.randint(0, ht)\n dx = np.random.randint(bounds[0], bounds[1])\n dy = np.random.randint(bounds[0], bounds[1])\n img2[y0:y0+dy, x0:x0+dx, :] = mean_color\n\n return img1, img2\n\n def spatial_transform(self, img1, img2, flow):\n # randomly sample scale\n ht, wd = img1.shape[:2]\n min_scale = np.maximum(\n (self.crop_size[0] + 8) / float(ht), \n (self.crop_size[1] + 8) / float(wd))\n\n scale = 2 ** np.random.uniform(self.min_scale, self.max_scale)\n scale_x = scale\n scale_y = scale\n if np.random.rand() < self.stretch_prob:\n scale_x *= 2 ** np.random.uniform(-self.max_stretch, self.max_stretch)\n scale_y *= 2 ** np.random.uniform(-self.max_stretch, self.max_stretch)\n \n scale_x = np.clip(scale_x, min_scale, None)\n scale_y = np.clip(scale_y, min_scale, None)\n\n if np.random.rand() < self.spatial_aug_prob:\n # rescale the images\n img1 = cv2.resize(img1, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR)\n img2 = cv2.resize(img2, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR)\n flow = cv2.resize(flow, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR)\n flow = flow * [scale_x, scale_y]\n\n if self.do_flip:\n if np.random.rand() < self.h_flip_prob: # h-flip\n img1 = img1[:, ::-1]\n img2 = img2[:, ::-1]\n flow = flow[:, ::-1] * [-1.0, 1.0]\n\n if np.random.rand() < self.v_flip_prob: # v-flip\n img1 = img1[::-1, :]\n img2 = img2[::-1, :]\n flow = flow[::-1, :] * [1.0, -1.0]\n\n y0 = np.random.randint(0, img1.shape[0] - self.crop_size[0])\n x0 = np.random.randint(0, img1.shape[1] - self.crop_size[1])\n \n img1 = img1[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]\n img2 = img2[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]\n flow = flow[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]\n\n return img1, img2, flow\n\n def __call__(self, img1, img2, flow):\n img1, img2 = self.color_transform(img1, img2)\n img1, img2 = self.eraser_transform(img1, img2)\n img1, img2, flow = self.spatial_transform(img1, img2, flow)\n\n img1 = np.ascontiguousarray(img1)\n img2 = np.ascontiguousarray(img2)\n flow = np.ascontiguousarray(flow)\n\n return img1, img2, flow\n\n\nclass SparseFlowAugmentor:\n def __init__(self, crop_size, min_scale=-0.2, max_scale=0.5, do_flip=False):\n # spatial augmentation params\n self.crop_size = crop_size\n self.min_scale = min_scale\n self.max_scale = max_scale\n self.spatial_aug_prob = 0.8\n self.stretch_prob = 0.8\n self.max_stretch = 0.2\n\n # flip augmentation params\n self.do_flip = do_flip\n self.h_flip_prob = 0.5\n self.v_flip_prob = 0.1\n\n # photometric augmentation params\n self.photo_aug = ColorJitter(brightness=0.3, contrast=0.3, saturation=0.3, hue=0.3/3.14)\n self.asymmetric_color_aug_prob = 0.2\n self.eraser_aug_prob = 0.5\n \n def color_transform(self, img1, img2):\n image_stack = np.concatenate([img1, img2], axis=0)\n image_stack = np.array(self.photo_aug(Image.fromarray(image_stack)), dtype=np.uint8)\n img1, img2 = np.split(image_stack, 2, axis=0)\n return img1, img2\n\n def eraser_transform(self, img1, img2):\n ht, wd = img1.shape[:2]\n if np.random.rand() < self.eraser_aug_prob:\n mean_color = np.mean(img2.reshape(-1, 3), axis=0)\n for _ in range(np.random.randint(1, 3)):\n x0 = np.random.randint(0, wd)\n y0 = np.random.randint(0, ht)\n dx = np.random.randint(50, 100)\n dy = np.random.randint(50, 100)\n img2[y0:y0+dy, x0:x0+dx, :] = mean_color\n\n return img1, img2\n\n def resize_sparse_flow_map(self, flow, valid, fx=1.0, fy=1.0):\n ht, wd = flow.shape[:2]\n coords = np.meshgrid(np.arange(wd), np.arange(ht))\n coords = np.stack(coords, axis=-1)\n\n coords = coords.reshape(-1, 2).astype(np.float32)\n flow = flow.reshape(-1, 2).astype(np.float32)\n valid = valid.reshape(-1).astype(np.float32)\n\n coords0 = coords[valid>=1]\n flow0 = flow[valid>=1]\n\n ht1 = int(round(ht * fy))\n wd1 = int(round(wd * fx))\n\n coords1 = coords0 * [fx, fy]\n flow1 = flow0 * [fx, fy]\n\n xx = np.round(coords1[:,0]).astype(np.int32)\n yy = np.round(coords1[:,1]).astype(np.int32)\n\n v = (xx > 0) & (xx < wd1) & (yy > 0) & (yy < ht1)\n xx = xx[v]\n yy = yy[v]\n flow1 = flow1[v]\n\n flow_img = np.zeros([ht1, wd1, 2], dtype=np.float32)\n valid_img = np.zeros([ht1, wd1], dtype=np.int32)\n\n flow_img[yy, xx] = flow1\n valid_img[yy, xx] = 1\n\n return flow_img, valid_img\n\n def spatial_transform(self, img1, img2, flow, valid):\n # randomly sample scale\n\n ht, wd = img1.shape[:2]\n min_scale = np.maximum(\n (self.crop_size[0] + 1) / float(ht), \n (self.crop_size[1] + 1) / float(wd))\n\n scale = 2 ** np.random.uniform(self.min_scale, self.max_scale)\n scale_x = np.clip(scale, min_scale, None)\n scale_y = np.clip(scale, min_scale, None)\n\n if np.random.rand() < self.spatial_aug_prob:\n # rescale the images\n img1 = cv2.resize(img1, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR)\n img2 = cv2.resize(img2, None, fx=scale_x, fy=scale_y, interpolation=cv2.INTER_LINEAR)\n flow, valid = self.resize_sparse_flow_map(flow, valid, fx=scale_x, fy=scale_y)\n\n if self.do_flip:\n if np.random.rand() < 0.5: # h-flip\n img1 = img1[:, ::-1]\n img2 = img2[:, ::-1]\n flow = flow[:, ::-1] * [-1.0, 1.0]\n valid = valid[:, ::-1]\n\n margin_y = 20\n margin_x = 50\n\n y0 = np.random.randint(0, img1.shape[0] - self.crop_size[0] + margin_y)\n x0 = np.random.randint(-margin_x, img1.shape[1] - self.crop_size[1] + margin_x)\n\n y0 = np.clip(y0, 0, img1.shape[0] - self.crop_size[0])\n x0 = np.clip(x0, 0, img1.shape[1] - self.crop_size[1])\n\n img1 = img1[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]\n img2 = img2[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]\n flow = flow[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]\n valid = valid[y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]\n return img1, img2, flow, valid\n\n def __call__(self, img1, img2, flow, valid):\n img1, img2 = self.color_transform(img1, img2)\n img1, img2 = self.eraser_transform(img1, img2)\n img1, img2, flow, valid = self.spatial_transform(img1, img2, flow, valid)\n\n img1 = np.ascontiguousarray(img1)\n img2 = np.ascontiguousarray(img2)\n flow = np.ascontiguousarray(flow)\n valid = np.ascontiguousarray(valid)\n\n return img1, img2, flow, valid\n"
] | [
[
"numpy.split",
"numpy.clip",
"numpy.ascontiguousarray",
"numpy.arange",
"numpy.stack",
"numpy.concatenate",
"numpy.round",
"numpy.random.rand",
"numpy.random.uniform",
"numpy.zeros",
"numpy.random.randint"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jphkun/CEASIOMpy | [
"6425cfeb786019fccfc98aaa2fd676b2de466dac",
"6425cfeb786019fccfc98aaa2fd676b2de466dac"
] | [
"ceasiompy/utils/WB/UncGeometry/WithFuseGeom/Wings/wingsgeom.py",
"ceasiompy/utils/optimfunctions.py"
] | [
"\"\"\"\nCEASIOMpy: Conceptual Aircraft Design Software\n\nDeveloped for CFS ENGINEERING, 1015 Lausanne, Switzerland\n\nThe script evaluate the wings geometry from cpacs file for an\nunconventional aircraft with fuselage.\n\nPython version: >=3.6\n\n| Author : Stefano Piccini\n| Date of creation: 2018-09-27\n| Last modifiction: 2020-01-22 (AJ)\n\n\"\"\"\n\n#==============================================================================\n# IMPORTS\n#==============================================================================\n\nimport numpy as np\nimport math\n\nimport ceasiompy.utils.cpacsfunctions as cpsf\n\nfrom ceasiompy.utils.ceasiomlogger import get_logger\n\nlog = get_logger(__file__.split('.')[0])\n\n\n#==============================================================================\n# CLASSES\n#==============================================================================\n\n\"\"\"All classes are defined inside the classes folder and in the\n InputClasses/Unconventional folder.\"\"\"\n\n\n#==============================================================================\n# FUNCTIONS\n#==============================================================================\n\ndef check_segment_connection(wing_plt_area_xz, wing_plt_area_yz, awg, tigl):\n \"\"\" The function checks for each segment the start and end section index\n and to reorder them.\n\n Args:\n wing_plt_area_xz (float): Wing area on the xz plane [m^2].\n wing_plt_area_yz (float): Wing area on the yz plane [m^2].\n awg (class): AircraftGeometry class look at\n aircraft_geometry_class.py in the\n classes folder for explanation.\n tigl (handel): Tigl handle.\n\n Returns:\n sec_nb (int): Number of sections for each wing.\n start_index (int) : Start section index for each wing.\n seg_sec_reordered (float-array): Reordered segments with respective\n start and end section for each wing.\n sec_index (float_array): List of section index reordered.\n \"\"\"\n\n log.info('-----------------------------------------------------------')\n log.info('---------- Checking wings segments connection -------------')\n log.info('-----------------------------------------------------------')\n\n # Initialising arrays\n nbmax = np.amax(awg.wing_seg_nb)\n seg_sec = np.zeros((nbmax,awg.w_nb,3))\n seg_sec_reordered = np.zeros(np.shape(seg_sec))\n sec_index = np.zeros((nbmax,awg.w_nb))\n start_index = []\n sec_nb = []\n\n # First for each segment the start and end section are found, then\n # they are reordered considering that the end section of a segment\n # is the start sectio of the next one.\n # The first section is the one that has the lowest y,\n # for horizontal wings, or z, for vertical wings position\n # The code works if a section is defined and not used and if the segments\n # are not define with a consequential order.\n # WARNING The code does not work if a segment is defined\n # and then not used.\n # The aircraft should be designed along the x axis\n # and on the x-y plane\n\n for i in range(1,awg.w_nb+1):\n wing_sec_index = []\n for j in range(1,awg.wing_seg_nb[i-1]+1):\n (s0,e) = tigl.wingGetInnerSectionAndElementIndex(i,j)\n (s1,e) = tigl.wingGetOuterSectionAndElementIndex(i,j)\n seg_sec[j-1,i-1,0] = s0\n seg_sec[j-1,i-1,1] = s1\n seg_sec[j-1,i-1,2] = j\n (slpx,slpy,slpz) = tigl.wingGetChordPoint(i,1,0.0,0.0)\n seg_sec_reordered[0,i-1,:] = seg_sec[0,i-1,:]\n start_index.append(1)\n for j in range(2,awg.wing_seg_nb[i-1]+1):\n (x,y,z) = tigl.wingGetChordPoint(i,j,1.0,0.0)\n if (awg.wing_plt_area[i-1] > wing_plt_area_xz[i-1]\\\n and awg.wing_plt_area[i-1] > wing_plt_area_yz[i-1]):\n if y < slpy:\n (slpx,slpy,slpz) = (x,y,z)\n start_index.append(j)\n seg_sec_reordered[0,i-1,:] = seg_sec[j-1,i-1,:]\n else:\n if z < slpz:\n (slpx,slpy,slpz) = (x,y,z)\n start_index.append(j)\n seg_sec_reordered[0,i-1,:] = seg_sec[j-1,i-1,:]\n for j in range(2,awg.wing_seg_nb[i-1]+1):\n end_sec = seg_sec_reordered[j-2,i-1,1]\n start_next = np.where(seg_sec[:,i-1,0] == end_sec)\n seg_sec_reordered[j-1,i-1,:] = seg_sec[start_next[0],i-1,:]\n wing_sec_index.append(seg_sec_reordered[0,0,0])\n for j in range(2,awg.wing_seg_nb[i-1]+1):\n if (seg_sec_reordered[j-1,i-1,0] in wing_sec_index) == False:\n wing_sec_index.append(seg_sec_reordered[j-1,i-1,0])\n if (seg_sec_reordered[j-1,i-1,1] in wing_sec_index) == False:\n wing_sec_index.append(seg_sec_reordered[j-1,i-1,1])\n nb = np.shape(wing_sec_index)\n if nb[0] > nbmax:\n nbmax = nb[0]\n sec_index.resize(nbmax,awg.w_nb)\n sec_index[0:nb[0],i-1] = wing_sec_index[0:nb[0]]\n sec_nb.append(nb[0])\n\n return(sec_nb, start_index, seg_sec_reordered, sec_index)\n\n\ndef get_wing_segment_length(awg, wing_center_section_point):\n \"\"\" The function evaluates the length of each segment of each wing,\n also considering the ones defined using symmetry.\n\n Args:\n awg (class): AircraftWingGeometry class look at\n aircraft_geometry_class.py in the\n classes folder for explanation.\n wing_center_section_point (float_array): Central point of each\n segment defined at 1/4\n of the chord [m, m, m].\n\n Returns:\n awg (class): AircraftGeometry class updated.\n \"\"\"\n\n log.info('-----------------------------------------------------------')\n log.info('---------- Evaluating wings segments length ---------------')\n log.info('-----------------------------------------------------------')\n max_seg_nb = np.amax(awg.wing_seg_nb)\n awg.wing_seg_length = np.zeros((max_seg_nb,awg.wing_nb))\n\n # To evaluate the length of each segment, the ditance of central point\n # of the start and end section of each segment is computed\n\n a = 0\n for i in range(1,awg.w_nb+1):\n for j in range(1,awg.wing_seg_nb[i-1]+1):\n (x1,y1,z1) = wing_center_section_point[j-1,i-1,:]\n (x2,y2,z2) = wing_center_section_point[j,i-1,:]\n awg.wing_seg_length[j-1][i+a-1]\\\n = (math.sqrt((x1-x2)**2+(y1-y2)**2+(z1-z2)**2))\n if awg.wing_sym[i-1] != 0:\n awg.wing_seg_length[:,i+a] = awg.wing_seg_length[:,i+a-1]\n a += 1\n\n return(awg)\n\n\ndef wing_geom_eval(w_nb, TP, awg, cpacs_in):\n \"\"\" Main function to evaluate the wings geometry\n\n Args:\n w_nb (int): Number of wings.\n TP (boolean): True if the aircraft is a turboprop.\n awg (class): AircraftWingGeometry class look at\n aircraft_geometry_class.py in the\n classes folder for explanation.\n cpacs_in (str): Path to the CPACS file\n\n Returns:\n awg (class): AircraftGeometry class updated.\n \"\"\"\n\n log.info('-----------------------------------------------------------')\n log.info('---------- Analysing wing geometry ------------------------')\n log.info('-----------------------------------------------------------')\n\n # Opening tixi and tigl\n tixi = cpsf.open_tixi(cpacs_in)\n tigl = cpsf.open_tigl(tixi)\n\n\n # INITIALIZATION 1 ---------------------------------------------------------\n\n\n awg.w_nb = w_nb\n awg.wing_nb = w_nb\n wing_plt_area_xz = []\n wing_plt_area_yz = []\n wingUID = []\n\n # Counting sections and segments--------------------------------------------\n\n b = 0\n PLT = 0\n\n for i in range(1,awg.w_nb + 1):\n double = 1\n awg.wing_sym.append(tigl.wingGetSymmetry(i))\n if awg.wing_sym[i-1] != 0:\n double = 2 # To consider the real amount of wing\n # when they are defined using symmetry\n awg.wing_nb += 1\n awg.wing_sec_nb.append(tigl.wingGetSectionCount(i))\n awg.wing_seg_nb.append(tigl.wingGetSegmentCount(i))\n awg.wing_vol.append(round(tigl.wingGetVolume(i) * double,3))\n # x-y plane\n awg.wing_plt_area.append(tigl.wingGetReferenceArea(i,1)*double)\n # x-z plane`\n wing_plt_area_xz.append(tigl.wingGetReferenceArea(i,2)*double)\n # y-z plane\n wing_plt_area_yz.append(tigl.wingGetReferenceArea(i,3)*double)\n awg.wing_tot_vol = awg.wing_tot_vol + awg.wing_vol[i-1]\n wingUID.append(tigl.wingGetUID(i))\n awg.wing_span.append(round(tigl.wingGetSpan(wingUID[i-1]),3))\n a = np.amax(awg.wing_span)\n # Evaluating the index that corresponds to the main wing\n if awg.wing_plt_area[i-1] > wing_plt_area_xz[i-1] and\\\n awg.wing_plt_area[i-1] > wing_plt_area_yz[i-1]:\n PLT += 1\n if a > b:\n awg.main_wing_index = i\n b = a\n\n # Checking segment and section connection and reordering them\n (awg.wing_sec_nb, start_index, seg_sec, wing_sec_index)\\\n = check_segment_connection(wing_plt_area_xz, wing_plt_area_yz,\\\n awg, tigl)\n\n\n # INITIALIZATION 2 ---------------------------------------------------------\n\n max_wing_sec_nb = np.amax(awg.wing_sec_nb)\n max_wing_seg_nb = np.amax(awg.wing_seg_nb)\n wing_center_section_point = np.zeros((max_wing_sec_nb, awg.w_nb, 3))\n awg.wing_center_seg_point = np.zeros((max_wing_seg_nb, awg.wing_nb, 3))\n awg.wing_seg_vol = np.zeros((max_wing_seg_nb, awg.w_nb))\n awg.wing_fuel_seg_vol = np.zeros((max_wing_seg_nb, awg.w_nb))\n awg.wing_fuel_vol = 0\n awg.wing_mac = np.zeros((4, awg.w_nb))\n awg.wing_sec_thicknes = np.zeros((max_wing_sec_nb+1, awg.w_nb))\n\n # WING ANALYSIS --------------------------------------------------------------\n\n # Main wing plantform area\n awg.wing_plt_area_main = round(awg.wing_plt_area[awg.main_wing_index-1],3)\n\n # Wing: MAC,chords,thicknes,span,plantform area ------------------------------\n for i in range(1,awg.w_nb+1):\n mac = tigl.wingGetMAC(wingUID[i-1])\n (wpx,wpy,wpz) = tigl.wingGetChordPoint(i,1,0.0,0.0)\n (wpx2,wpy2,wpz2) = tigl.wingGetChordPoint(i,1,0.0,1.0)\n awg.wing_max_chord.append(np.sqrt((wpx2-wpx)**2 + (wpy2-wpy)**2\\\n + (wpz2-wpz)**2))\n (wpx,wpy,wpz) = tigl.wingGetChordPoint(i,awg.wing_seg_nb[i-1],1.0,0.0)\n (wpx2,wpy2,wpz2) = tigl.wingGetChordPoint(i,awg.wing_seg_nb[i-1],\\\n 1.0,1.0)\n awg.wing_min_chord.append(np.sqrt((wpx2-wpx)**2 + (wpy2-wpy)**2\\\n + (wpz2-wpz)**2) )\n for k in range(1,5):\n awg.wing_mac[k-1][i-1] = mac[k-1]\n for jj in range(1,awg.wing_seg_nb[i-1]+1):\n j = int(seg_sec[jj-1,i-1,2])\n cle = tigl.wingGetChordPoint(i,j,0.0,0.0)\n awg.wing_seg_vol[j-1][i-1] = tigl.wingGetSegmentVolume(i,j)\n lp = tigl.wingGetLowerPoint(i,j,0.0,0.0)\n up = tigl.wingGetUpperPoint(i,j,0.0,0.0)\n if np.all(cle == lp):\n L = 0.25\n else:\n L = 0.75\n if np.all(cle == up):\n U = 0.25\n else:\n U = 0.75\n (wplx, wply, wplz) = tigl.wingGetLowerPoint(i,j,0.0,L)\n (wpux, wpuy, wpuz) = tigl.wingGetUpperPoint(i,j,0.0,U)\n wing_center_section_point[j-1][i-1][0] = (wplx+wpux) / 2\n wing_center_section_point[j-1][i-1][1] = (wply+wpuy) / 2\n wing_center_section_point[j-1][i-1][2] = (wplz+wpuz) / 2\n awg.wing_sec_thicknes[j-1][i-1] = np.sqrt((wpux-wplx)**2\\\n + (wpuy-wply)**2 + (wpuz-wplz)**2)\n j = int(seg_sec[awg.wing_seg_nb[i-1]-1,i-1,2])\n (wplx, wply, wplz) = tigl.wingGetLowerPoint(\\\n i,awg.wing_seg_nb[i-1],1.0,L)\n (wpux, wpuy, wpuz) = tigl.wingGetUpperPoint(\\\n i,awg.wing_seg_nb[i-1],1.0,U)\n awg.wing_sec_thicknes[j][i-1] = np.sqrt((wpux-wplx)**2\\\n + (wpuy-wply)**2 + (wpuz-wplz)**2)\n wing_center_section_point[awg.wing_seg_nb[i-1]][i-1][0] = (wplx+wpux)/2\n wing_center_section_point[awg.wing_seg_nb[i-1]][i-1][1] = (wply+wpuy)/2\n wing_center_section_point[awg.wing_seg_nb[i-1]][i-1][2] = (wplz+wpuz)/2\n awg.wing_sec_mean_thick.append(np.mean(\\\n awg.wing_sec_thicknes[0:awg.wing_seg_nb[i-1]+1,i-1]))\n\n # Evaluating wing fuel tank volume and if the wing is horizontal or vertical\n if awg.wing_plt_area[i-1] > wing_plt_area_xz[i-1] and\\\n awg.wing_plt_area[i-1] > wing_plt_area_yz[i-1]:\n tp_ratio = awg.wing_min_chord[i-1]/awg.wing_max_chord[i-1]\n if TP:\n corr = -0.05\n else:\n corr = 0.0\n if PLT == 1:\n corr += 0.05\n if tp_ratio * awg.wing_plt_area[i-1] > 80:\n awg.wing_fuel_vol += round(awg.wing_vol[i-1] * (0.7+corr),2)\n elif tp_ratio * awg.wing_plt_area[i-1] > 40:\n awg.wing_fuel_vol += round(awg.wing_vol[i-1] * (0.65+corr),2)\n elif tp_ratio * awg.wing_plt_area[i-1] > 10:\n awg.wing_fuel_vol += round(awg.wing_vol[i-1] * (0.55+corr),2)\n else:\n awg.wing_fuel_vol += 0\n for j in seg_sec[:,i-1,2]:\n if j == 0.0:\n break\n awg.wing_fuel_seg_vol[int(j)-1][i-1]\\\n = round((awg.wing_seg_vol[int(j)-1][i-1]\\\n /(sum(awg.wing_vol))) * awg.wing_fuel_vol,2)\n awg.is_horiz.append(True)\n if awg.wing_sym[i-1] != 0:\n awg.is_horiz.append(True)\n else:\n awg.is_horiz.append(False)\n if awg.wing_sym[i-1] != 0:\n awg.is_horiz.append(False)\n\n # Wing segment length evaluatin function\n awg = get_wing_segment_length(awg,wing_center_section_point)\n awg.w_seg_sec = seg_sec\n\n # Wings wetted area\n awg.tail_wings_surface = []\n for i in range(1, awg.w_nb+1):\n a = str(wingUID[i-1])\n s = tigl.wingGetSurfaceArea(i)\n if awg.wing_sym[i-1] != 0:\n s *= 2\n if i == awg.main_wing_index:\n awg.main_wing_surface = s\n else:\n awg.tail_wings_surface.append(s)\n awg.total_wings_surface += s\n\n # Evaluating the point at the center of each segment, the center\n # is placed at 1/4 of the chord, symmetry is considered.\n\n a = 0\n c = False\n for i in range(1,int(awg.wing_nb)+1):\n if c:\n c = False\n continue\n for jj in range(1,awg.wing_seg_nb[i-a-1]+1):\n j = int(seg_sec[jj-1,i-a-1,2])\n awg.wing_center_seg_point[j-1][i-1][0]\\\n = (wing_center_section_point[j-1][i-a-1][0]\\\n + wing_center_section_point[j][i-a-1][0])/2\n awg.wing_center_seg_point[j-1][i-1][1]\\\n = (wing_center_section_point[j-1][i-a-1][1]\\\n + wing_center_section_point[j][i-a-1][1])/2\n awg.wing_center_seg_point[j-1][i-1][2]\\\n = (wing_center_section_point[j-1][i-a-1][2]\\\n + wing_center_section_point[j][i-a-1][2])/2\n if awg.wing_sym[i-1-a] != 0:\n if awg.wing_sym[i-1-a] == 1:\n symy = 1\n symx = 1\n symz = -1\n if awg.wing_sym[i-1-a] == 2:\n symy = -1\n symx = 1\n symz = 1\n if awg.wing_sym[i-1-a] == 3:\n symy = 1\n symx = -1\n symz = 1\n awg.wing_center_seg_point[:,i,0]\\\n = awg.wing_center_seg_point[:,i-1,0] * symx\n awg.wing_center_seg_point[:,i,1]\\\n = awg.wing_center_seg_point[:,i-1,1] * symy\n awg.wing_center_seg_point[:,i,2]\\\n = awg.wing_center_seg_point[:,i-1,2] * symz\n c = True\n a += 1\n\n cpsf.close_tixi(tixi, cpacs_in)\n\n # log info display ---------------------------------------------------------\n log.info('-----------------------------------------------------------')\n log.info('---------- Wing Geometry Evaluation -----------------------')\n log.info('---------- USEFUL INFO ------------------------------------')\n log.info('If wing number is greater than 1 the informations of each obj \\\n are listed in an array ordered progressively')\n log.info('Number of Wings [-]: ' + str(awg.wing_nb))\n log.info('Wing symmetry plane [-]: ' + str(awg.wing_sym))\n log.info('Number of wing sections (not counting symmetry) [-]: ' + str(awg.wing_sec_nb))\n log.info('Number of wing segments (not counting symmetry) [-]: ' + str(awg.wing_seg_nb))\n log.info('Wing Span (counting symmetry)[m]: \\n' + str(awg.wing_span))\n log.info('Wing MAC length [m]: ' + str(awg.wing_mac[0,]))\n log.info('Wing MAC x,y,z coordinate [m]: \\n' + str(awg.wing_mac[1:4,]))\n log.info('Wings sections thicknes [m]: \\n' + str(awg.wing_sec_thicknes))\n log.info('Wings sections mean thicknes [m]: \\n' + str(awg.wing_sec_mean_thick))\n log.info('Wing segments length [m]: \\n' + str(awg.wing_seg_length))\n log.info('Wing max chord length [m]: \\n' + str(awg.wing_max_chord))\n log.info('Wing min chord length [m]: \\n' + str(awg.wing_min_chord))\n log.info('Main wing plantform area [m^2]: ' + str(awg.wing_plt_area_main))\n log.info('Main wing wetted surface [m^2]: ' + str(awg.main_wing_surface))\n log.info('Tail wings wetted surface [m^2]: \\n' + str(awg.tail_wings_surface))\n log.info('Wings plantform area [m^2]: \\n' + str(awg.wing_plt_area))\n log.info('Volume of each wing [m^3]: ' + str(awg.wing_vol))\n log.info('Total wing volume [m^3]: ' + str(awg.wing_tot_vol))\n log.info('Fuel volume in the wing [m^3]:' + str(awg.wing_fuel_vol))\n log.info('Total fuel Volume [m^3]:' + str(awg.fuel_vol_tot))\n log.info('-----------------------------------------------------------')\n\n return(awg)\n\n\n#==============================================================================\n# MAIN\n#==============================================================================\n\nif __name__ == '__main__':\n\n log.warning('###########################################################')\n log.warning('# ERROR NOT A STANDALONE PROGRAM, RUN balanceuncmain.py #')\n log.warning('###########################################################')\n",
"\"\"\"\nCEASIOMpy: Conceptual Aircraft Design Software.\n\nDeveloped by CFS ENGINEERING, 1015 Lausanne, Switzerland\n\nFunction library for the optimisation module.\n\nPython version: >=3.6\n\n| Author: Vivien Riolo\n| Creation: 2020-04-10\n| Last modification: 2020-04-10\n\nTodo:\n----\n * Check how to open the csv file depending on the user program\n\n\"\"\"\n\n\n# ==============================================================================\n# IMPORTS\n# ==============================================================================\nimport os\n\nfrom re import split\nimport pandas as pd\n\nimport ceasiompy.SMUse.smuse as smu\nimport ceasiompy.utils.apmfunctions as apmf\nimport ceasiompy.utils.cpacsfunctions as cpsf\nimport ceasiompy.utils.moduleinterfaces as mif\nimport ceasiompy.utils.workflowfunctions as wkf\nimport ceasiompy.Optimisation.func.tools as tls\nimport ceasiompy.Optimisation.func.dictionnary as dct\n\nfrom ceasiompy.utils.ceasiomlogger import get_logger\nlog = get_logger(__file__.split('.')[0])\n\n\n# ==============================================================================\n# GLOBALS\n# ==============================================================================\n\nMODULE_DIR = os.path.dirname(os.path.abspath(__file__))\nCPACS_OPTIM_PATH = mif.get_toolinput_file_path('Optimisation')\nCSV_PATH = MODULE_DIR+'/Variable_library.csv'\n\nWKDIR_XPATH = '/cpacs/toolspecific/CEASIOMpy/filesPath/wkdirPath'\nOPTWKDIR_XPATH = '/cpacs/toolspecific/CEASIOMpy/filesPath/optimPath'\nOPTIM_XPATH = '/cpacs/toolspecific/CEASIOMpy/Optimisation/'\nAEROMAP_XPATH = '/cpacs/vehicles/aircraft/model/analyses/aeroPerformance'\nSU2_XPATH = '/cpacs/toolspecific/CEASIOMpy/aerodynamics/su2'\n\n# Parameters that can not be used as problem variables\nbanned_entries = ['wing', 'delete_old_wkdirs', 'check_extract_loads', # Not relevant variables\n 'cabin_crew_nb', # Is an input in range and an output in weightconv\n 'MASS_CARGO' # Strange behaviour to be fixed\n ]\n\nobjective = []\nvar = {'Name':[], 'type':[], 'init':[], 'min':[], 'max':[], 'xpath':[]}\n\n# ==============================================================================\n# CLASS\n# ==============================================================================\nclass Routine:\n \"\"\"Setup the routine to launch in Openmdao.\"\"\"\n\n def __init__(self):\n \"\"\"Define default main parameters.\"\"\"\n # Choice of routine type : DOE or Optimisation\n self.type = \"Optim\"\n self.date = \"\"\n self.modules = []\n\n # Problem setup\n self.minmax = 'min' # Minimize or maximise the objective function\n self.objective = ['cl']\n\n # Driver choice\n self.driver = \"COBYLA\"\n\n # When to save the CPACS\n self.save_iter = 1\n self.max_iter = 200\n self.tol = 1e-3\n\n # DoE\n self.doedriver = 'uniform'\n self.samplesnb = 3\n self.doe_file = ''\n\n # User specified configuration file path\n self.user_config = '../Optimisation/Default_config.csv'\n self.aeromap_uid = '-'\n self.use_aeromap = False\n\n def get_user_inputs(self, tixi):\n \"\"\"Take user inputs from the GUI.\"\"\"\n\n # Problem setup\n objectives = cpsf.get_value_or_default(tixi, OPTIM_XPATH+'objective', 'cl')\n self.objective = split(';|,', objectives)\n self.minmax = cpsf.get_value_or_default(tixi, OPTIM_XPATH+'minmax', 'max')\n\n # Global parameters\n self.driver = cpsf.get_value_or_default(tixi, OPTIM_XPATH+'parameters/driver', 'COBYLA')\n self.max_iter = int(cpsf.get_value_or_default(tixi, OPTIM_XPATH+'iterationNB', 200))\n self.tol = float(cpsf.get_value_or_default(tixi, OPTIM_XPATH+'tolerance', 1e-3))\n self.save_iter = int(cpsf.get_value_or_default(tixi, OPTIM_XPATH+'saving/perIter', 1))\n\n # Specific DoE parameters\n self.doedriver = cpsf.get_value_or_default(tixi, OPTIM_XPATH+'parameters/DoE/driver', 'uniform')\n self.samplesnb = int(cpsf.get_value_or_default(tixi, OPTIM_XPATH+'parameters/DoE/sampleNB', 3))\n\n # User specified configuration file path\n self.user_config = str(cpsf.get_value_or_default(tixi, OPTIM_XPATH+'Config/filepath', '-'))\n self.aeromap_uid = str(cpsf.get_value_or_default(tixi, OPTIM_XPATH+'aeroMapUID', '-'))\n\n self.use_aeromap = cpsf.get_value_or_default(tixi, OPTIM_XPATH+'Config/useAero', False)\n\n# ==============================================================================\n# FUNCTIONS\n# ==============================================================================\n\ndef first_run(Rt):\n \"\"\"Run subworkflow once for the optimisation problem.\n\n This function runs a first loop to ensure that all problem variables\n are created an can be fed to the optimisation setup program.\n\n Args:\n Rt (Routine object): Class that contains the routine informations.\n\n Returns:\n None.\n\n \"\"\"\n log.info('Launching initialization workflow')\n Rt.modules.insert(0, 'Optimisation')\n\n # Settings needed for CFD calculation\n added_gui = False\n if 'SettingsGUI' not in Rt.modules:\n Rt.modules.insert(0, 'SettingsGUI')\n added_gui = True\n\n # First iteration to create aeromap results if no pre-workflow\n wkf.copy_module_to_module('Optimisation', 'in', Rt.modules[0], 'in')\n wkf.run_subworkflow(Rt.modules)\n wkf.copy_module_to_module(Rt.modules[-1], 'out', 'Optimisation', 'in')\n\n # SettingsGUI only needed at the first iteration\n if 'SettingsGUI' in Rt.modules and added_gui:\n Rt.modules.remove('SettingsGUI')\n\n # Optimisation parameters only needed for the first run\n Rt.modules.remove('Optimisation')\n\n\ndef gen_doe_csv(user_config):\n \"\"\"Generate adequate csv with user-defined csv.\n\n For a DoE where a CSV file is provided by the user, the format must be\n adapted to the one that will be read by the OpenMDAO DoE tool. Here it is\n ensured that the format is correct.\n\n Args:\n user_config (str): Path to user configured file.\n\n Returns:\n doe_csv (str): Path to reformated file.\n\n \"\"\"\n\n df = pd.read_csv(user_config)\n\n try:\n # Check if the name, type and at least one point are present.\n log.info(df[['Name', 'type', 0]])\n\n # Get only design variables\n df = df.loc[[i for i, v in enumerate(df['type']) if v == 'des']]\n\n # Get only name and columns with point values\n l = [i for i in df.columns if i.isdigit()]\n l.insert(0, 'Name')\n df = df[l]\n\n df = df.T\n\n except:\n pass\n doe_csv = os.path.split(user_config)[0]+'DoE_points.csv'\n\n df.to_csv(doe_csv, header=False, index=False)\n\n return doe_csv\n\n\ndef get_normal_param(tixi, entry, outputs):\n \"\"\"Add a variable to the optimisation dictionnary.\n\n It is checked if the variable has a user-specified initial value, else it\n will assign a default value or the variable will be excluded from the\n problem.\n\n Args:\n tixi (Tixi3 handle): Handle of the current CPACS file.\n entry (object): Current parameter object.\n\n Returns:\n None.\n\n \"\"\"\n\n value = '-'\n xpath = entry.xpath\n def_val = entry.default_value\n\n if not def_val:\n if entry.var_type in [float, int]:\n def_val = 0.0\n else:\n def_val = '-'\n\n if entry.var_name not in banned_entries:\n value = cpsf.get_value_or_default(tixi, xpath, def_val)\n if entry.var_type == int:\n value = int(value)\n\n if not tls.is_digit(value):\n log.info('Not a digital value')\n value = '-'\n elif entry.var_type == bool:\n log.info('Boolean, not implemented yet')\n value = '-'\n\n # Ignores values that are not int or float\n if value != '-':\n value = str(value)\n tixi.updateTextElement(xpath, value)\n\n var['init'].append(value)\n var['xpath'].append(xpath)\n var['Name'].append(entry.var_name)\n\n tls.add_type(entry, outputs, objective, var)\n tls.add_bounds(value, var)\n log.info('Value : {}'.format(value))\n log.info('Added to variable file')\n\n\ndef update_am_path(tixi, am_uid):\n \"\"\"Replace the aeromap uID for each module.\n\n Update the aeromap uID that is used for by modules in the optimisation loop\n\n Args:\n tixi (Tixi3 handle): Handle of the current CPACS file.\n am_uid (str): uID of the aeromap that will be used by all modules.\n\n Return:\n None.\n\n \"\"\"\n am_xpath = ['/cpacs/toolspecific/pytornado/aeroMapUID',\n '/cpacs/toolspecific/CEASIOMpy/aerodynamics/su2/aeroMapUID',\n '/cpacs/toolspecific/CEASIOMpy/surrogateModelUse/AeroMapOnly']\n for name in am_xpath:\n if tixi.checkElement(name):\n tixi.updateTextElement(name, am_uid)\n else:\n cpsf.create_branch(tixi, name)\n tixi.updateTextElement(name, am_uid)\n\n\ndef get_aeromap_index(tixi, am_uid):\n \"\"\"Return index of the aeromap to be used.\n\n With the aeromap uID, the index of this aeromap is returned if there are\n more than one in the CPACS file.\n\n Args:\n tixi (Tixi3 handle): Handle of the current CPACS file\n am_uid (str): uID of the aeromap that will be used by all modules.\n\n Returns:\n am_index (str): The index of the aeromap between brackets.\n\n \"\"\"\n am_list = apmf.get_aeromap_uid_list(tixi)\n am_index = '[1]'\n for i, uid in enumerate(am_list):\n if uid == am_uid:\n am_index = '[{}]'.format(i+1)\n\n return am_index\n\n\ndef get_aero_param(tixi):\n \"\"\"Add the aeromap variables to the optimisation dictionnary.\n\n Takes the variables of the aeromap that is used.\n It is checked if the variable has a user-specified initial value, else it\n will assign a default value or the variable will be excluded from the\n problem.\n\n Args:\n tixi (Tixi3 handle): Handle of the current CPACS file.\n\n Returns:\n None.\n\n \"\"\"\n log.info('Default aeromap parameters will be set')\n\n am_uid = cpsf.get_value(tixi, OPTIM_XPATH+'aeroMapUID')\n am_index = get_aeromap_index(tixi, am_uid)\n\n log.info('Aeromap \\\"{}\\\" will be used for the variables.'.format(am_uid))\n\n xpath = apmf.AEROPERFORMANCE_XPATH + '/aeroMap'\\\n + am_index + '/aeroPerformanceMap/'\n\n for name in apmf.COEF_LIST+apmf.XSTATES:\n xpath_param = xpath+name\n value = str(tixi.getDoubleElement(xpath_param))\n\n var['Name'].append(name)\n var['init'].append(value)\n var['xpath'].append(xpath_param)\n\n tls.add_type(name, apmf.COEF_LIST, objective, var)\n tls.add_bounds(value, var)\n\n\ndef get_smu_vars(tixi):\n \"\"\"Retrieves variable in the case of a surrogate.\n\n In the case of a surrogate model being used, the entries are retrieved from\n the dataframe that is saved in the SM file.\n\n Args:\n tixi (Tixi3 handler): Tixi handle of the CPACS file.\n\n Returns:\n None.\n\n \"\"\"\n Model = smu.load_surrogate(tixi)\n df = Model.df.rename(columns={'Unnamed: 0':'Name'})\n df.set_index('Name', inplace=True)\n\n for name in df.index:\n name = tls.change_var_name(name)\n if name not in var['Name'] and df.loc[name]['setcmd'] == '-':\n var['Name'].append(name)\n xpath = df.loc[name]['getcmd']\n value = str(tixi.getDoubleElement(xpath))\n var['xpath'].append(xpath)\n var['init'].append(value)\n var['type'].append(df.loc[name]['type'])\n tls.add_bounds(value, var)\n else:\n log.warning('Variable already exists')\n log.info(name+' will not be added to the variable file')\n\n\ndef get_module_vars(tixi, specs):\n \"\"\"Retrieve input and output variables of a module.\n\n Gets all the inputs and outputs of a module based on its __spec__ file,\n and decides for each parameter if it can be added to the problem or not.\n\n Returns:\n tixi (Tixi3 handler): Tixi handle of the CPACS file.\n specs (class): Contains the modules inputs and outputs specifications.\n\n Returns:\n None.\n\n \"\"\"\n aeromap = True\n inouts = specs.cpacs_inout.inputs + specs.cpacs_inout.outputs\n for entry in inouts:\n xpath = entry.xpath\n if xpath.endswith('/'):\n xpath = xpath[:-1]\n value_name = xpath.split('/')[-1]\n\n log.info('----------------------------')\n log.info('Name : '+entry.var_name)\n\n # Change the name of the entry if it's a valid accronym (ex: mtom) or\n # if it has a special sign (ex: ranges[0])\n entry.var_name = tls.change_var_name(entry.var_name)\n\n log.info(xpath)\n log.info(value_name)\n\n # Check validity of variable\n if entry.var_name == '':\n log.error('Empty name, not a valid variable name')\n elif entry.var_name in var['Name']:\n log.warning('Variable already exists')\n log.info(entry.var_name+' will not be added to the variable file')\n\n # Aeromap variable\n elif value_name == 'aeroPerformanceMap' and aeromap:\n aeromap = False\n get_aero_param(tixi)\n # Normal case\n else:\n get_normal_param(tixi, entry, specs.cpacs_inout.outputs)\n\n\ndef generate_dict(df):\n \"\"\"Generate dictionary from a dataframe.\n\n Convert a dataframe to a dictionary and modifies the dictionary in order to\n have all the necessary keys to\n\n Args:\n df (DataFrame): Contains all the variable. Used to passs from a csv to a dict\n\n Returns:\n optim_var_dict (dict): Used to pass the variables to the openMDAO setup.\n\n \"\"\"\n df.dropna(axis=0, subset=['type', 'getcmd'], inplace=True)\n if 'min' not in df.columns:\n df['min'] = '-'\n if 'max' not in df.columns:\n df['max'] = '-'\n\n defined_dict = df.to_dict('index')\n\n # Transform to a convenient form of dict\n optim_var_dict = {}\n for key, subdict in defined_dict.items():\n if subdict['initial value'] in ['False', 'True', '-'] or subdict['type'] == 'obj':\n optim_var_dict[key] = (subdict['type'], [subdict['initial value']],\n '-', '-', subdict['getcmd'], subdict['setcmd'])\n else:\n optim_var_dict[key] = (subdict['type'], [float(subdict['initial value'])],\n subdict['min'], subdict['max'],\n subdict['getcmd'], subdict['setcmd'])\n return optim_var_dict\n\n\ndef add_entries(tixi, module_list):\n \"\"\"Add the entries of all the modules.\n\n Search all the entries that can be used as problenm parameters.\n\n Args:\n tixi (Tixi3 handler): Tixi handle of the CPACS file.\n\n Returns:\n None.\n\n \"\"\"\n use_am = cpsf.get_value_or_default(tixi, smu.SMUSE_XPATH+'AeroMapOnly', False)\n if 'SMUse' in module_list and use_am:\n get_aero_param(tixi)\n else:\n for mod_name, specs in mif.get_all_module_specs().items():\n if specs and mod_name in module_list:\n if mod_name == 'SMUse':\n get_smu_vars(tixi)\n else:\n get_module_vars(tixi, specs)\n\n\ndef initialize_df():\n \"\"\"Initialize the dataframe with the entries.\n\n Setup a dataframe that contains all the entries that were found in the\n modules.\n\n Args:\n None\n\n Returns:\n None.\n\n \"\"\"\n df = pd.DataFrame(columns=['Name'], data=var['Name'])\n df['type'] = var['type']\n df['initial value'] = var['init']\n df['min'] = var['min']\n df['max'] = var['max']\n df['getcmd'] = var['xpath']\n\n return df\n\n\ndef add_geometric_vars(tixi, df):\n \"\"\"Add geometry parameters as design variables.\n\n The geometric variables are not included as module entries and must be\n added differently.\n\n Args:\n tixi (Tixi3 handler): Tixi handle of the CPACS file.\n\n Returns:\n None.\n\n \"\"\"\n geom_var = dct.init_geom_var_dict(tixi)\n for key, (var_name, [init_value], lower_bound, upper_bound, setcmd, getcmd) in geom_var.items():\n new_row = {'Name': var_name, 'type': 'des', 'initial value': init_value,\n 'min': lower_bound, 'max': upper_bound, 'getcmd': getcmd,\n 'setcmd': setcmd}\n df = df.append(new_row, ignore_index=True)\n\n df.sort_values(by=['type', 'Name'], axis=0, ignore_index=True,\n ascending=[False, True], inplace=True)\n\n return df\n\n\ndef get_default_df(tixi, module_list):\n \"\"\"Generate dataframe with all inouts.\n\n Generates a dataframe containing all the variables that could be found in\n each module and that could be used as a parameter for an optimisation or\n DoE routine.\n\n Args:\n tixi (Tixi3 handler): Tixi handle of the CPACS file.\n module_list (lst): list of modules to execute in the routine.\n\n Returns:\n df (Dataframe): Dataframe with all the module variables.\n\n \"\"\"\n add_entries(tixi, module_list)\n\n df = initialize_df()\n\n df = add_geometric_vars(tixi, df)\n\n return df\n\n\ndef create_am_lib(Rt, tixi):\n \"\"\"Create a dictionary for the aeromap coefficients.\n\n Return a dictionary with all the values of the aeromap that is used during\n the routine, so that all the results of the aeromap can later be exploited.\n\n Args:\n Rt (class): Contains all the parameters of the current routine.\n tixi (Tixi3 handler): Tixi handle of the CPACS file.\n\n Returns:\n am_dict (dct): Dictionnary with all aeromap parameters.\n\n \"\"\"\n Coef = apmf.get_aeromap(tixi, Rt.aeromap_uid)\n am_dict = Coef.to_dict()\n am_index = apmf.get_aeromap_index(tixi, Rt.aeromap_uid)\n\n xpath = apmf.AEROPERFORMANCE_XPATH + '/aeroMap'\\\n + am_index + '/aeroPerformanceMap/'\n\n for name in apmf.COEF_LIST+apmf.XSTATES:\n if name in ['altitude', 'machNumber']:\n min_val = 0\n max_val = '-'\n val_type = 'des'\n if name in apmf.COEF_LIST:\n min_val = -1\n max_val = 1\n if name in Rt.objective:\n val_type = 'obj'\n else:\n val_type = 'const'\n if name in ['angleOfAttack', 'angleOfSideslip']:\n min_val = -5\n max_val = 5\n val_type = 'des'\n am_dict[name] = (val_type, am_dict[name], min_val, max_val, xpath+name, '-')\n\n return am_dict\n\n\ndef create_variable_library(Rt, tixi, optim_dir_path):\n \"\"\"Create a dictionnary and a CSV file containing all variables that appear\n in the module list.\n\n The CSV files lists all the inputs and outputs of each module with :\n * An initial value\n * An upper and lower bound\n * The commands to get and modify the value of the parameter in the CPACS file\n * The variable type : Constraint, Design variable, Objective function component\n\n Args:\n Rt (class): Contains all the parameters of the current routine.\n tixi (Tixi3 handler): Tixi handle of the CPACS file.\n optim_dir_path (str): Path to the working directory.\n\n Returns:\n optim_var_dict (dct): Dictionnary with all optimisation parameters.\n\n \"\"\"\n global objective, var\n CSV_PATH = optim_dir_path+'/Variable_library.csv'\n\n for obj in Rt.objective:\n objective.extend(split('[+*/-]', obj))\n\n if os.path.isfile(Rt.user_config):\n log.info('Configuration file found, will be used')\n log.info(Rt.user_config)\n df = pd.read_csv(Rt.user_config, index_col=0)\n optim_var_dict = generate_dict(df)\n\n else:\n log.info('No configuration file found, default one will be generated')\n df = get_default_df(tixi, Rt.modules)\n\n # Save and open CSV file\n df.to_csv(CSV_PATH, index=False, na_rep='-')\n log.info('Variable library file has been generated')\n\n tls.launch_external_program(CSV_PATH)\n\n log.info('Variable library file has been saved at '+CSV_PATH)\n df = pd.read_csv(CSV_PATH, index_col=0, skip_blank_lines=True)\n optim_var_dict = generate_dict(df)\n\n return optim_var_dict\n\n\nif __name__ == '__main__':\n\n log.info('|-------------------------------------------------|')\n log.info('|Not a standalone module. Nothing will be executed|')\n log.info('|-------------------------------------------------|')\n"
] | [
[
"numpy.amax",
"numpy.sqrt",
"numpy.all",
"numpy.shape",
"numpy.mean",
"numpy.where",
"numpy.zeros"
],
[
"pandas.read_csv",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
ineersa/DeepPavlov | [
"8200bf9a0f0b378baad4ee0eb75b59453f516004",
"8200bf9a0f0b378baad4ee0eb75b59453f516004"
] | [
"deeppavlov/core/layers/tf_csoftmax_attention.py",
"deeppavlov/dataset_iterators/file_paths_iterator.py"
] | [
"# Copyright 2017 Neural Networks and Deep Learning lab, MIPT\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\nimport tensorflow as tf\n\n\ndef csoftmax_for_slice(input):\n \"\"\" It is a implementation of the constrained softmax (csoftmax) for slice.\n Based on the paper:\n https://andre-martins.github.io/docs/emnlp2017_final.pdf \"Learning What's Easy: Fully Differentiable Neural Easy-First Taggers\" (page 4)\n Args:\n input: A list of [input tensor, cumulative attention].\n Returns:\n output: A list of [csoftmax results, masks]\n \"\"\"\n\n [ten, u] = input\n\n shape_t = ten.shape\n shape_u = u.shape\n\n ten -= tf.reduce_mean(ten)\n q = tf.exp(ten)\n active = tf.ones_like(u, dtype=tf.int32)\n mass = tf.constant(0, dtype=tf.float32)\n found = tf.constant(True, dtype=tf.bool)\n\n def loop(q_, mask, mass_, found_):\n q_list = tf.dynamic_partition(q_, mask, 2)\n condition_indices = tf.dynamic_partition(tf.range(tf.shape(q_)[0]), mask, 2) # 0 element it False,\n # 1 element if true\n\n p = q_list[1] * (1.0 - mass_) / tf.reduce_sum(q_list[1])\n p_new = tf.dynamic_stitch(condition_indices, [q_list[0], p])\n\n # condition verification and mask modification\n less_mask = tf.cast(tf.less(u, p_new), tf.int32) # 0 when u is bigger than p, 1 when u is less than p\n condition_indices = tf.dynamic_partition(tf.range(tf.shape(p_new)[0]), less_mask,\n 2) # 0 when u is bigger than p, 1 when u is less than p\n\n split_p_new = tf.dynamic_partition(p_new, less_mask, 2)\n split_u = tf.dynamic_partition(u, less_mask, 2)\n\n alpha = tf.dynamic_stitch(condition_indices, [split_p_new[0], split_u[1]])\n mass_ += tf.reduce_sum(split_u[1])\n\n mask = mask * (tf.ones_like(less_mask) - less_mask)\n\n found_ = tf.cond(tf.equal(tf.reduce_sum(less_mask), 0),\n lambda: False,\n lambda: True)\n\n alpha = tf.reshape(alpha, q_.shape)\n\n return alpha, mask, mass_, found_\n\n (csoft, mask_, _, _) = tf.while_loop(cond=lambda _0, _1, _2, f: f,\n body=loop,\n loop_vars=(q, active, mass, found))\n\n return [csoft, mask_]\n\n\ndef csoftmax(tensor, inv_cumulative_att):\n \"\"\" It is a implementation of the constrained softmax (csoftmax).\n Based on the paper:\n https://andre-martins.github.io/docs/emnlp2017_final.pdf \"Learning What's Easy: Fully Differentiable Neural Easy-First Taggers\"\n Args:\n tensor: A tensorflow tensor is score. This tensor have dimensionality [None, n_tokens]\n inv_cumulative_att: A inverse cumulative attention tensor with dimensionality [None, n_tokens]\n Returns:\n cs: Tensor at the output with dimensionality [None, n_tokens]\n \"\"\"\n shape_ten = tensor.shape\n shape_cum = inv_cumulative_att.shape\n\n merge_tensor = [tensor, inv_cumulative_att]\n cs, _ = tf.map_fn(csoftmax_for_slice, merge_tensor, dtype=[tf.float32, tf.float32]) # [bs, L]\n return cs\n\n\ndef attention_gen_step(hidden_for_sketch, hidden_for_attn_alignment, sketch, key, cum_att):\n \"\"\" It is a implementation one step of block of the Luong et al. attention mechanism with general score and the constrained softmax (csoftmax).\n Based on the papers:\n https://arxiv.org/abs/1508.04025 \"Effective Approaches to Attention-based Neural Machine Translation\"\n https://andre-martins.github.io/docs/emnlp2017_final.pdf \"Learning What's Easy: Fully Differentiable Neural Easy-First Taggers\"\n Args:\n hidden_for_sketch: A tensorflow tensor for a sketch computing. This tensor have dimensionality [None, max_num_tokens, sketch_hidden_size]\n hidden_for_attn_alignment: A tensorflow tensor is aligned for output during a performing. This tensor have dimensionality [None, max_num_tokens, hidden_size_for_attn_alignment]\n sketch: A previous step sketch tensor for a sketch computing. This tensor have dimensionality [None, sketch_hidden_size]\n key: A tensorflow tensor with dimensionality [None, None, key_size]\n cum_att: A cumulative attention tensor with dimensionality [None, max_num_tokens]\n Returns:\n next_sketch: Tensor of the current step sketch with dimensionality [None, sketch_hidden_size]\n att: Tensor of the current step attention with dimensionality [None, max_num_tokens]\n aligned_hidden_sketch: Tensor of aligned hidden state of current step with dimensionality [None, hidden_size_for_attn_alignment]\n \"\"\"\n with tf.name_scope('attention_step'):\n sketch_dims = hidden_for_sketch.get_shape().as_list()\n batch_size = sketch_dims[0]\n num_tokens = sketch_dims[1]\n hidden_size = sketch_dims[2]\n attn_alignment_dims = hidden_for_attn_alignment.get_shape().as_list()\n attn_alignment_hidden_size = attn_alignment_dims[2]\n\n repeated_sketch = tf.tile(tf.reshape(sketch, [-1, 1, hidden_size]), (1,num_tokens, 1))\n concat_mem = tf.concat([hidden_for_sketch, repeated_sketch],-1)\n\n\n concat_mem = tf.reshape(concat_mem, [-1, num_tokens, 2*hidden_size]) # dirty trick\n reduce_mem = tf.layers.dense(concat_mem, hidden_size)\n\n projected_key = tf.layers.dense(key, hidden_size)\n t_key = tf.reshape(projected_key,[-1, hidden_size, 1])\n\n score = tf.reshape(tf.matmul(reduce_mem, t_key), [-1, num_tokens])\n\n inv_cum_att = tf.reshape(tf.ones_like(cum_att) - cum_att, [-1, num_tokens])\n att = csoftmax(score, inv_cum_att)\n\n t_reduce_mem = tf.transpose(reduce_mem, [0,2,1])\n t_hidden_for_attn_alignment = tf.transpose(hidden_for_attn_alignment, [0,2,1])\n\n r_att = tf.reshape(att, [-1, num_tokens, 1])\n\n next_sketch = tf.squeeze(tf.matmul(t_reduce_mem,r_att),-1)\n aligned_hidden_sketch = tf.squeeze(tf.matmul(t_hidden_for_attn_alignment,r_att),-1)\n return next_sketch, att, aligned_hidden_sketch\n\n\ndef attention_gen_block(hidden_for_sketch, hidden_for_attn_alignment, key, attention_depth):\n \"\"\" It is a implementation of the Luong et al. attention mechanism with general score and the constrained softmax (csoftmax).\n Based on the papers:\n https://arxiv.org/abs/1508.04025 \"Effective Approaches to Attention-based Neural Machine Translation\"\n https://andre-martins.github.io/docs/emnlp2017_final.pdf \"Learning What's Easy: Fully Differentiable Neural Easy-First Taggers\"\n Args:\n hidden_for_sketch: A tensorflow tensor for a sketch computing. This tensor have dimensionality [None, max_num_tokens, sketch_hidden_size]\n hidden_for_attn_alignment: A tensorflow tensor is aligned for output during a performing. This tensor have dimensionality [None, max_num_tokens, hidden_size_for_attn_alignment]\n key: A tensorflow tensor with dimensionality [None, None, key_size]\n attention_depth: Number of usage csoftmax\n Returns:\n final_aligned_hiddens: Tensor at the output with dimensionality [1, attention_depth, hidden_size_for_attn_alignment]\n \"\"\"\n with tf.name_scope('attention_block'):\n sketch_dims = tf.shape(hidden_for_sketch)\n batch_size = sketch_dims[0]\n num_tokens = sketch_dims[1]\n hidden_size = sketch_dims[2]\n\n attn_alignment_dims = tf.shape(hidden_for_attn_alignment)\n attn_alignment_hidden_size = attn_alignment_dims[2]\n\n sketches = [tf.zeros(shape=[batch_size, hidden_size], dtype=tf.float32)]\n aligned_hiddens = []\n cum_att = tf.zeros(shape=[batch_size, num_tokens]) # cumulative attention\n for i in range(attention_depth):\n sketch, cum_att_, aligned_hidden = attention_gen_step(hidden_for_sketch, hidden_for_attn_alignment, sketches[-1], key, cum_att)\n sketches.append(sketch) #sketch\n aligned_hiddens.append(aligned_hidden) #sketch\n cum_att += cum_att_\n final_aligned_hiddens = tf.reshape(tf.transpose(tf.stack(aligned_hiddens), [1, 0, 2]),[1, attention_depth, attn_alignment_hidden_size])\n return final_aligned_hiddens\n\n\ndef attention_bah_step(hidden_for_sketch, hidden_for_attn_alignment, sketch, cum_att):\n \"\"\" It is a implementation one step of block of the Bahdanau et al. attention mechanism with concat score and the constrained softmax (csoftmax).\n Based on the papers:\n https://arxiv.org/abs/1409.0473 \"Neural Machine Translation by Jointly Learning to Align and Translate\"\n https://andre-martins.github.io/docs/emnlp2017_final.pdf \"Learning What's Easy: Fully Differentiable Neural Easy-First Taggers\"\n Args:\n hidden_for_sketch: A tensorflow tensor for a sketch computing. This tensor have dimensionality [None, max_num_tokens, sketch_hidden_size]\n hidden_for_attn_alignment: A tensorflow tensor is aligned for output during a performing. This tensor have dimensionality [None, max_num_tokens, hidden_size_for_attn_alignment]\n sketch: A previous step sketch tensor for a sketch computing. This tensor have dimensionality [None, sketch_hidden_size]\n key: A tensorflow tensor with dimensionality [None, None, key_size]\n cum_att: A cumulative attention tensor with dimensionality [None, max_num_tokens]\n Returns:\n next_sketch: Tensor of the current step sketch with dimensionality [None, sketch_hidden_size]\n att: Tensor of the current step attention with dimensionality [None, max_num_tokens]\n aligned_hidden_sketch: Tensor of aligned hidden state of current step with dimensionality [None, hidden_size_for_attn_alignment]\n \"\"\"\n with tf.name_scope('attention_step'):\n sketch_dims = hidden_for_sketch.get_shape().as_list()\n batch_size = sketch_dims[0]\n num_tokens = sketch_dims[1]\n hidden_size = sketch_dims[2]\n attn_alignment_dims = hidden_for_attn_alignment.get_shape().as_list()\n attn_alignment_hidden_size = attn_alignment_dims[2]\n\n repeated_sketch = tf.tile(tf.reshape(sketch, [-1, 1, hidden_size]), (1,num_tokens, 1))\n concat_mem = tf.concat([hidden_for_sketch, repeated_sketch],-1)\n\n\n concat_mem = tf.reshape(concat_mem, [-1, num_tokens, 2*hidden_size]) # dirty trick\n reduce_mem = tf.layers.dense(concat_mem, hidden_size)\n\n score = tf.squeeze(tf.layers.dense(reduce_mem, units = 1,\n use_bias=False),-1)\n inv_cum_att = tf.reshape(tf.ones_like(cum_att) - cum_att, [-1, num_tokens])\n att = csoftmax(score, inv_cum_att)\n\n t_reduce_mem = tf.transpose(reduce_mem, [0,2,1])\n t_hidden_for_attn_alignment = tf.transpose(hidden_for_attn_alignment, [0,2,1])\n\n r_att = tf.reshape(att, [-1, num_tokens, 1])\n\n next_sketch = tf.squeeze(tf.matmul(t_reduce_mem,r_att),-1)\n aligned_hidden_sketch = tf.squeeze(tf.matmul(t_hidden_for_attn_alignment,r_att),-1)\n return next_sketch, att, aligned_hidden_sketch\n\n\ndef attention_bah_block(hidden_for_sketch, hidden_for_attn_alignment, attention_depth):\n \"\"\" It is a implementation of the Bahdanau et al. attention mechanism with concat score and the constrained softmax (csoftmax).\n Based on the papers:\n https://arxiv.org/abs/1409.0473 \"Neural Machine Translation by Jointly Learning to Align and Translate\"\n https://andre-martins.github.io/docs/emnlp2017_final.pdf \"Learning What's Easy: Fully Differentiable Neural Easy-First Taggers\"\n Args:\n hidden_for_sketch: A tensorflow tensor for a sketch computing. This tensor have dimensionality [None, max_num_tokens, sketch_hidden_size]\n hidden_for_attn_alignment: A tensorflow tensor is aligned for output during a performing. This tensor have dimensionality [None, max_num_tokens, hidden_size_for_attn_alignment]\n key: A tensorflow tensor with dimensionality [None, None, key_size]\n attention_depth: Number of usage csoftmax\n Returns:\n final_aligned_hiddens: Tensor at the output with dimensionality [1, attention_depth, hidden_size_for_attn_alignment]\n \"\"\"\n with tf.name_scope('attention_block'):\n sketch_dims = tf.shape(hidden_for_sketch)\n batch_size = sketch_dims[0]\n num_tokens = sketch_dims[1]\n hidden_size = sketch_dims[2]\n\n attn_alignment_dims = tf.shape(hidden_for_attn_alignment)\n attn_alignment_hidden_size = attn_alignment_dims[2]\n\n sketches = [tf.zeros(shape=[batch_size, hidden_size], dtype=tf.float32)]\n aligned_hiddens = []\n cum_att = tf.zeros(shape=[batch_size, num_tokens]) # cumulative attention\n for i in range(attention_depth):\n sketch, cum_att_, aligned_hidden = attention_bah_step(hidden_for_sketch, hidden_for_attn_alignment, sketches[-1], cum_att)\n sketches.append(sketch) #sketch\n aligned_hiddens.append(aligned_hidden) #sketch\n cum_att += cum_att_\n final_aligned_hiddens = tf.reshape(tf.transpose(tf.stack(aligned_hiddens), [1, 0, 2]),[1, attention_depth, attn_alignment_hidden_size])\n return final_aligned_hiddens\n",
"# Copyright 2017 Neural Networks and Deep Learning lab, MIPT\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\nfrom typing import Tuple, Iterator, Optional, Dict, List, Union\nfrom pathlib import Path\n\nimport numpy as np\n\nfrom deeppavlov.core.common.registry import register\nfrom deeppavlov.core.data.data_learning_iterator import DataLearningIterator\nfrom deeppavlov.core.common.log import get_logger\nfrom deeppavlov.core.data.utils import chunk_generator\n\nlog = get_logger(__name__)\n\n\n@register('file_paths_iterator')\nclass FilePathsIterator(DataLearningIterator):\n \"\"\"Dataset iterator for datasets like 1 Billion Word Benchmark.\n It gets lists of file paths from the data dictionary and returns lines from each file.\n\n Args:\n data: dict with keys ``'train'``, ``'valid'`` and ``'test'`` and values\n seed: random seed for data shuffling\n shuffle: whether to shuffle data during batching\n\n \"\"\"\n\n def __init__(self,\n data: Dict[str, List[Union[str, Path]]],\n seed: Optional[int] = None, \n shuffle: bool = True,\n *args, **kwargs) -> None:\n self.seed = seed\n self.np_random = np.random.RandomState(seed)\n super().__init__(data, seed, shuffle, *args, **kwargs)\n\n def _shard_generator(self, shards: List[Union[str, Path]], shuffle: bool = False) -> List[str]:\n shards_to_choose = list(shards)\n if shuffle:\n self.np_random.shuffle(shards_to_choose)\n for shard in shards_to_choose:\n log.info(f'Loaded shard from {shard}')\n with open(shard, encoding='utf-8') as f:\n lines = f.readlines()\n if shuffle:\n self.np_random.shuffle(lines)\n yield lines\n\n def gen_batches(self, batch_size: int, data_type: str = 'train', shuffle: Optional[bool] = None)\\\n -> Iterator[Tuple[str, str]]:\n if shuffle is None:\n shuffle = self.shuffle\n\n tgt_data = self.data[data_type]\n shard_generator = self._shard_generator(tgt_data, shuffle=shuffle)\n\n for shard in shard_generator:\n if not (batch_size):\n bs = len(shard)\n lines_generator = chunk_generator(shard, bs)\n for lines in lines_generator:\n yield (lines, [None] * len(lines))\n"
] | [
[
"tensorflow.concat",
"tensorflow.zeros",
"tensorflow.stack",
"tensorflow.reduce_sum",
"tensorflow.map_fn",
"tensorflow.while_loop",
"tensorflow.layers.dense",
"tensorflow.dynamic_stitch",
"tensorflow.name_scope",
"tensorflow.matmul",
"tensorflow.dynamic_partition",
"tensorflow.shape",
"tensorflow.less",
"tensorflow.exp",
"tensorflow.constant",
"tensorflow.transpose",
"tensorflow.reduce_mean",
"tensorflow.reshape",
"tensorflow.ones_like"
],
[
"numpy.random.RandomState"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ralfgerlich/simupy | [
"7716c95ab51b63483278208230758dfdcd1a2b51"
] | [
"tests/test_numeric_switchedsystem.py"
] | [
"import pytest\nimport numpy as np\nimport numpy.testing as npt\nfrom simupy.systems import (SwitchedSystem, need_state_equation_function_msg,\n need_output_equation_function_msg,\n zero_dim_output_msg, full_state_output)\n\nmax_n_condition = 4\nbounds_min = -1\nbounds_max = 1\n\n\ndef state_equation_function(t, x, u):\n return np.ones(x.shape)\n\n\ndef output_equation_function(t, u):\n return np.ones(u.shape)\n\n\ndef event_variable_equation_function(t, x):\n return x\n\n\[email protected](scope=\"module\", params=np.arange(2, max_n_condition))\ndef switch_fixture(request):\n yield (((bounds_max - bounds_min)*np.sort(np.random.rand(request.param-1))\n + bounds_min),\n np.array([lambda t, x, u: cnd*np.ones(x.shape)\n for cnd in range(request.param)]),\n np.array([lambda t, u: cnd*np.ones(u.shape)\n for cnd in range(request.param)])\n )\n\n\ndef test_dim_output_0(switch_fixture):\n with pytest.raises(ValueError, match=zero_dim_output_msg):\n SwitchedSystem(\n event_variable_equation_function=event_variable_equation_function,\n event_bounds=switch_fixture[0],\n output_equations_functions=switch_fixture[2]\n )\n SwitchedSystem(\n dim_output=1,\n event_variable_equation_function=event_variable_equation_function,\n event_bounds=switch_fixture[0],\n output_equations_functions=switch_fixture[2],\n )\n\n\ndef test_state_equations_functions_kwarg(switch_fixture):\n with pytest.raises(ValueError, match=need_state_equation_function_msg):\n SwitchedSystem(\n dim_state=1,\n event_variable_equation_function=event_variable_equation_function,\n event_bounds=switch_fixture[0],\n output_equations_functions=switch_fixture[2]\n )\n with pytest.raises(ValueError, match=\"broadcast\"):\n SwitchedSystem(\n dim_state=1,\n event_variable_equation_function=event_variable_equation_function,\n event_bounds=switch_fixture[0],\n state_equations_functions=np.array([\n lambda t, x, u: cnd*np.ones(x.shape)\n for cnd in range(switch_fixture[0].size+2)\n ]),\n output_equations_functions=switch_fixture[2]\n )\n sys = SwitchedSystem(\n dim_state=1,\n event_variable_equation_function=event_variable_equation_function,\n event_bounds=switch_fixture[0],\n state_equations_functions=switch_fixture[1],\n output_equations_functions=switch_fixture[2]\n )\n npt.assert_array_equal(sys.state_equations_functions, switch_fixture[1])\n sys = SwitchedSystem(\n dim_state=1,\n event_variable_equation_function=event_variable_equation_function,\n event_bounds=switch_fixture[0],\n state_equations_functions=state_equation_function,\n output_equations_functions=switch_fixture[2]\n )\n npt.assert_array_equal(\n sys.state_equations_functions,\n state_equation_function\n )\n\n\ndef test_output_equations_functions_kwarg(switch_fixture):\n with pytest.raises(ValueError, match=need_output_equation_function_msg):\n SwitchedSystem(\n dim_output=1,\n event_variable_equation_function=event_variable_equation_function,\n event_bounds=switch_fixture[0],\n )\n with pytest.raises(ValueError, match=\"broadcast\"):\n SwitchedSystem(\n dim_output=1,\n event_variable_equation_function=event_variable_equation_function,\n event_bounds=switch_fixture[0],\n output_equations_functions=np.array([\n lambda t, u: cnd*np.ones(u.shape)\n for cnd in range(switch_fixture[0].size+2)\n ]),\n )\n sys = SwitchedSystem(\n dim_state=1,\n event_variable_equation_function=event_variable_equation_function,\n event_bounds=switch_fixture[0],\n state_equations_functions=switch_fixture[1],\n )\n npt.assert_array_equal(\n sys.output_equations_functions,\n full_state_output\n )\n\n sys = SwitchedSystem(\n dim_output=1,\n event_variable_equation_function=event_variable_equation_function,\n event_bounds=switch_fixture[0],\n output_equations_functions=switch_fixture[2]\n )\n npt.assert_array_equal(sys.output_equations_functions, switch_fixture[2])\n\n sys = SwitchedSystem(\n dim_output=1,\n event_variable_equation_function=event_variable_equation_function,\n event_bounds=switch_fixture[0],\n output_equations_functions=output_equation_function\n )\n npt.assert_array_equal(\n sys.output_equations_functions,\n output_equation_function\n )\n\n\ndef test_event_equation_function(switch_fixture):\n sys = SwitchedSystem(\n dim_output=1,\n event_variable_equation_function=event_variable_equation_function,\n event_bounds=switch_fixture[0],\n state_equations_functions=switch_fixture[1],\n output_equations_functions=switch_fixture[2],\n )\n\n assert sys.state_update_equation_function == full_state_output\n\n for x in np.linspace(bounds_min, bounds_max):\n if not np.any(np.isclose(x, switch_fixture[0])):\n assert ~np.any(np.isclose(\n sys.event_equation_function(x, x),\n 0\n ))\n\n for zero in switch_fixture[0]:\n npt.assert_allclose(\n sys.event_equation_function(len(switch_fixture[0]), zero),\n 0\n )\n\n\ndef test_update_equation_function(switch_fixture):\n sys = SwitchedSystem(\n dim_output=1,\n event_variable_equation_function=event_variable_equation_function,\n event_bounds=switch_fixture[0],\n state_equations_functions=switch_fixture[1],\n output_equations_functions=switch_fixture[2],\n )\n\n assert not hasattr(sys, 'condition_idx')\n sys.prepare_to_integrate()\n\n assert sys.condition_idx is None\n sys.update_equation_function(np.random.rand(1), bounds_min)\n assert sys.condition_idx == 0\n\n for cnd_idx, zero in enumerate(switch_fixture[0]):\n sys.update_equation_function(np.random.rand(1), zero)\n assert sys.condition_idx == cnd_idx+1\n\n if len(switch_fixture[0]) > 1:\n with pytest.warns(UserWarning):\n sys.update_equation_function(np.random.rand(1), bounds_min)\n"
] | [
[
"numpy.linspace",
"numpy.arange",
"numpy.ones",
"numpy.testing.assert_array_equal",
"numpy.random.rand",
"numpy.isclose"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
amalekji/trading-tech-analysis | [
"b360062d6b2a31f0bf237e42a9a399d3b1f6c306"
] | [
"ta/trend.py"
] | [
"\"\"\"\n.. module:: trend\n :synopsis: Trend Indicators.\n\n.. moduleauthor:: Dario Lopez Padial (Bukosabino)\n\n\"\"\"\nimport numpy as np\nimport pandas as pd\n\nfrom ta.utils import IndicatorMixin, ema, get_min_max, sma\n\n\nclass AroonIndicator(IndicatorMixin):\n \"\"\"Aroon Indicator\n\n Identify when trends are likely to change direction.\n\n Aroon Up = ((N - Days Since N-day High) / N) x 100\n Aroon Down = ((N - Days Since N-day Low) / N) x 100\n Aroon Indicator = Aroon Up - Aroon Down\n\n https://www.investopedia.com/terms/a/aroon.asp\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n \"\"\"\n\n def __init__(self, close: pd.Series, n: int = 25, fillna: bool = False):\n self._close = close\n self._n = n\n self._fillna = fillna\n self._run()\n\n def _run(self):\n min_periods = 0 if self._fillna else self._n\n rolling_close = self._close.rolling(self._n, min_periods=min_periods)\n self._aroon_up = rolling_close.apply(\n lambda x: float(np.argmax(x) + 1) / self._n * 100, raw=True)\n self._aroon_down = rolling_close.apply(\n lambda x: float(np.argmin(x) + 1) / self._n * 100, raw=True)\n\n def aroon_up(self) -> pd.Series:\n \"\"\"Aroon Up Channel\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n aroon_up = self._check_fillna(self._aroon_up, value=0)\n return pd.Series(aroon_up, name=f'aroon_up_{self._n}')\n\n def aroon_down(self) -> pd.Series:\n \"\"\"Aroon Down Channel\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n aroon_down = self._check_fillna(self._aroon_down, value=0)\n return pd.Series(aroon_down, name=f'aroon_down_{self._n}')\n\n def aroon_indicator(self) -> pd.Series:\n \"\"\"Aroon Indicator\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n aroon_diff = self._aroon_up - self._aroon_down\n aroon_diff = self._check_fillna(aroon_diff, value=0)\n return pd.Series(aroon_diff, name=f'aroon_ind_{self._n}')\n\n\nclass MACD(IndicatorMixin):\n \"\"\"Moving Average Convergence Divergence (MACD)\n\n Is a trend-following momentum indicator that shows the relationship between\n two moving averages of prices.\n\n https://school.stockcharts.com/doku.php?id=technical_indicators:moving_average_convergence_divergence_macd\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n n_fast(int): n period short-term.\n n_slow(int): n period long-term.\n n_sign(int): n period to signal.\n fillna(bool): if True, fill nan values.\n \"\"\"\n def __init__(self,\n close: pd.Series,\n n_slow: int = 26,\n n_fast: int = 12,\n n_sign: int = 9,\n fillna: bool = False):\n self._close = close\n self._n_slow = n_slow\n self._n_fast = n_fast\n self._n_sign = n_sign\n self._fillna = fillna\n self._run()\n\n def _run(self):\n self._emafast = ema(self._close, self._n_fast, self._fillna)\n self._emaslow = ema(self._close, self._n_slow, self._fillna)\n self._macd = self._emafast - self._emaslow\n self._macd_signal = ema(self._macd, self._n_sign, self._fillna)\n self._macd_diff = self._macd - self._macd_signal\n\n def macd(self) -> pd.Series:\n \"\"\"MACD Line\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n macd = self._check_fillna(self._macd, value=0)\n return pd.Series(macd, name=f'MACD_{self._n_fast}_{self._n_slow}')\n\n def macd_signal(self) -> pd.Series:\n \"\"\"Signal Line\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n\n macd_signal = self._check_fillna(self._macd_signal, value=0)\n return pd.Series(macd_signal, name=f'MACD_sign_{self._n_fast}_{self._n_slow}')\n\n def macd_diff(self) -> pd.Series:\n \"\"\"MACD Histogram\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n macd_diff = self._check_fillna(self._macd_diff, value=0)\n return pd.Series(macd_diff, name=f'MACD_diff_{self._n_fast}_{self._n_slow}')\n\n\nclass EMAIndicator(IndicatorMixin):\n \"\"\"EMA - Exponential Moving Average\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n \"\"\"\n\n def __init__(self, close: pd.Series, n: int = 14, fillna: bool = False):\n self._close = close\n self._n = n\n self._fillna = fillna\n\n def ema_indicator(self) -> pd.Series:\n \"\"\"Exponential Moving Average (EMA)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n ema_ = ema(self._close, self._n, self._fillna)\n return pd.Series(ema_, name=f'ema_{self._n}')\n\n\nclass SMAIndicator(IndicatorMixin):\n \"\"\"SMA - Simple Moving Average\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n \"\"\"\n\n def __init__(self, close: pd.Series, n: int, fillna: bool = False):\n self._close = close\n self._n = n\n self._fillna = fillna\n\n def sma_indicator(self) -> pd.Series:\n \"\"\"Simple Moving Average (SMA)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n sma_ = sma(self._close, self._n, self._fillna)\n return pd.Series(sma_, name=f'sma_{self._n}')\n\n\nclass TRIXIndicator(IndicatorMixin):\n \"\"\"Trix (TRIX)\n\n Shows the percent rate of change of a triple exponentially smoothed moving\n average.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:trix\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n \"\"\"\n\n def __init__(self, close: pd.Series, n: int = 15, fillna: bool = False):\n self._close = close\n self._n = n\n self._fillna = fillna\n self._run()\n\n def _run(self):\n ema1 = ema(self._close, self._n, self._fillna)\n ema2 = ema(ema1, self._n, self._fillna)\n ema3 = ema(ema2, self._n, self._fillna)\n self._trix = (ema3 - ema3.shift(1, fill_value=ema3.mean())) / ema3.shift(1, fill_value=ema3.mean())\n self._trix *= 100\n\n def trix(self) -> pd.Series:\n \"\"\"Trix (TRIX)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n trix = self._check_fillna(self._trix, value=0)\n return pd.Series(trix, name=f'trix_{self._n}')\n\n\nclass MassIndex(IndicatorMixin):\n \"\"\"Mass Index (MI)\n\n It uses the high-low range to identify trend reversals based on range\n expansions. It identifies range bulges that can foreshadow a reversal of\n the current trend.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:mass_index\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n n(int): n low period.\n n2(int): n high period.\n fillna(bool): if True, fill nan values.\n \"\"\"\n\n def __init__(self, high: pd.Series, low: pd.Series, n: int = 9, n2: int = 25, fillna: bool = False):\n self._high = high\n self._low = low\n self._n = n\n self._n2 = n2\n self._fillna = fillna\n self._run()\n\n def _run(self):\n min_periods = 0 if self._fillna else self._n2\n amplitude = self._high - self._low\n ema1 = ema(amplitude, self._n, self._fillna)\n ema2 = ema(ema1, self._n, self._fillna)\n mass = ema1 / ema2\n self._mass = mass.rolling(self._n2, min_periods=min_periods).sum()\n\n def mass_index(self) -> pd.Series:\n \"\"\"Mass Index (MI)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n mass = self._check_fillna(self._mass, value=0)\n return pd.Series(mass, name=f'mass_index_{self._n}_{self._n2}')\n\n\nclass IchimokuIndicator(IndicatorMixin):\n \"\"\"Ichimoku Kinkō Hyō (Ichimoku)\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:ichimoku_cloud\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n n1(int): n1 low period.\n n2(int): n2 medium period.\n n3(int): n3 high period.\n visual(bool): if True, shift n2 values.\n fillna(bool): if True, fill nan values.\n \"\"\"\n\n def __init__(self, high: pd.Series, low: pd.Series, n1: int = 9, n2: int = 26, n3: int = 52,\n visual: bool = False, fillna: bool = False):\n self._high = high\n self._low = low\n self._n1 = n1\n self._n2 = n2\n self._n3 = n3\n self._visual = visual\n self._fillna = fillna\n self._run()\n\n def _run(self):\n min_periods_n1 = 0 if self._fillna else self._n1\n min_periods_n2 = 0 if self._fillna else self._n2\n self._conv = 0.5 * (\n self._high.rolling(self._n1, min_periods=min_periods_n1).max() +\n self._low.rolling(self._n1, min_periods=min_periods_n1).min())\n self._base = 0.5 * (\n self._high.rolling(self._n2, min_periods=min_periods_n2).max() +\n self._low.rolling(self._n2, min_periods=min_periods_n2).min())\n\n def ichimoku_conversion_line(self) -> pd.Series:\n \"\"\"Tenkan-sen (Conversion Line)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n conversion = self._check_fillna(self._conv, value=-1)\n return pd.Series(conversion, name=f'ichimoku_conv_{self._n1}_{self._n2}')\n\n def ichimoku_base_line(self) -> pd.Series:\n \"\"\"Kijun-sen (Base Line)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n base = self._check_fillna(self._base, value=-1)\n return pd.Series(base, name=f'ichimoku_base_{self._n1}_{self._n2}')\n\n def ichimoku_a(self) -> pd.Series:\n \"\"\"Senkou Span A (Leading Span A)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n spana = 0.5 * (self._conv + self._base)\n spana = spana.shift(self._n2, fill_value=spana.mean()) if self._visual else spana\n spana = self._check_fillna(spana, value=-1)\n return pd.Series(spana, name=f'ichimoku_a_{self._n1}_{self._n2}')\n\n def ichimoku_b(self) -> pd.Series:\n \"\"\"Senkou Span B (Leading Span B)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n spanb = 0.5 * (self._high.rolling(self._n3, min_periods=0).max()\n + self._low.rolling(self._n3, min_periods=0).min())\n spanb = spanb.shift(self._n2, fill_value=spanb.mean()) if self._visual else spanb\n spanb = self._check_fillna(spanb, value=-1)\n return pd.Series(spanb, name=f'ichimoku_b_{self._n1}_{self._n2}')\n\n\nclass KSTIndicator(IndicatorMixin):\n \"\"\"KST Oscillator (KST Signal)\n\n It is useful to identify major stock market cycle junctures because its\n formula is weighed to be more greatly influenced by the longer and more\n dominant time spans, in order to better reflect the primary swings of stock\n market cycle.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:know_sure_thing_kst\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n r1(int): r1 period.\n r2(int): r2 period.\n r3(int): r3 period.\n r4(int): r4 period.\n n1(int): n1 smoothed period.\n n2(int): n2 smoothed period.\n n3(int): n3 smoothed period.\n n4(int): n4 smoothed period.\n nsig(int): n period to signal.\n fillna(bool): if True, fill nan values.\n \"\"\"\n\n def __init__(self, close: pd.Series, r1: int = 10, r2: int = 15, r3: int = 20, r4: int = 30,\n n1: int = 10, n2: int = 10, n3: int = 10, n4: int = 15, nsig: int = 9,\n fillna: bool = False):\n self._close = close\n self._r1 = r1\n self._r2 = r2\n self._r3 = r3\n self._r4 = r4\n self._n1 = n1\n self._n2 = n2\n self._n3 = n3\n self._n4 = n4\n self._nsig = nsig\n self._fillna = fillna\n self._run()\n\n def _run(self):\n min_periods_n1 = 0 if self._fillna else self._n1\n min_periods_n2 = 0 if self._fillna else self._n2\n min_periods_n3 = 0 if self._fillna else self._n3\n min_periods_n4 = 0 if self._fillna else self._n4\n rocma1 = (\n (self._close - self._close.shift(self._r1, fill_value=self._close.mean()))\n / self._close.shift(self._r1, fill_value=self._close.mean())).rolling(\n self._n1, min_periods=min_periods_n1).mean()\n rocma2 = (\n (self._close - self._close.shift(self._r2, fill_value=self._close.mean()))\n / self._close.shift(self._r2, fill_value=self._close.mean())).rolling(\n self._n2, min_periods=min_periods_n2).mean()\n rocma3 = (\n (self._close - self._close.shift(self._r3, fill_value=self._close.mean()))\n / self._close.shift(self._r3, fill_value=self._close.mean())).rolling(\n self._n3, min_periods=min_periods_n3).mean()\n rocma4 = (\n (self._close - self._close.shift(self._r4, fill_value=self._close.mean()))\n / self._close.shift(self._r4, fill_value=self._close.mean())).rolling(\n self._n4, min_periods=min_periods_n4).mean()\n self._kst = 100 * (rocma1 + 2 * rocma2 + 3 * rocma3 + 4 * rocma4)\n self._kst_sig = self._kst.rolling(self._nsig, min_periods=0).mean()\n\n def kst(self) -> pd.Series:\n \"\"\"Know Sure Thing (KST)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n kst = self._check_fillna(self._kst, value=0)\n return pd.Series(kst, name='kst')\n\n def kst_sig(self) -> pd.Series:\n \"\"\"Signal Line Know Sure Thing (KST)\n\n nsig-period SMA of KST\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n kst_sig = self._check_fillna(self._kst_sig, value=0)\n return pd.Series(kst_sig, name='kst_sig')\n\n def kst_diff(self) -> pd.Series:\n \"\"\"Diff Know Sure Thing (KST)\n\n KST - Signal_KST\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n kst_diff = self._kst - self._kst_sig\n kst_diff = self._check_fillna(kst_diff, value=0)\n return pd.Series(kst_diff, name='kst_diff')\n\n\nclass DPOIndicator(IndicatorMixin):\n \"\"\"Detrended Price Oscillator (DPO)\n\n Is an indicator designed to remove trend from price and make it easier to\n identify cycles.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:detrended_price_osci\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n \"\"\"\n def __init__(self, close: pd.Series, n: int = 20, fillna: bool = False):\n self._close = close\n self._n = n\n self._fillna = fillna\n self._run()\n\n def _run(self):\n min_periods = 0 if self._fillna else self._n\n self._dpo = (self._close.shift(int((0.5 * self._n) + 1), fill_value=self._close.mean())\n - self._close.rolling(self._n, min_periods=min_periods).mean())\n\n def dpo(self) -> pd.Series:\n \"\"\"Detrended Price Oscillator (DPO)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n dpo = self._check_fillna(self._dpo, value=0)\n return pd.Series(dpo, name='dpo_'+str(self._n))\n\n\nclass CCIIndicator(IndicatorMixin):\n \"\"\"Commodity Channel Index (CCI)\n\n CCI measures the difference between a security's price change and its\n average price change. High positive readings indicate that prices are well\n above their average, which is a show of strength. Low negative readings\n indicate that prices are well below their average, which is a show of\n weakness.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:commodity_channel_index_cci\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n close(pandas.Series): dataset 'Close' column.\n n(int): n period.\n c(int): constant.\n fillna(bool): if True, fill nan values.\n \"\"\"\n\n def __init__(self,\n high: pd.Series,\n low: pd.Series,\n close: pd.Series,\n n: int = 20,\n c: float = 0.015,\n fillna: bool = False):\n self._high = high\n self._low = low\n self._close = close\n self._n = n\n self._c = c\n self._fillna = fillna\n self._run()\n\n def _run(self):\n\n def _mad(x):\n return np.mean(np.abs(x-np.mean(x)))\n\n min_periods = 0 if self._fillna else self._n\n pp = (self._high + self._low + self._close) / 3.0\n self._cci = ((pp - pp.rolling(self._n, min_periods=min_periods).mean())\n / (self._c * pp.rolling(self._n, min_periods=min_periods).apply(_mad, True)))\n\n def cci(self) -> pd.Series:\n \"\"\"Commodity Channel Index (CCI)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n cci = self._check_fillna(self._cci, value=0)\n return pd.Series(cci, name='cci')\n\n\nclass ADXIndicator(IndicatorMixin):\n \"\"\"Average Directional Movement Index (ADX)\n\n The Plus Directional Indicator (+DI) and Minus Directional Indicator (-DI)\n are derived from smoothed averages of these differences, and measure trend\n direction over time. These two indicators are often referred to\n collectively as the Directional Movement Indicator (DMI).\n\n The Average Directional Index (ADX) is in turn derived from the smoothed\n averages of the difference between +DI and -DI, and measures the strength\n of the trend (regardless of direction) over time.\n\n Using these three indicators together, chartists can determine both the\n direction and strength of the trend.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:average_directional_index_adx\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n close(pandas.Series): dataset 'Close' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n \"\"\"\n\n def __init__(self, high: pd.Series, low: pd.Series, close: pd.Series, n: int = 14, fillna: bool = False):\n self._high = high\n self._low = low\n self._close = close\n self._n = n\n self._fillna = fillna\n self._run()\n\n def _run(self):\n assert self._n != 0, \"N may not be 0 and is %r\" % n\n\n cs = self._close.shift(1)\n pdm = get_min_max(self._high, cs, 'max')\n pdn = get_min_max(self._low, cs, 'min')\n tr = pdm - pdn\n\n self._trs_initial = np.zeros(self._n-1)\n self._trs = np.zeros(len(self._close) - (self._n - 1))\n self._trs[0] = tr.dropna()[0:self._n].sum()\n tr = tr.reset_index(drop=True)\n\n for i in range(1, len(self._trs)-1):\n self._trs[i] = self._trs[i-1] - (self._trs[i-1]/float(self._n)) + tr[self._n+i]\n\n up = self._high - self._high.shift(1)\n dn = self._low.shift(1) - self._low\n pos = abs(((up > dn) & (up > 0)) * up)\n neg = abs(((dn > up) & (dn > 0)) * dn)\n\n self._dip = np.zeros(len(self._close) - (self._n - 1))\n self._dip[0] = pos.dropna()[0:self._n].sum()\n\n pos = pos.reset_index(drop=True)\n\n for i in range(1, len(self._dip)-1):\n self._dip[i] = self._dip[i-1] - (self._dip[i-1]/float(self._n)) + pos[self._n+i]\n\n self._din = np.zeros(len(self._close) - (self._n - 1))\n self._din[0] = neg.dropna()[0:self._n].sum()\n\n neg = neg.reset_index(drop=True)\n\n for i in range(1, len(self._din)-1):\n self._din[i] = self._din[i-1] - (self._din[i-1]/float(self._n)) + neg[self._n+i]\n\n def adx(self) -> pd.Series:\n \"\"\"Average Directional Index (ADX)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n dip = np.zeros(len(self._trs))\n for i in range(len(self._trs)):\n dip[i] = 100 * (self._dip[i]/self._trs[i])\n\n din = np.zeros(len(self._trs))\n for i in range(len(self._trs)):\n din[i] = 100 * (self._din[i]/self._trs[i])\n\n dx = 100 * np.abs((dip - din) / (dip + din))\n\n adx = np.zeros(len(self._trs))\n adx[self._n] = dx[0:self._n].mean()\n\n for i in range(self._n+1, len(adx)):\n adx[i] = ((adx[i-1] * (self._n - 1)) + dx[i-1]) / float(self._n)\n\n adx = np.concatenate((self._trs_initial, adx), axis=0)\n self._adx = pd.Series(data=adx, index=self._close.index)\n\n adx = self._check_fillna(self._adx, value=20)\n return pd.Series(adx, name='adx')\n\n def adx_pos(self) -> pd.Series:\n \"\"\"Plus Directional Indicator (+DI)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n dip = np.zeros(len(self._close))\n for i in range(1, len(self._trs)-1):\n dip[i+self._n] = 100 * (self._dip[i]/self._trs[i])\n\n adx_pos = self._check_fillna(pd.Series(dip, index=self._close.index), value=20)\n return pd.Series(adx_pos, name='adx_pos')\n\n def adx_neg(self) -> pd.Series:\n \"\"\"Minus Directional Indicator (-DI)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n din = np.zeros(len(self._close))\n for i in range(1, len(self._trs)-1):\n din[i+self._n] = 100 * (self._din[i]/self._trs[i])\n\n adx_neg = self._check_fillna(pd.Series(din, index=self._close.index), value=20)\n return pd.Series(adx_neg, name='adx_neg')\n\n\nclass VortexIndicator(IndicatorMixin):\n \"\"\"Vortex Indicator (VI)\n\n It consists of two oscillators that capture positive and negative trend\n movement. A bullish signal triggers when the positive trend indicator\n crosses above the negative trend indicator or a key level.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:vortex_indicator\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n close(pandas.Series): dataset 'Close' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n \"\"\"\n\n def __init__(self, high: pd.Series, low: pd.Series, close: pd.Series, n: int = 14, fillna: bool = False):\n self._high = high\n self._low = low\n self._close = close\n self._n = n\n self._fillna = fillna\n self._run()\n\n def _run(self):\n cs = self._close.shift(1, fill_value=self._close.mean())\n tr = self._true_range(self._high, self._low, cs)\n min_periods = 0 if self._fillna else self._n\n trn = tr.rolling(self._n, min_periods=min_periods).sum()\n vmp = np.abs(self._high - self._low.shift(1))\n vmm = np.abs(self._low - self._high.shift(1))\n self._vip = vmp.rolling(self._n, min_periods=min_periods).sum() / trn\n self._vin = vmm.rolling(self._n, min_periods=min_periods).sum() / trn\n\n def vortex_indicator_pos(self):\n \"\"\"+VI\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n vip = self._check_fillna(self._vip, value=1)\n return pd.Series(vip, name='vip')\n\n def vortex_indicator_neg(self):\n \"\"\"-VI\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n vin = self._check_fillna(self._vin, value=1)\n return pd.Series(vin, name='vin')\n\n def vortex_indicator_diff(self):\n \"\"\"Diff VI\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n vid = self._vip - self._vin\n vid = self._check_fillna(vid, value=0)\n return pd.Series(vid, name='vid')\n\n\nclass PSARIndicator(IndicatorMixin):\n \"\"\"Parabolic Stop and Reverse (Parabolic SAR)\n\n The Parabolic Stop and Reverse, more commonly known as the\n Parabolic SAR,is a trend-following indicator developed by\n J. Welles Wilder. The Parabolic SAR is displayed as a single\n parabolic line (or dots) underneath the price bars in an uptrend,\n and above the price bars in a downtrend.\n\n https://school.stockcharts.com/doku.php?id=technical_indicators:parabolic_sar\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n close(pandas.Series): dataset 'Close' column.\n step(float): the Acceleration Factor used to compute the SAR.\n max_step(float): the maximum value allowed for the Acceleration Factor.\n fillna(bool): if True, fill nan values.\n \"\"\"\n def __init__(self, high: pd.Series, low: pd.Series, close: pd.Series,\n step: float = 0.02, max_step: float = 0.20,\n fillna: bool = False):\n self._high = high\n self._low = low\n self._close = close\n self._step = step\n self._max_step = max_step\n self._fillna = fillna\n self._run()\n\n def _run(self):\n up_trend = True\n af = self._step\n up_trend_high = self._high.iloc[0]\n down_trend_low = self._low.iloc[0]\n\n self._psar = self._close.copy()\n self._psar_up = pd.Series(index=self._psar.index)\n self._psar_down = pd.Series(index=self._psar.index)\n\n for i in range(2, len(self._close)):\n reversal = False\n\n max_high = self._high.iloc[i]\n min_low = self._low.iloc[i]\n\n if up_trend:\n self._psar.iloc[i] = self._psar.iloc[i-1] + (\n af * (up_trend_high - self._psar.iloc[i-1]))\n\n if min_low < self._psar.iloc[i]:\n reversal = True\n self._psar.iloc[i] = up_trend_high\n down_trend_low = min_low\n af = self._step\n else:\n if max_high > up_trend_high:\n up_trend_high = max_high\n af = min(af + self._step, self._max_step)\n\n l1 = self._low.iloc[i-1]\n l2 = self._low.iloc[i-2]\n if l2 < self._psar.iloc[i]:\n self._psar.iloc[i] = l2\n elif l1 < self._psar.iloc[i]:\n self._psar.iloc[i] = l1\n else:\n self._psar.iloc[i] = self._psar.iloc[i-1] - (\n af * (self._psar.iloc[i-1] - down_trend_low))\n\n if max_high > self._psar.iloc[i]:\n reversal = True\n self._psar.iloc[i] = down_trend_low\n up_trend_high = max_high\n af = self._step\n else:\n if min_low < down_trend_low:\n down_trend_low = min_low\n af = min(af + self._step, self._max_step)\n\n h1 = self._high.iloc[i-1]\n h2 = self._high.iloc[i-2]\n if h2 > self._psar.iloc[i]:\n self._psar[i] = h2\n elif h1 > self._psar.iloc[i]:\n self._psar.iloc[i] = h1\n\n up_trend = up_trend != reversal # XOR\n\n if up_trend:\n self._psar_up.iloc[i] = self._psar.iloc[i]\n else:\n self._psar_down.iloc[i] = self._psar.iloc[i]\n\n def psar(self) -> pd.Series:\n \"\"\"PSAR value\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n psar = self._check_fillna(self._psar, value=-1)\n return pd.Series(psar, name='psar')\n\n def psar_up(self) -> pd.Series:\n \"\"\"PSAR up trend value\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n psar_up = self._check_fillna(self._psar_up, value=-1)\n return pd.Series(psar_up, name='psarup')\n\n def psar_down(self) -> pd.Series:\n \"\"\"PSAR down trend value\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n psar_down = self._check_fillna(self._psar_down, value=-1)\n return pd.Series(psar_down, name='psardown')\n\n def psar_up_indicator(self) -> pd.Series:\n \"\"\"PSAR up trend value\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n indicator = self._psar_up.where(self._psar_up.notnull()\n & self._psar_up.shift(1).isnull(), 0)\n indicator = indicator.where(indicator == 0, 1)\n return pd.Series(indicator, index=self._close.index, name='psariup')\n\n def psar_down_indicator(self) -> pd.Series:\n \"\"\"PSAR down trend value\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n indicator = self._psar_up.where(self._psar_down.notnull()\n & self._psar_down.shift(1).isnull(), 0)\n indicator = indicator.where(indicator == 0, 1)\n return pd.Series(indicator, index=self._close.index, name='psaridown')\n\n\ndef ema_indicator(close, n=12, fillna=False):\n \"\"\"Exponential Moving Average (EMA)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return EMAIndicator(close=close, n=n, fillna=fillna).ema_indicator()\n\n\ndef sma_indicator(close, n=12, fillna=False):\n \"\"\"Simple Moving Average (SMA)\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return SMAIndicator(close=close, n=n, fillna=fillna).sma_indicator()\n\n\ndef macd(close, n_slow=26, n_fast=12, fillna=False):\n \"\"\"Moving Average Convergence Divergence (MACD)\n\n Is a trend-following momentum indicator that shows the relationship between\n two moving averages of prices.\n\n https://en.wikipedia.org/wiki/MACD\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n n_fast(int): n period short-term.\n n_slow(int): n period long-term.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return MACD(close=close, n_slow=n_slow, n_fast=n_fast, n_sign=9, fillna=fillna).macd()\n\n\ndef macd_signal(close, n_slow=26, n_fast=12, n_sign=9, fillna=False):\n \"\"\"Moving Average Convergence Divergence (MACD Signal)\n\n Shows EMA of MACD.\n\n https://en.wikipedia.org/wiki/MACD\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n n_fast(int): n period short-term.\n n_slow(int): n period long-term.\n n_sign(int): n period to signal.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return MACD(close=close, n_slow=n_slow, n_fast=n_fast, n_sign=n_sign, fillna=fillna).macd_signal()\n\n\ndef macd_diff(close, n_slow=26, n_fast=12, n_sign=9, fillna=False):\n \"\"\"Moving Average Convergence Divergence (MACD Diff)\n\n Shows the relationship between MACD and MACD Signal.\n\n https://en.wikipedia.org/wiki/MACD\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n n_fast(int): n period short-term.\n n_slow(int): n period long-term.\n n_sign(int): n period to signal.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return MACD(close=close, n_slow=n_slow, n_fast=n_fast, n_sign=n_sign, fillna=fillna).macd_diff()\n\n\ndef adx(high, low, close, n=14, fillna=False):\n \"\"\"Average Directional Movement Index (ADX)\n\n The Plus Directional Indicator (+DI) and Minus Directional Indicator (-DI)\n are derived from smoothed averages of these differences, and measure trend\n direction over time. These two indicators are often referred to\n collectively as the Directional Movement Indicator (DMI).\n\n The Average Directional Index (ADX) is in turn derived from the smoothed\n averages of the difference between +DI and -DI, and measures the strength\n of the trend (regardless of direction) over time.\n\n Using these three indicators together, chartists can determine both the\n direction and strength of the trend.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:average_directional_index_adx\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n close(pandas.Series): dataset 'Close' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return ADXIndicator(high=high, low=low, close=close, n=n, fillna=fillna).adx()\n\n\ndef adx_pos(high, low, close, n=14, fillna=False):\n \"\"\"Average Directional Movement Index Positive (ADX)\n\n The Plus Directional Indicator (+DI) and Minus Directional Indicator (-DI)\n are derived from smoothed averages of these differences, and measure trend\n direction over time. These two indicators are often referred to\n collectively as the Directional Movement Indicator (DMI).\n\n The Average Directional Index (ADX) is in turn derived from the smoothed\n averages of the difference between +DI and -DI, and measures the strength\n of the trend (regardless of direction) over time.\n\n Using these three indicators together, chartists can determine both the\n direction and strength of the trend.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:average_directional_index_adx\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n close(pandas.Series): dataset 'Close' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return ADXIndicator(high=high, low=low, close=close, n=n, fillna=fillna).adx_pos()\n\n\ndef adx_neg(high, low, close, n=14, fillna=False):\n \"\"\"Average Directional Movement Index Negative (ADX)\n\n The Plus Directional Indicator (+DI) and Minus Directional Indicator (-DI)\n are derived from smoothed averages of these differences, and measure trend\n direction over time. These two indicators are often referred to\n collectively as the Directional Movement Indicator (DMI).\n\n The Average Directional Index (ADX) is in turn derived from the smoothed\n averages of the difference between +DI and -DI, and measures the strength\n of the trend (regardless of direction) over time.\n\n Using these three indicators together, chartists can determine both the\n direction and strength of the trend.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:average_directional_index_adx\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n close(pandas.Series): dataset 'Close' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return ADXIndicator(high=high, low=low, close=close, n=n, fillna=fillna).adx_neg()\n\n\ndef vortex_indicator_pos(high, low, close, n=14, fillna=False):\n \"\"\"Vortex Indicator (VI)\n\n It consists of two oscillators that capture positive and negative trend\n movement. A bullish signal triggers when the positive trend indicator\n crosses above the negative trend indicator or a key level.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:vortex_indicator\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n close(pandas.Series): dataset 'Close' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return VortexIndicator(high=high, low=low, close=close, n=n, fillna=fillna).vortex_indicator_pos()\n\n\ndef vortex_indicator_neg(high, low, close, n=14, fillna=False):\n \"\"\"Vortex Indicator (VI)\n\n It consists of two oscillators that capture positive and negative trend\n movement. A bearish signal triggers when the negative trend indicator\n crosses above the positive trend indicator or a key level.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:vortex_indicator\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n close(pandas.Series): dataset 'Close' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return VortexIndicator(high=high, low=low, close=close, n=n, fillna=fillna).vortex_indicator_neg()\n\n\ndef trix(close, n=15, fillna=False):\n \"\"\"Trix (TRIX)\n\n Shows the percent rate of change of a triple exponentially smoothed moving\n average.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:trix\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return TRIXIndicator(close=close, n=n, fillna=fillna).trix()\n\n\ndef mass_index(high, low, n=9, n2=25, fillna=False):\n \"\"\"Mass Index (MI)\n\n It uses the high-low range to identify trend reversals based on range\n expansions. It identifies range bulges that can foreshadow a reversal of\n the current trend.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:mass_index\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n n(int): n low period.\n n2(int): n high period.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n\n \"\"\"\n return MassIndex(high=high, low=low, n=n, n2=n2, fillna=fillna).mass_index()\n\n\ndef cci(high, low, close, n=20, c=0.015, fillna=False):\n \"\"\"Commodity Channel Index (CCI)\n\n CCI measures the difference between a security's price change and its\n average price change. High positive readings indicate that prices are well\n above their average, which is a show of strength. Low negative readings\n indicate that prices are well below their average, which is a show of\n weakness.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:commodity_channel_index_cci\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n close(pandas.Series): dataset 'Close' column.\n n(int): n periods.\n c(int): constant.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n\n \"\"\"\n return CCIIndicator(high=high, low=low, close=close, n=n, c=c, fillna=fillna).cci()\n\n\ndef dpo(close, n=20, fillna=False):\n \"\"\"Detrended Price Oscillator (DPO)\n\n Is an indicator designed to remove trend from price and make it easier to\n identify cycles.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:detrended_price_osci\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return DPOIndicator(close=close, n=n, fillna=fillna).dpo()\n\n\ndef kst(close, r1=10, r2=15, r3=20, r4=30, n1=10, n2=10, n3=10, n4=15, fillna=False):\n \"\"\"KST Oscillator (KST)\n\n It is useful to identify major stock market cycle junctures because its\n formula is weighed to be more greatly influenced by the longer and more\n dominant time spans, in order to better reflect the primary swings of stock\n market cycle.\n\n https://en.wikipedia.org/wiki/KST_oscillator\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n r1(int): r1 period.\n r2(int): r2 period.\n r3(int): r3 period.\n r4(int): r4 period.\n n1(int): n1 smoothed period.\n n2(int): n2 smoothed period.\n n3(int): n3 smoothed period.\n n4(int): n4 smoothed period.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return KSTIndicator(\n close=close, r1=r1, r2=r2, r3=r3, r4=r4, n1=n1, n2=n2, n3=n3, n4=n4, nsig=9, fillna=fillna).kst()\n\n\ndef kst_sig(close, r1=10, r2=15, r3=20, r4=30, n1=10, n2=10, n3=10, n4=15, nsig=9, fillna=False):\n \"\"\"KST Oscillator (KST Signal)\n\n It is useful to identify major stock market cycle junctures because its\n formula is weighed to be more greatly influenced by the longer and more\n dominant time spans, in order to better reflect the primary swings of stock\n market cycle.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:know_sure_thing_kst\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n r1(int): r1 period.\n r2(int): r2 period.\n r3(int): r3 period.\n r4(int): r4 period.\n n1(int): n1 smoothed period.\n n2(int): n2 smoothed period.\n n3(int): n3 smoothed period.\n n4(int): n4 smoothed period.\n nsig(int): n period to signal.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return KSTIndicator(\n close=close, r1=r1, r2=r2, r3=r3, r4=r4, n1=n1, n2=n2, n3=n3, n4=n4, nsig=nsig, fillna=fillna).kst_sig()\n\n\ndef ichimoku_conversion_line(high, low, n1=9, n2=26, visual=False, fillna=False) -> pd.Series:\n \"\"\"Tenkan-sen (Conversion Line)\n\n It identifies the trend and look for potential signals within that trend.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:ichimoku_cloud\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n n1(int): n1 low period.\n n2(int): n2 medium period.\n visual(bool): if True, shift n2 values.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return IchimokuIndicator(\n high=high, low=low, n1=n1, n2=n2, n3=52, visual=visual, fillna=fillna).ichimoku_conversion_line()\n\n\ndef ichimoku_base_line(high, low, n1=9, n2=26, visual=False, fillna=False) -> pd.Series:\n \"\"\"Kijun-sen (Base Line)\n\n It identifies the trend and look for potential signals within that trend.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:ichimoku_cloud\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n n1(int): n1 low period.\n n2(int): n2 medium period.\n visual(bool): if True, shift n2 values.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return IchimokuIndicator(\n high=high, low=low, n1=n1, n2=n2, n3=52, visual=visual, fillna=fillna).ichimoku_base_line()\n\n\ndef ichimoku_a(high, low, n1=9, n2=26, visual=False, fillna=False):\n \"\"\"Ichimoku Kinkō Hyō (Ichimoku)\n\n It identifies the trend and look for potential signals within that trend.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:ichimoku_cloud\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n n1(int): n1 low period.\n n2(int): n2 medium period.\n visual(bool): if True, shift n2 values.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return IchimokuIndicator(high=high, low=low, n1=n1, n2=n2, n3=52, visual=visual, fillna=fillna).ichimoku_a()\n\n\ndef ichimoku_b(high, low, n2=26, n3=52, visual=False, fillna=False):\n \"\"\"Ichimoku Kinkō Hyō (Ichimoku)\n\n It identifies the trend and look for potential signals within that trend.\n\n http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:ichimoku_cloud\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n n2(int): n2 medium period.\n n3(int): n3 high period.\n visual(bool): if True, shift n2 values.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return IchimokuIndicator(high=high, low=low, n1=9, n2=n2, n3=n3, visual=visual, fillna=fillna).ichimoku_b()\n\n\ndef aroon_up(close, n=25, fillna=False):\n \"\"\"Aroon Indicator (AI)\n\n Identify when trends are likely to change direction (uptrend).\n\n Aroon Up - ((N - Days Since N-day High) / N) x 100\n\n https://www.investopedia.com/terms/a/aroon.asp\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n\n \"\"\"\n return AroonIndicator(close=close, n=n, fillna=fillna).aroon_up()\n\n\ndef aroon_down(close, n=25, fillna=False):\n \"\"\"Aroon Indicator (AI)\n\n Identify when trends are likely to change direction (downtrend).\n\n Aroon Down - ((N - Days Since N-day Low) / N) x 100\n\n https://www.investopedia.com/terms/a/aroon.asp\n\n Args:\n close(pandas.Series): dataset 'Close' column.\n n(int): n period.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n return AroonIndicator(close=close, n=n, fillna=fillna).aroon_down()\n\n\ndef psar_up(high, low, close, step=0.02, max_step=0.20, fillna=False):\n \"\"\"Parabolic Stop and Reverse (Parabolic SAR)\n\n Returns the PSAR series with non-N/A values for upward trends\n\n https://school.stockcharts.com/doku.php?id=technical_indicators:parabolic_sar\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n close(pandas.Series): dataset 'Close' column.\n step(float): the Acceleration Factor used to compute the SAR.\n max_step(float): the maximum value allowed for the Acceleration Factor.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n indicator = PSARIndicator(high=high, low=low, close=close, step=step,\n max_step=max_step, fillna=fillna)\n return indicator.psar_up()\n\n\ndef psar_down(high, low, close, step=0.02, max_step=0.20, fillna=False):\n \"\"\"Parabolic Stop and Reverse (Parabolic SAR)\n\n Returns the PSAR series with non-N/A values for downward trends\n\n https://school.stockcharts.com/doku.php?id=technical_indicators:parabolic_sar\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n close(pandas.Series): dataset 'Close' column.\n step(float): the Acceleration Factor used to compute the SAR.\n max_step(float): the maximum value allowed for the Acceleration Factor.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n indicator = PSARIndicator(high=high, low=low, close=close, step=step,\n max_step=max_step, fillna=fillna)\n return indicator.psar_down()\n\n\ndef psar_up_indicator(high, low, close, step=0.02, max_step=0.20, fillna=False):\n \"\"\"Parabolic Stop and Reverse (Parabolic SAR) Upward Trend Indicator\n\n Returns 1, if there is a reversal towards an upward trend. Else, returns 0.\n\n https://school.stockcharts.com/doku.php?id=technical_indicators:parabolic_sar\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n close(pandas.Series): dataset 'Close' column.\n step(float): the Acceleration Factor used to compute the SAR.\n max_step(float): the maximum value allowed for the Acceleration Factor.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n indicator = PSARIndicator(high=high, low=low, close=close, step=step,\n max_step=max_step, fillna=fillna)\n return indicator.psar_up_indicator()\n\n\ndef psar_down_indicator(high, low, close, step=0.02, max_step=0.20, fillna=False):\n \"\"\"Parabolic Stop and Reverse (Parabolic SAR) Downward Trend Indicator\n\n Returns 1, if there is a reversal towards an downward trend. Else, returns 0.\n\n https://school.stockcharts.com/doku.php?id=technical_indicators:parabolic_sar\n\n Args:\n high(pandas.Series): dataset 'High' column.\n low(pandas.Series): dataset 'Low' column.\n close(pandas.Series): dataset 'Close' column.\n step(float): the Acceleration Factor used to compute the SAR.\n max_step(float): the maximum value allowed for the Acceleration Factor.\n fillna(bool): if True, fill nan values.\n\n Returns:\n pandas.Series: New feature generated.\n \"\"\"\n indicator = PSARIndicator(high=high, low=low, close=close, step=step,\n max_step=max_step, fillna=fillna)\n return indicator.psar_down_indicator()\n"
] | [
[
"numpy.abs",
"pandas.Series",
"numpy.concatenate",
"numpy.argmax",
"numpy.mean",
"numpy.argmin",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
smarsu/mtcnn | [
"98c3839e250b18c310efa920bc6289a70379f07d"
] | [
"datasets.py"
] | [
"# --------------------------------------------------------\r\n# Face Datasets\r\n# Licensed under The MIT License [see LICENSE for details]\r\n# Copyright 2019 smarsu. All Rights Reserved.\r\n# --------------------------------------------------------\r\n\r\nimport os.path as osp\r\nimport numpy as np\r\n\r\n\r\nclass Dataset(object):\r\n \"\"\"The base class of dataset.\r\n \r\n self._train_datas = [n, str]\r\n self._train_labels = [n, list of box]\r\n \"\"\"\r\n def __init__(self):\r\n pass\r\n\r\n\r\n @property\r\n def size(self):\r\n \"\"\"Return the number of train datas.\"\"\"\r\n raise NotImplementedError\r\n\r\n\r\n def train_datas_debug(self, batch_size):\r\n \"\"\"Yield batch size train datas per step. \r\n\r\n Train datas should be shuffled.\r\n \r\n Args:\r\n batch_size: int, > 0\r\n \"\"\"\r\n if not isinstance(batch_size, int):\r\n raise ValueError('In Dataset, batch_size should be int, get '\r\n '{}'.format(type(batch_size)))\r\n if batch_size <= 0:\r\n raise ValueError('In Dataset, batch_size should larger equal to '\r\n '1, get {}'.format(batch_size))\r\n \r\n indices = list(range(batch_size))\r\n \r\n datas = []\r\n # for label, we have box and landmark which is 0.\r\n datas.append([self._train_datas[:batch_size], \r\n self._train_labels[:batch_size]])\r\n return datas\r\n\r\n\r\n def train_datas(self, batch_size):\r\n \"\"\"Yield batch size train datas per step. \r\n\r\n Train datas should be shuffled.\r\n \r\n Args:\r\n batch_size: int, > 0\r\n \"\"\"\r\n if not isinstance(batch_size, int):\r\n raise ValueError('In Dataset, batch_size should be int, get '\r\n '{}'.format(type(batch_size)))\r\n if batch_size <= 0:\r\n raise ValueError('In Dataset, batch_size should larger equal to '\r\n '1, get {}'.format(batch_size))\r\n \r\n indices = list(range(self.size))\r\n np.random.shuffle(indices)\r\n\r\n epoch_size = self.size // batch_size * batch_size\r\n self._train_datas = self._train_datas[indices][:epoch_size] # [epoch_size, ...]\r\n self._train_labels = self._train_labels[indices][:epoch_size] # [epoch_size, ...]\r\n \r\n datas = []\r\n for i in range(self.size // batch_size):\r\n # for label, we have box and landmark which is 0.\r\n datas.append([self._train_datas[i*batch_size:(i+1)*batch_size], \r\n self._train_labels[i*batch_size:(i+1)*batch_size]])\r\n return datas\r\n\r\n\r\n def merge(self, other):\r\n \"\"\"Merge the other datas to self.\r\n \r\n Args:\r\n other: Dataset\r\n \"\"\"\r\n self._train_datas = np.concatenate(\r\n [self._train_datas, other._train_datas], 0)\r\n self._train_labels = np.concatenate(\r\n [self._train_labels, other._train_labels], 0)\r\n\r\n\r\nclass WiderFace(Dataset):\r\n def __init__(self, train_image_path, label_path, value_image_path=None, \r\n test_image_path=None):\r\n \"\"\"\r\n TODO(smarsu): Add way to read `value_image_path` and `test_image_path`.\r\n Add way to read `value_label_path` and `test_label_path`.\r\n\r\n Args:\r\n train_image_path: str, the path of train images.\r\n label_path: str\r\n \"\"\"\r\n self._data_map = {}\r\n\r\n self.train_image_path = train_image_path\r\n self.label_path = label_path\r\n self.train_label_path = self.label_path\r\n\r\n self._train_datas, self._train_labels = self._read_train_datas()\r\n\r\n\r\n @property\r\n def size(self):\r\n \"\"\"Return the number of train datas.\r\n \r\n Assert the size of self._train_datas and self._train_labels is equal.\r\n \"\"\"\r\n return len(self._train_datas)\r\n\r\n\r\n def data_map(self, key):\r\n \"\"\"\"\"\"\r\n if key not in self._data_map:\r\n raise KeyError('{} not in the data map.'.format(key))\r\n return self._data_map[key]\r\n\r\n\r\n def _real_image_path(self, path):\r\n \"\"\"Get real path of image.\r\n\r\n self.train_image_path + '/' + path\r\n \r\n Args:\r\n path: str, the image name(id) of labels.\r\n \"\"\"\r\n return osp.join(self.train_image_path, path)\r\n\r\n\r\n def _read_train_datas(self):\r\n \"\"\"The special way to read wider face labels.\r\n\r\n Args:\r\n label_path: str, \r\n \"\"\"\r\n with open(self.train_label_path, 'r') as fb:\r\n lines = fb.readlines()\r\n return self._parse_raw_labels(lines)\r\n\r\n\r\n def _parse_raw_labels(self, lines):\r\n \"\"\"Parse raw str lines to python object.\r\n \r\n Args:\r\n lines: list of str, with the structure of \r\n File name\r\n Number of bounding box\r\n x1, y1, w, h, blur, expression, illumination, invalid, occlusion, pose\r\n\r\n Returns:\r\n images: numpy array, [n], image paths\r\n labels: numpy array, [n, 4], [x1, y1, x2, y2]\r\n \"\"\"\r\n images = []\r\n labels = []\r\n idx = 0\r\n while idx < len(lines):\r\n image_path = lines[idx].strip()\r\n images.append(self._real_image_path(image_path))\r\n idx += 1\r\n\r\n num = int(lines[idx])\r\n idx += 1\r\n\r\n labels_ = []\r\n for _ in range(num):\r\n x1, y1, w, h, blur, expression, illumination, invalid, \\\r\n occlusion, pose = [int(v) \r\n for v in lines[idx].strip().split()]\r\n x2, y2 = x1 + w - 1, y1 + h - 1 # -1 to get the read x2, y2\r\n\r\n labels_.append([x1, y1, x2, y2])\r\n idx += 1\r\n \r\n labels.append(np.array(labels_))\r\n\r\n self._data_map[self._real_image_path(image_path)] = np.array(labels_)\r\n return np.array(images), np.array(labels)\r\n\r\n\r\nif __name__ == '__main__':\r\n import time\r\n # Test wider face dataset\r\n wider = WiderFace('/datasets/wider/images', \r\n '/datasets/wider/wider_face_split/wider_face_train_bbx_gt.txt')\r\n t1 = time.time()\r\n for data, label in wider.train_datas(32):\r\n print(data, label)\r\n t2 = time.time()\r\n print('Time for read wider dataset:', t2 - t1) # 2.467153787612915s with `print`\r\n print(type(wider._train_datas))\r\n print(type(wider._train_labels))\r\n"
] | [
[
"numpy.concatenate",
"numpy.array",
"numpy.random.shuffle"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
chinchila/codesearch | [
"9b91ce40e8a727932302436c4de2eddb04ebb396"
] | [
"codesearch/retrieval.py"
] | [
"# © 2020 Nokia\n#\n# Licensed under the BSD 3 Clause license\n#\n# SPDX-License-Identifier: BSD-3-Clause\n# ============================================\n\n\nimport functools\nimport sys\n\nimport numpy as np\n\nfrom codesearch.utils import Saveable\nfrom codesearch.data_config import DESCRIPTION_FIELD, CODE_FIELD\n \n\nclass RetrievalModel(Saveable):\n \n def __init__(self):\n super().__init__()\n self._id2snippet = {}\n \n def query(self, query, n=10, projection=[], **kwargs):\n n = min(n, len(self._id2snippet))\n if projection and \"id\" not in projection:\n projection = [\"id\"] + projection\n sims = self.similarities(query, **kwargs)\n return_sims = \"score\" in projection or not projection\n if return_sims:\n ranking_ids, sims = self._sims_to_ranking(sims, n, return_sims)\n else:\n ranking_ids = self._sims_to_ranking(sims, n, return_sims)\n sims = None\n ranking_snippets = [dict(self._id2snippet[id_]) for id_ in ranking_ids]\n if sims:\n for s, sim in zip(ranking_snippets, sims):\n s[\"score\"] = sim\n if projection:\n ranking_snippets = [ {f: r[f] for f in projection} for r in ranking_snippets]\n \n return ranking_snippets\n \n def log_query_results(self, queries, relevant_ids=[], projection=[DESCRIPTION_FIELD, CODE_FIELD], log_file=None):\n if log_file:\n stdout = sys.stdout\n with open(log_file, \"a\") as f:\n sys.stdout = f\n self._log_query_results(queries, relevant_ids, projection)\n sys.stdout = stdout\n else:\n self._log_query_results(queries, relevant_ids, projection)\n\n \n def _log_query_results(self, queries, relevant_ids=[], projection=[DESCRIPTION_FIELD, CODE_FIELD]):\n \n line1 = \"*\" * 40\n line2 = \"-\" * 40\n line3 = \"-\" * 10\n for q in queries:\n results = self.query(q, n=5, projection=projection)\n print(line1)\n print(f\"QUERY: {q}\")\n print(line1)\n print()\n for i, r in enumerate(results):\n annotation = \"\"\n if relevant_ids and r[\"id\"] in relevant_ids:\n annotation = \" - RELEVANT\"\n print(line2)\n print(f\"RANK {i+1}{annotation}\")\n print(line2)\n for f in projection:\n if \"\\n\" in str(r[f]):\n print(f\"{f.upper()}:\")\n print(r[f])\n else:\n print(f\"{f.upper()}: {r[f]}\")\n print(line2)\n print()\n print()\n print()\n \n \n \n def _sims_to_ranking(self, sims, n, return_sims):\n idxs = np.argpartition(sims, -n)[-n:]\n top_idxs = idxs[np.argsort(sims[idxs])][::-1]\n snippet_ids = [self.get_snippetid(top_idx) for top_idx in top_idxs]\n if return_sims:\n top_sims = [sims[top_idx] for top_idx in top_idxs]\n return snippet_ids, top_sims\n return snippet_ids\n \n def query_batch(self, queries, n=10, return_sims=False, **kwargs):\n sims_batch = self.similarities_batch(tuple(queries), **kwargs)\n snippet_ids_batch = []\n for sims in sims_batch:\n snippet_ids = self._sims_to_ranking(sims, n, return_sims)\n snippet_ids_batch.append(snippet_ids)\n return snippet_ids_batch\n \n def add_snippets(self, snippets):\n for s in snippets:\n self._id2snippet[s[\"id\"]] = s\n \n def get_snippetid(self, idx):\n pass\n \n def similarities(self, query, **kwargs):\n pass\n \n def save(self, path):\n super().save(path)\n \n\nclass RetrievalEnsemble(RetrievalModel):\n \n def __init__(self, retrieval_models, weights):\n super().__init__()\n self.retrieval_models = retrieval_models\n self.weights = weights\n\n def similarities(self, query, model_kwargs=None):\n N = len(self.snippets)\n sims = np.zeros(shape=(N,), dtype=np.float32)\n for i, model in enumerate(self.retrieval_models):\n weight = self.weights[i] if self.weights else 1.\n sims += (weight * model.similarities(query))\n \n return sims "
] | [
[
"numpy.argsort",
"numpy.zeros",
"numpy.argpartition"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Victorwz/fast-weights-pytorch | [
"cef79631c9e41ae48fedbbc11e52be0cf084bfde"
] | [
"generator.py"
] | [
"import numpy as np\nimport random\nimport pickle\n\nnum_train = 60000\nnum_val = 10000\nnum_test = 10000\n\nstep_num = 4\nelem_num = 26 + 10 + 1\n\nx_train = np.zeros([num_train, step_num * 2 + 3, elem_num], dtype=np.float32)\nx_val = np.zeros([num_val, step_num * 2 + 3, elem_num], dtype=np.float32)\nx_test = np.zeros([num_test, step_num * 2 + 3, elem_num], dtype=np.float32)\n\ny_train = np.zeros([num_train, elem_num], dtype=np.float32)\ny_val = np.zeros([num_val, elem_num], dtype=np.float32)\ny_test = np.zeros([num_test, elem_num], dtype=np.float32)\n\n\ndef get_one_hot(c):\n a = np.zeros([elem_num])\n if ord('a') <= ord(c) <= ord('z'):\n a[ord(c) - ord('a')] = 1\n elif ord('0') <= ord(c) <= ord('9'):\n a[ord(c) - ord('0') + 26] = 1\n else:\n a[-1] = 1\n return a\n\n\ndef generate_one():\n a = np.zeros([step_num * 2 + 3, elem_num])\n d = {}\n st = ''\n\n for i in range(0, step_num):\n c = random.randint(0, 25)\n while d.has_key(c):\n c = random.randint(0, 25)\n b = random.randint(0, 9)\n d[c] = b\n s, t = chr(c + ord('a')), chr(b + ord('0'))\n st += s + t\n a[i*2] = get_one_hot(s)\n a[i*2+1] = get_one_hot(t)\n\n s = random.choice(d.keys())\n t = chr(s + ord('a'))\n r = chr(d[s] + ord('0'))\n a[step_num * 2] = get_one_hot('?')\n a[step_num * 2 + 1] = get_one_hot('?')\n a[step_num * 2 + 2] = get_one_hot(t)\n st += '??' + t + r\n e = get_one_hot(r)\n return a, e\n\nif __name__ == '__main__':\n for i in range(0, num_train):\n x_train[i], y_train[i] = generate_one()\n\n for i in range(0, num_test):\n x_test[i], y_test[i] = generate_one()\n\n for i in range(0, num_val):\n x_val[i], y_val[i] = generate_one()\n\n d = {\n 'x_train': x_train,\n 'x_test': x_test,\n 'x_val': x_val,\n 'y_train': y_train,\n 'y_test': y_test,\n 'y_val': y_val\n }\n with open('associative-retrieval.pkl', 'wb') as f:\n pickle.dump(d, f, protocol=2)"
] | [
[
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ml-resources/tensorflow | [
"4ecd72b68cd70c3930551aebbf0c80badc301d28"
] | [
"tensorflow/python/framework/ops.py"
] | [
"# Copyright 2015 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\n\"\"\"Classes and functions used to construct graphs.\"\"\"\n# pylint: disable=g-bad-name\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport contextlib\nimport copy\nimport linecache\nimport re\nimport sys\nimport threading\n\nimport six\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.core.framework import function_pb2\nfrom tensorflow.core.framework import graph_pb2\nfrom tensorflow.core.framework import node_def_pb2\nfrom tensorflow.core.framework import tensor_shape_pb2\nfrom tensorflow.core.framework import types_pb2\nfrom tensorflow.core.framework import versions_pb2\nfrom tensorflow.python.framework import device as pydev\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import op_def_registry\nfrom tensorflow.python.framework import registry\nfrom tensorflow.python.framework import tensor_shape\nfrom tensorflow.python.framework import versions\nfrom tensorflow.python.platform import tf_logging as logging\nfrom tensorflow.python.util import compat\nfrom tensorflow.python.util import decorator_utils\n\n\ndef _override_helper(clazz_object, operator, func):\n \"\"\"Overrides (string) operator on Tensors to call func.\n\n Args:\n clazz_object: the class to override for; either Tensor or SparseTensor.\n operator: the string name of the operator to override.\n func: the function that replaces the overridden operator.\n\n Raises:\n ValueError: If operator has already been overwritten,\n or if operator is not allowed to be overwritten.\n \"\"\"\n existing = getattr(clazz_object, operator, None)\n if existing is not None:\n # Check to see if this is a default method-wrapper or slot wrapper which\n # will be true for the comparison operators.\n if not isinstance(existing, type(object.__lt__)):\n raise ValueError(\"operator %s cannot be overwritten again on class %s.\" %\n (operator, clazz_object))\n if operator not in Tensor.OVERLOADABLE_OPERATORS:\n raise ValueError(\"Overriding %s is disallowed\" % operator)\n setattr(clazz_object, operator, func)\n\n\ndef _convert_stack(stack):\n \"\"\"Converts a stack extracted using _extract_stack() to a traceback stack.\n\n Args:\n stack: A list of n 4-tuples, (filename, lineno, name, frame_globals).\n\n Returns:\n A list of n 4-tuples (filename, lineno, name, code), where the code tuple\n element is calculated from the corresponding elements of the input tuple.\n \"\"\"\n ret = []\n for filename, lineno, name, frame_globals in stack:\n linecache.checkcache(filename)\n line = linecache.getline(filename, lineno, frame_globals)\n if line:\n line = line.strip()\n else:\n line = None\n ret.append((filename, lineno, name, line))\n return ret\n\n\n# pylint: disable=line-too-long\ndef _extract_stack():\n \"\"\"A lightweight re-implementation of traceback.extract_stack.\n\n NOTE(mrry): traceback.extract_stack eagerly retrieves the line of code for\n each stack frame using linecache, which results in an abundance of stat()\n calls. This implementation does not retrieve the code, and any consumer\n should apply _convert_stack to the result to obtain a traceback that can\n be formatted etc. using traceback methods.\n\n Returns:\n A list of 4-tuples (filename, lineno, name, frame_globals) corresponding to\n the call stack of the current thread.\n \"\"\"\n # pylint: enable=line-too-long\n try:\n raise ZeroDivisionError\n except ZeroDivisionError:\n f = sys.exc_info()[2].tb_frame.f_back\n ret = []\n while f is not None:\n lineno = f.f_lineno\n co = f.f_code\n filename = co.co_filename\n name = co.co_name\n frame_globals = f.f_globals\n ret.append((filename, lineno, name, frame_globals))\n f = f.f_back\n ret.reverse()\n return ret\n\n\ndef _as_graph_element(obj):\n \"\"\"Convert `obj` to a graph element if possible, otherwise return `None`.\n\n Args:\n obj: Object to convert.\n\n Returns:\n The result of `obj._as_graph_element()` if that method is available;\n otherwise `None`.\n \"\"\"\n conv_fn = getattr(obj, \"_as_graph_element\", None)\n if conv_fn and callable(conv_fn):\n return conv_fn()\n return None\n\n\n_TENSOR_LIKE_TYPES = tuple()\n\n\ndef is_dense_tensor_like(t):\n \"\"\"EXPERIMENTAL: Returns true if `t` implements the tensor interface.\n\n See `register_dense_tensor_like_type()` for the current definition of a\n \"tensor-like type\".\n\n Args:\n t: An object.\n\n Returns:\n True iff `t` is an instance of one of the registered \"tensor-like\" types.\n \"\"\"\n return isinstance(t, _TENSOR_LIKE_TYPES)\n\n\ndef register_dense_tensor_like_type(tensor_type):\n \"\"\"EXPERIMENTAL: Registers `tensor_type` as implementing the tensor interface.\n\n A \"tensor-like type\" can represent a single dense tensor, and implements\n the `name` and `dtype` properties.\n\n Args:\n tensor_type: A type implementing the tensor interface.\n\n Raises:\n TypeError: If `tensor_type` does not implement the tensor interface.\n \"\"\"\n try:\n if not isinstance(tensor_type.name, property):\n raise TypeError(\"Type %s does not define a `name` property\")\n except AttributeError:\n raise TypeError(\"Type %s does not define a `name` property\")\n try:\n if not isinstance(tensor_type.dtype, property):\n raise TypeError(\"Type %s does not define a `dtype` property\")\n except AttributeError:\n raise TypeError(\"Type %s does not define a `dtype` property\")\n # We expect this list to be small, so choose quadratic complexity\n # for registration, so that we have a tuple that can be used for\n # more efficient `isinstance` checks later.\n global _TENSOR_LIKE_TYPES\n _TENSOR_LIKE_TYPES = tuple(list(_TENSOR_LIKE_TYPES) + [tensor_type])\n\n\n# NOTE(ebrevdo): Do not subclass this. If you do, I will break you on purpose.\nclass _TensorLike(object):\n \"\"\"Internal cls for grouping Tensor, SparseTensor, ..., for is_instance.\"\"\"\n pass\n\n\nclass Tensor(_TensorLike):\n \"\"\"Represents one of the outputs of an `Operation`.\n\n A `Tensor` is a symbolic handle to one of the outputs of an\n `Operation`. It does not hold the values of that operation's output,\n but instead provides a means of computing those values in a\n TensorFlow [`Session`](../../api_docs/python/client.md#Session).\n\n This class has two primary purposes:\n\n 1. A `Tensor` can be passed as an input to another `Operation`.\n This builds a dataflow connection between operations, which\n enables TensorFlow to execute an entire `Graph` that represents a\n large, multi-step computation.\n\n 2. After the graph has been launched in a session, the value of the\n `Tensor` can be computed by passing it to\n [`Session.run()`](../../api_docs/python/client.md#Session.run).\n `t.eval()` is a shortcut for calling\n `tf.get_default_session().run(t)`.\n\n In the following example, `c`, `d`, and `e` are symbolic `Tensor`\n objects, whereas `result` is a numpy array that stores a concrete\n value:\n\n ```python\n # Build a dataflow graph.\n c = tf.constant([[1.0, 2.0], [3.0, 4.0]])\n d = tf.constant([[1.0, 1.0], [0.0, 1.0]])\n e = tf.matmul(c, d)\n\n # Construct a `Session` to execute the graph.\n sess = tf.Session()\n\n # Execute the graph and store the value that `e` represents in `result`.\n result = sess.run(e)\n ```\n\n @@dtype\n @@name\n @@value_index\n @@graph\n @@op\n @@consumers\n\n @@eval\n\n @@get_shape\n @@shape\n @@set_shape\n\n \"\"\"\n\n # List of Python operators that we allow to override.\n OVERLOADABLE_OPERATORS = {\n # Binary.\n \"__add__\",\n \"__radd__\",\n \"__sub__\",\n \"__rsub__\",\n \"__mul__\",\n \"__rmul__\",\n \"__div__\",\n \"__rdiv__\",\n \"__truediv__\",\n \"__rtruediv__\",\n \"__floordiv__\",\n \"__rfloordiv__\",\n \"__mod__\",\n \"__rmod__\",\n \"__lt__\",\n \"__le__\",\n \"__gt__\",\n \"__ge__\",\n \"__and__\",\n \"__rand__\",\n \"__or__\",\n \"__ror__\",\n \"__xor__\",\n \"__rxor__\",\n \"__getitem__\",\n \"__pow__\",\n \"__rpow__\",\n # Unary.\n \"__invert__\",\n \"__neg__\",\n \"__abs__\"\n }\n\n def __init__(self, op, value_index, dtype):\n \"\"\"Creates a new `Tensor`.\n\n Args:\n op: An `Operation`. `Operation` that computes this tensor.\n value_index: An `int`. Index of the operation's endpoint that produces\n this tensor.\n dtype: A `DType`. Type of elements stored in this tensor.\n\n Raises:\n TypeError: If the op is not an `Operation`.\n \"\"\"\n if not isinstance(op, Operation):\n raise TypeError(\"op needs to be an Operation: %s\" % op)\n self._op = op\n self._value_index = value_index\n self._dtype = dtypes.as_dtype(dtype)\n self._shape = tensor_shape.unknown_shape()\n # List of operations that use this Tensor as input. We maintain this list\n # to easily navigate a computation graph.\n self._consumers = []\n\n # Attributes used for C++ shape inference. Not inspected, only forwarded.\n self._handle_shape = tensor_shape_pb2.TensorShapeProto()\n self._handle_dtype = types_pb2.DT_INVALID\n\n @property\n def op(self):\n \"\"\"The `Operation` that produces this tensor as an output.\"\"\"\n return self._op\n\n @property\n def dtype(self):\n \"\"\"The `DType` of elements in this tensor.\"\"\"\n return self._dtype\n\n @property\n def graph(self):\n \"\"\"The `Graph` that contains this tensor.\"\"\"\n return self._op.graph\n\n @property\n def name(self):\n \"\"\"The string name of this tensor.\"\"\"\n if not self._op.name:\n raise ValueError(\"Operation was not named: %s\" % self._op)\n return \"%s:%d\" % (self._op.name, self._value_index)\n\n @property\n def device(self):\n \"\"\"The name of the device on which this tensor will be produced, or None.\"\"\"\n return self._op.device\n\n @property\n def shape(self):\n \"\"\"Returns the `TensorShape` that represents the shape of this tensor.\n\n The shape is computed using shape inference functions that are\n registered in the Op for each `Operation`. See\n [`TensorShape`](../../api_docs/python/framework.md#TensorShape)\n for more details of what a shape represents.\n\n The inferred shape of a tensor is used to provide shape\n information without having to launch the graph in a session. This\n can be used for debugging, and providing early error messages. For\n example:\n\n ```python\n c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])\n\n print(c.shape)\n ==> TensorShape([Dimension(2), Dimension(3)])\n\n d = tf.constant([[1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 1.0]])\n\n print(d.shape)\n ==> TensorShape([Dimension(4), Dimension(2)])\n\n # Raises a ValueError, because `c` and `d` do not have compatible\n # inner dimensions.\n e = tf.matmul(c, d)\n\n f = tf.matmul(c, d, transpose_a=True, transpose_b=True)\n\n print(f.shape)\n ==> TensorShape([Dimension(3), Dimension(4)])\n ```\n\n In some cases, the inferred shape may have unknown dimensions. If\n the caller has additional information about the values of these\n dimensions, `Tensor.set_shape()` can be used to augment the\n inferred shape.\n\n Returns:\n A `TensorShape` representing the shape of this tensor.\n\n \"\"\"\n return self._shape\n\n def _shape_as_list(self):\n if self._shape.ndims is not None:\n return [dim.value for dim in self._shape.dims]\n else:\n return None\n\n def get_shape(self):\n \"\"\"Alias of Tensor.shape.\"\"\"\n return self.shape\n\n def set_shape(self, shape):\n \"\"\"Updates the shape of this tensor.\n\n This method can be called multiple times, and will merge the given\n `shape` with the current shape of this tensor. It can be used to\n provide additional information about the shape of this tensor that\n cannot be inferred from the graph alone. For example, this can be used\n to provide additional information about the shapes of images:\n\n ```python\n _, image_data = tf.TFRecordReader(...).read(...)\n image = tf.image.decode_png(image_data, channels=3)\n\n # The height and width dimensions of `image` are data dependent, and\n # cannot be computed without executing the op.\n print(image.shape)\n ==> TensorShape([Dimension(None), Dimension(None), Dimension(3)])\n\n # We know that each image in this dataset is 28 x 28 pixels.\n image.set_shape([28, 28, 3])\n print(image.shape)\n ==> TensorShape([Dimension(28), Dimension(28), Dimension(3)])\n ```\n\n Args:\n shape: A `TensorShape` representing the shape of this tensor.\n\n Raises:\n ValueError: If `shape` is not compatible with the current shape of\n this tensor.\n \"\"\"\n self._shape = self._shape.merge_with(shape)\n\n @property\n def value_index(self):\n \"\"\"The index of this tensor in the outputs of its `Operation`.\"\"\"\n return self._value_index\n\n def consumers(self):\n \"\"\"Returns a list of `Operation`s that consume this tensor.\n\n Returns:\n A list of `Operation`s.\n \"\"\"\n return self._consumers\n\n def _add_consumer(self, consumer):\n \"\"\"Add a consumer to this tensor.\n\n Args:\n consumer: an Operation.\n\n Raises:\n TypeError: if the consumer is not an Operation.\n \"\"\"\n if not isinstance(consumer, Operation):\n raise TypeError(\"Consumer must be an Operation: %s\" % consumer)\n self._consumers.append(consumer)\n\n def _as_node_def_input(self):\n \"\"\"Return a value to use for the NodeDef \"input\" attribute.\n\n The returned string can be used in a NodeDef \"input\" attribute\n to indicate that the NodeDef uses this Tensor as input.\n\n Raises:\n ValueError: if this Tensor's Operation does not have a name.\n\n Returns:\n a string.\n \"\"\"\n if not self._op.name:\n raise ValueError(\"Operation was not named: %s\" % self._op)\n if self._value_index == 0:\n return self._op.name\n else:\n return \"%s:%d\" % (self._op.name, self._value_index)\n\n def __str__(self):\n return \"Tensor(\\\"%s\\\"%s%s%s)\" % (\n self.name,\n (\", shape=%s\" % self.get_shape())\n if self.get_shape().ndims is not None else \"\",\n (\", dtype=%s\" % self._dtype.name) if self._dtype else \"\",\n (\", device=%s\" % self.device) if self.device else \"\")\n\n def __repr__(self):\n return \"<tf.Tensor '%s' shape=%s dtype=%s>\" % (\n self.name, self.get_shape(), self._dtype.name)\n\n def __hash__(self):\n # Necessary to support Python's collection membership operators\n return id(self)\n\n def __eq__(self, other):\n # Necessary to support Python's collection membership operators\n return id(self) == id(other)\n\n # NOTE(mrry): This enables the Tensor's overloaded \"right\" binary\n # operators to run when the left operand is an ndarray, because it\n # accords the Tensor class higher priority than an ndarray, or a\n # numpy matrix.\n # TODO(mrry): Convert this to using numpy's __numpy_ufunc__\n # mechanism, which allows more control over how Tensors interact\n # with ndarrays.\n __array_priority__ = 100\n\n @staticmethod\n def _override_operator(operator, func):\n _override_helper(Tensor, operator, func)\n\n def __iter__(self):\n \"\"\"Dummy method to prevent iteration. Do not call.\n\n NOTE(mrry): If we register __getitem__ as an overloaded operator,\n Python will valiantly attempt to iterate over the Tensor from 0 to\n infinity. Declaring this method prevents this unintended\n behavior.\n\n Raises:\n TypeError: when invoked.\n \"\"\"\n raise TypeError(\"'Tensor' object is not iterable.\")\n\n def __bool__(self):\n \"\"\"Dummy method to prevent a tensor from being used as a Python `bool`.\n\n This overload raises a `TypeError` when the user inadvertently\n treats a `Tensor` as a boolean (e.g. in an `if` statement). For\n example:\n\n ```python\n if tf.constant(True): # Will raise.\n # ...\n\n if tf.constant(5) < tf.constant(7): # Will raise.\n # ...\n ```\n\n This disallows ambiguities between testing the Python value vs testing the\n dynamic condition of the `Tensor`.\n\n Raises:\n `TypeError`.\n \"\"\"\n raise TypeError(\"Using a `tf.Tensor` as a Python `bool` is not allowed. \"\n \"Use `if t is not None:` instead of `if t:` to test if a \"\n \"tensor is defined, and use TensorFlow ops such as \"\n \"tf.cond to execute subgraphs conditioned on the value of \"\n \"a tensor.\")\n\n def __nonzero__(self):\n \"\"\"Dummy method to prevent a tensor from being used as a Python `bool`.\n\n This is the Python 2.x counterpart to `__bool__()` above.\n\n Raises:\n `TypeError`.\n \"\"\"\n raise TypeError(\"Using a `tf.Tensor` as a Python `bool` is not allowed. \"\n \"Use `if t is not None:` instead of `if t:` to test if a \"\n \"tensor is defined, and use TensorFlow ops such as \"\n \"tf.cond to execute subgraphs conditioned on the value of \"\n \"a tensor.\")\n\n def eval(self, feed_dict=None, session=None):\n \"\"\"Evaluates this tensor in a `Session`.\n\n Calling this method will execute all preceding operations that\n produce the inputs needed for the operation that produces this\n tensor.\n\n *N.B.* Before invoking `Tensor.eval()`, its graph must have been\n launched in a session, and either a default session must be\n available, or `session` must be specified explicitly.\n\n Args:\n feed_dict: A dictionary that maps `Tensor` objects to feed values.\n See [`Session.run()`](../../api_docs/python/client.md#Session.run) for a\n description of the valid feed values.\n session: (Optional.) The `Session` to be used to evaluate this tensor. If\n none, the default session will be used.\n\n Returns:\n A numpy array corresponding to the value of this tensor.\n\n \"\"\"\n return _eval_using_default_session(self, feed_dict, self.graph, session)\n\n\ndef _TensorTensorConversionFunction(t, dtype=None, name=None, as_ref=False):\n _ = name, as_ref\n if dtype and not dtype.is_compatible_with(t.dtype):\n raise ValueError(\n \"Tensor conversion requested dtype %s for Tensor with dtype %s: %r\"\n % (dtype.name, t.dtype.name, str(t)))\n return t\n\n\n_tensor_conversion_func_registry = {\n 0: [(Tensor, _TensorTensorConversionFunction)]}\nregister_dense_tensor_like_type(Tensor)\n\n\ndef convert_to_tensor(value,\n dtype=None,\n name=None,\n preferred_dtype=None):\n \"\"\"Converts the given `value` to a `Tensor`.\n\n This function converts Python objects of various types to `Tensor`\n objects. It accepts `Tensor` objects, numpy arrays, Python lists,\n and Python scalars. For example:\n\n ```python\n import numpy as np\n\n def my_func(arg):\n arg = tf.convert_to_tensor(arg, dtype=tf.float32)\n return tf.matmul(arg, arg) + arg\n\n # The following calls are equivalent.\n value_1 = my_func(tf.constant([[1.0, 2.0], [3.0, 4.0]]))\n value_2 = my_func([[1.0, 2.0], [3.0, 4.0]])\n value_3 = my_func(np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32))\n ```\n\n This function can be useful when composing a new operation in Python\n (such as `my_func` in the example above). All standard Python op\n constructors apply this function to each of their Tensor-valued\n inputs, which allows those ops to accept numpy arrays, Python lists,\n and scalars in addition to `Tensor` objects.\n\n Args:\n value: An object whose type has a registered `Tensor` conversion function.\n dtype: Optional element type for the returned tensor. If missing, the\n type is inferred from the type of `value`.\n name: Optional name to use if a new `Tensor` is created.\n preferred_dtype: Optional element type for the returned tensor,\n used when dtype is None. In some cases, a caller may not have a\n dtype in mind when converting to a tensor, so preferred_dtype\n can be used as a soft preference. If the conversion to\n `preferred_dtype` is not possible, this argument has no effect.\n\n Returns:\n An `Output` based on `value`.\n\n Raises:\n TypeError: If no conversion function is registered for `value`.\n RuntimeError: If a registered conversion function returns an invalid value.\n\n \"\"\"\n return internal_convert_to_tensor(\n value=value,\n dtype=dtype,\n name=name,\n preferred_dtype=preferred_dtype,\n as_ref=False)\n\n\ndef internal_convert_to_tensor(value,\n dtype=None,\n name=None,\n as_ref=False,\n preferred_dtype=None):\n \"\"\"Converts the given `value` to an `Tensor`.\n\n This function converts Python objects of various types to `Tensor`\n objects. It accepts `Tensor` objects, numpy arrays, Python lists,\n and Python scalars. For example:\n\n This function can be useful when composing a new operation in Python\n All standard Python op constructors apply this function to each of their\n Tensor-valued inputs, which allows those ops to accept numpy arrays, Python\n lists, and scalars in addition to `Tensor` objects.\n\n Args:\n value: An object whose type has a registered `Tensor` conversion function.\n dtype: Optional element type for the returned tensor. If missing, the\n type is inferred from the type of `value`.\n name: Optional name to use if a new `Tensor` is created.\n as_ref: True if we want the mutable view of Variables, if applicable.\n preferred_dtype: Optional element type for the returned tensor,\n used when dtype is None. In some cases, a caller may not have a\n dtype in mind when converting to a tensor, so preferred_dtype\n can be used as a soft preference. If the conversion to\n `preferred_dtype` is not possible, this argument has no effect.\n\n Returns:\n A `Tensor` based on `value`.\n\n Raises:\n TypeError: If no conversion function is registered for `value`.\n RuntimeError: If a registered conversion function returns an invalid value.\n\n \"\"\"\n error_prefix = \"\" if name is None else \"%s: \" % name\n if dtype is not None:\n dtype = dtypes.as_dtype(dtype)\n for _, funcs_at_priority in sorted(_tensor_conversion_func_registry.items()):\n for base_type, conversion_func in funcs_at_priority:\n if isinstance(value, base_type):\n # If dtype is None but preferred_dtype is not None, we try to\n # cast to preferred_dtype first.\n ret = None\n if dtype is None and preferred_dtype is not None:\n try:\n ret = conversion_func(\n value, dtype=preferred_dtype, name=name, as_ref=as_ref)\n except (TypeError, ValueError):\n # Could not coerce the conversion to use the preferred dtype.\n ret = None\n\n if ret is not None and ret is not NotImplemented:\n if (ret.dtype.base_dtype !=\n dtypes.as_dtype(preferred_dtype).base_dtype):\n raise TypeError(\"convert_to_tensor did not convert to \"\n \"the preferred dtype: %s vs %s \" %\n (ret.dtype.base_dtype,\n dtypes.as_dtype(preferred_dtype).base_dtype))\n\n if ret is None:\n ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)\n\n if ret is NotImplemented:\n continue\n\n if not isinstance(ret, Tensor):\n raise RuntimeError(\n \"%sConversion function %r for type %s returned non-Tensor: %r\"\n % (error_prefix, conversion_func, base_type, ret))\n if dtype and not dtype.is_compatible_with(ret.dtype):\n raise RuntimeError(\n \"%sConversion function %r for type %s returned incompatible \"\n \"dtype: requested = %s, actual = %s\"\n % (error_prefix, conversion_func, base_type,\n dtype.name, ret.dtype.name))\n return ret\n raise TypeError(\"%sCannot convert %r with type %s to Tensor: \"\n \"no conversion function registered.\"\n % (error_prefix, value, type(value)))\n\n\ndef internal_convert_n_to_tensor(values,\n dtype=None,\n name=None,\n as_ref=False,\n preferred_dtype=None):\n \"\"\"Converts `values` to a list of `Tensor` objects.\n\n Args:\n values: A list of objects that can be consumed by `tf.convert_to_tensor()`.\n dtype: (Optional.) The required `DType` of the returned `Tensor` objects.\n name: (Optional.) A name prefix to used when a new `Tensor` is\n created, in which case element `i` will be given the name `name\n + '_' + i`.\n as_ref: True if the caller wants the results as ref tensors.\n preferred_dtype: Optional element type for the returned tensors,\n used when dtype is None. In some cases, a caller may not have a\n dtype in mind when converting to a tensor, so preferred_dtype\n can be used as a soft preference. If the conversion to\n `preferred_dtype` is not possible, this argument has no effect.\n\n Returns:\n A list of `Tensor` and/or `IndexedSlices` objects.\n\n Raises:\n TypeError: If no conversion function is registered for an element in\n `values`.\n RuntimeError: If a registered conversion function returns an invalid\n value.\n \"\"\"\n if not isinstance(values, collections.Sequence):\n raise TypeError(\"values must be a list.\")\n ret = []\n for i, value in enumerate(values):\n n = None if name is None else \"%s_%d\" % (name, i)\n ret.append(\n internal_convert_to_tensor(\n value,\n dtype=dtype,\n name=n,\n as_ref=as_ref,\n preferred_dtype=preferred_dtype))\n return ret\n\n\ndef convert_n_to_tensor(values,\n dtype=None,\n name=None,\n preferred_dtype=None):\n \"\"\"Converts `values` to a list of `Tensor` objects.\n\n Args:\n values: A list of objects that can be consumed by `tf.convert_to_tensor()`.\n dtype: (Optional.) The required `DType` of the returned `Tensor` objects.\n name: (Optional.) A name prefix to used when a new `Tensor` is\n created, in which case element `i` will be given the name `name\n + '_' + i`.\n preferred_dtype: Optional element type for the returned tensors,\n used when dtype is None. In some cases, a caller may not have a\n dtype in mind when converting to a tensor, so preferred_dtype\n can be used as a soft preference. If the conversion to\n `preferred_dtype` is not possible, this argument has no effect.\n\n Returns:\n A list of `Tensor` and/or `IndexedSlices` objects.\n\n Raises:\n TypeError: If no conversion function is registered for an element in\n `values`.\n RuntimeError: If a registered conversion function returns an invalid\n value.\n \"\"\"\n return internal_convert_n_to_tensor(values=values,\n dtype=dtype,\n name=name,\n preferred_dtype=preferred_dtype,\n as_ref=False)\n\n\ndef convert_to_tensor_or_indexed_slices(value, dtype=None, name=None):\n \"\"\"Converts the given object to a `Tensor` or an `IndexedSlices`.\n\n If `value` is an `IndexedSlices` or `SparseTensor` it is returned\n unmodified. Otherwise, it is converted to a `Tensor` using\n `convert_to_tensor()`.\n\n Args:\n value: An `IndexedSlices`, `SparseTensor`, or an object that can be consumed\n by `convert_to_tensor()`.\n dtype: (Optional.) The required `DType` of the returned `Tensor` or\n `IndexedSlices`.\n name: (Optional.) A name to use if a new `Tensor` is created.\n\n Returns:\n An `Tensor`, `IndexedSlices`, or `SparseTensor` based on `value`.\n\n Raises:\n ValueError: If `dtype` does not match the element type of `value`.\n \"\"\"\n return internal_convert_to_tensor_or_indexed_slices(\n value=value, dtype=dtype, name=name, as_ref=False)\n\n\ndef internal_convert_to_tensor_or_indexed_slices(value, dtype=None, name=None,\n as_ref=False):\n \"\"\"Converts the given object to an `Tensor` or an `IndexedSlices`.\n\n If `value` is an `IndexedSlices` or `SparseTensor` it is returned\n unmodified. Otherwise, it is converted to a `Tensor` using\n `convert_to_tensor()`.\n\n Args:\n value: An `IndexedSlices`, `SparseTensor`, or an object that can be consumed\n by `convert_to_tensor()`.\n dtype: (Optional.) The required `DType` of the returned `Tensor` or\n `IndexedSlices`.\n name: (Optional.) A name to use if a new `Tensor` is created.\n as_ref: True if the caller wants the results as ref tensors.\n\n Returns:\n An `Tensor`, `IndexedSlices`, or `SparseTensor` based on `value`.\n\n Raises:\n ValueError: If `dtype` does not match the element type of `value`.\n \"\"\"\n if isinstance(value, _TensorLike):\n if dtype and not dtypes.as_dtype(dtype).is_compatible_with(value.dtype):\n raise ValueError(\n \"Tensor conversion requested dtype %s for Tensor with dtype %s: %r\"\n % (dtypes.as_dtype(dtype).name, value.dtype.name, str(value)))\n return value\n else:\n return internal_convert_to_tensor(value,\n dtype=dtype,\n name=name,\n as_ref=as_ref)\n\n\ndef internal_convert_n_to_tensor_or_indexed_slices(values, dtype=None,\n name=None, as_ref=False):\n \"\"\"Converts `values` to a list of `Tensor` or `IndexedSlices` objects.\n\n Any `IndexedSlices` or `SparseTensor` objects in `values` are returned\n unmodified.\n\n Args:\n values: A list of `None`, `IndexedSlices`, `SparseTensor`, or objects that\n can be consumed by `convert_to_tensor()`.\n dtype: (Optional.) The required `DType` of the returned `Tensor`\n `IndexedSlices`.\n name: (Optional.) A name prefix to used when a new `Tensor` is\n created, in which case element `i` will be given the name `name\n + '_' + i`.\n as_ref: True if the caller wants the results as ref tensors.\n\n Returns:\n A list of `Tensor`, `IndexedSlices`, and/or `SparseTensor` objects.\n\n Raises:\n TypeError: If no conversion function is registered for an element in\n `values`.\n RuntimeError: If a registered conversion function returns an invalid\n value.\n \"\"\"\n if not isinstance(values, collections.Sequence):\n raise TypeError(\"values must be a list.\")\n ret = []\n for i, value in enumerate(values):\n if value is None:\n ret.append(value)\n else:\n n = None if name is None else \"%s_%d\" % (name, i)\n ret.append(\n internal_convert_to_tensor_or_indexed_slices(\n value, dtype=dtype, name=n, as_ref=as_ref))\n return ret\n\n\ndef convert_n_to_tensor_or_indexed_slices(values, dtype=None, name=None):\n \"\"\"Converts `values` to a list of `Output` or `IndexedSlices` objects.\n\n Any `IndexedSlices` or `SparseTensor` objects in `values` are returned\n unmodified.\n\n Args:\n values: A list of `None`, `IndexedSlices`, `SparseTensor`, or objects that\n can be consumed by `convert_to_tensor()`.\n dtype: (Optional.) The required `DType` of the returned `Tensor`\n `IndexedSlices`.\n name: (Optional.) A name prefix to used when a new `Tensor` is\n created, in which case element `i` will be given the name `name\n + '_' + i`.\n\n Returns:\n A list of `Tensor`, `IndexedSlices`, and/or `SparseTensor` objects.\n\n Raises:\n TypeError: If no conversion function is registered for an element in\n `values`.\n RuntimeError: If a registered conversion function returns an invalid\n value.\n \"\"\"\n return internal_convert_n_to_tensor_or_indexed_slices(\n values=values, dtype=dtype, name=name, as_ref=False)\n\n\ndef register_tensor_conversion_function(base_type, conversion_func,\n priority=100):\n \"\"\"Registers a function for converting objects of `base_type` to `Tensor`.\n\n The conversion function must have the following signature:\n\n ```python\n def conversion_func(value, dtype=None, name=None, as_ref=False):\n # ...\n ```\n\n It must return a `Tensor` with the given `dtype` if specified. If the\n conversion function creates a new `Tensor`, it should use the given\n `name` if specified. All exceptions will be propagated to the caller.\n\n The conversion function may return `NotImplemented` for some\n inputs. In this case, the conversion process will continue to try\n subsequent conversion functions.\n\n If `as_ref` is true, the function must return a `Tensor` reference,\n such as a `Variable`.\n\n NOTE: The conversion functions will execute in order of priority,\n followed by order of registration. To ensure that a conversion function\n `F` runs before another conversion function `G`, ensure that `F` is\n registered with a smaller priority than `G`.\n\n Args:\n base_type: The base type or tuple of base types for all objects that\n `conversion_func` accepts.\n conversion_func: A function that converts instances of `base_type` to\n `Tensor`.\n priority: Optional integer that indicates the priority for applying this\n conversion function. Conversion functions with smaller priority values\n run earlier than conversion functions with larger priority values.\n Defaults to 100.\n\n Raises:\n TypeError: If the arguments do not have the appropriate type.\n\n \"\"\"\n if not (isinstance(base_type, type) or\n (isinstance(base_type, tuple)\n and all(isinstance(x, type) for x in base_type))):\n raise TypeError(\"base_type must be a type or a tuple of types.\")\n if not callable(conversion_func):\n raise TypeError(\"conversion_func must be callable.\")\n\n try:\n funcs_at_priority = _tensor_conversion_func_registry[priority]\n except KeyError:\n funcs_at_priority = []\n _tensor_conversion_func_registry[priority] = funcs_at_priority\n funcs_at_priority.append((base_type, conversion_func))\n\n\nclass IndexedSlices(_TensorLike):\n \"\"\"A sparse representation of a set of tensor slices at given indices.\n\n This class is a simple wrapper for a pair of `Tensor` objects:\n\n * `values`: A `Tensor` of any dtype with shape `[D0, D1, ..., Dn]`.\n * `indices`: A 1-D integer `Tensor` with shape `[D0]`.\n\n An `IndexedSlices` is typically used to represent a subset of a larger\n tensor `dense` of shape `[LARGE0, D1, .. , DN]` where `LARGE0 >> D0`.\n The values in `indices` are the indices in the first dimension of\n the slices that have been extracted from the larger tensor.\n\n The dense tensor `dense` represented by an `IndexedSlices` `slices` has\n\n ```python\n dense[slices.indices[i], :, :, :, ...] = slices.values[i, :, :, :, ...]\n ```\n\n The `IndexedSlices` class is used principally in the definition of\n gradients for operations that have sparse gradients\n (e.g. [`tf.gather`](../../api_docs/python/array_ops.md#gather)).\n\n Contrast this representation with\n [`SparseTensor`](../../api_docs/python/sparse_ops.md#SparseTensor),\n which uses multi-dimensional indices and scalar values.\n\n @@__init__\n\n @@values\n @@indices\n @@dense_shape\n\n @@name\n @@dtype\n @@device\n @@op\n \"\"\"\n\n def __init__(self, values, indices, dense_shape=None):\n \"\"\"Creates an `IndexedSlices`.\"\"\"\n _get_graph_from_inputs([values, indices, dense_shape])\n self._values = values\n self._indices = indices\n self._dense_shape = dense_shape\n\n @property\n def values(self):\n \"\"\"A `Tensor` containing the values of the slices.\"\"\"\n return self._values\n\n @property\n def indices(self):\n \"\"\"A 1-D `Tensor` containing the indices of the slices.\"\"\"\n return self._indices\n\n @property\n def dense_shape(self):\n \"\"\"A 1-D `Tensor` containing the shape of the corresponding dense tensor.\"\"\"\n return self._dense_shape\n\n @property\n def name(self):\n \"\"\"The name of this `IndexedSlices`.\"\"\"\n return self.values.name\n\n @property\n def device(self):\n \"\"\"The name of the device on which `values` will be produced, or `None`.\"\"\"\n return self.values.device\n\n @property\n def op(self):\n \"\"\"The `Operation` that produces `values` as an output.\"\"\"\n return self.values.op\n\n @property\n def dtype(self):\n \"\"\"The `DType` of elements in this tensor.\"\"\"\n return self.values.dtype\n\n @property\n def graph(self):\n \"\"\"The `Graph` that contains the values, indices, and shape tensors.\"\"\"\n return self._values.graph\n\n def __str__(self):\n return \"IndexedSlices(indices=%s, values=%s%s)\" % (\n self._indices, self._values,\n (\", dense_shape=%s\" % self._dense_shape)\n if self._dense_shape is not None else \"\")\n\n def __neg__(self):\n return IndexedSlices(-self.values, self.indices, self.dense_shape)\n\n\nIndexedSlicesValue = collections.namedtuple(\n \"IndexedSlicesValue\", [\"values\", \"indices\", \"dense_shape\"])\n\n\ndef _device_string(dev_spec):\n if isinstance(dev_spec, pydev.DeviceSpec):\n return dev_spec.to_string()\n else:\n return dev_spec\n\n\ndef _NodeDef(op_type, name, device=None, attrs=None):\n \"\"\"Create a NodeDef proto.\n\n Args:\n op_type: Value for the \"op\" attribute of the NodeDef proto.\n name: Value for the \"name\" attribute of the NodeDef proto.\n device: string, device, or function from NodeDef to string.\n Value for the \"device\" attribute of the NodeDef proto.\n attrs: Optional dictionary where the key is the attribute name (a string)\n and the value is the respective \"attr\" attribute of the NodeDef proto (an\n AttrValue).\n\n Returns:\n A node_def_pb2.NodeDef protocol buffer.\n \"\"\"\n node_def = node_def_pb2.NodeDef()\n node_def.op = compat.as_bytes(op_type)\n node_def.name = compat.as_bytes(name)\n if attrs is not None:\n for k, v in six.iteritems(attrs):\n node_def.attr[k].CopyFrom(v)\n if device is not None:\n if callable(device):\n node_def.device = device(node_def)\n else:\n node_def.device = _device_string(device)\n return node_def\n\n\n# Copied from core/framework/node_def_util.cc\n# TODO(mrry,josh11b): Consolidate this validation in C++ code.\n_VALID_OP_NAME_REGEX = re.compile(\"^[A-Za-z0-9.][A-Za-z0-9_.\\\\-/]*$\")\n_VALID_SCOPE_NAME_REGEX = re.compile(\"^[A-Za-z0-9_.\\\\-/]*$\")\n\n\nclass Operation(object):\n \"\"\"Represents a graph node that performs computation on tensors.\n\n An `Operation` is a node in a TensorFlow `Graph` that takes zero or\n more `Tensor` objects as input, and produces zero or more `Tensor`\n objects as output. Objects of type `Operation` are created by\n calling a Python op constructor (such as\n [`tf.matmul()`](../../api_docs/python/math_ops.md#matmul))\n or [`Graph.create_op()`](../../api_docs/python/framework.md#Graph.create_op).\n\n For example `c = tf.matmul(a, b)` creates an `Operation` of type\n \"MatMul\" that takes tensors `a` and `b` as input, and produces `c`\n as output.\n\n After the graph has been launched in a session, an `Operation` can\n be executed by passing it to\n [`Session.run()`](../../api_docs/python/client.md#Session.run).\n `op.run()` is a shortcut for calling `tf.get_default_session().run(op)`.\n\n @@name\n @@type\n @@inputs\n @@control_inputs\n @@outputs\n @@device\n @@graph\n\n @@run\n\n @@get_attr\n @@traceback\n \"\"\"\n\n def __init__(self, node_def, g, inputs=None, output_types=None,\n control_inputs=None, input_types=None, original_op=None,\n op_def=None):\n r\"\"\"Creates an `Operation`.\n\n NOTE: This constructor validates the name of the `Operation` (passed\n as `node_def.name`). Valid `Operation` names match the following\n regular expression:\n\n [A-Za-z0-9.][A-Za-z0-9_.\\\\-/]*\n\n Args:\n node_def: `node_def_pb2.NodeDef`. `NodeDef` for the `Operation`.\n Used for attributes of `node_def_pb2.NodeDef`, typically `name`,\n `op`, and `device`. The `input` attribute is irrelevant here\n as it will be computed when generating the model.\n g: `Graph`. The parent graph.\n inputs: list of `Tensor` objects. The inputs to this `Operation`.\n output_types: list of `DType` objects. List of the types of the\n `Tensors` computed by this operation. The length of this list indicates\n the number of output endpoints of the `Operation`.\n control_inputs: list of operations or tensors from which to have a\n control dependency.\n input_types: List of `DType` objects representing the\n types of the tensors accepted by the `Operation`. By default\n uses `[x.dtype.base_dtype for x in inputs]`. Operations that expect\n reference-typed inputs must specify these explicitly.\n original_op: Optional. Used to associate the new `Operation` with an\n existing `Operation` (for example, a replica with the op that was\n replicated).\n op_def: Optional. The `op_def_pb2.OpDef` proto that describes the\n op type that this `Operation` represents.\n\n Raises:\n TypeError: if control inputs are not Operations or Tensors,\n or if `node_def` is not a `NodeDef`,\n or if `g` is not a `Graph`,\n or if `inputs` are not tensors,\n or if `inputs` and `input_types` are incompatible.\n ValueError: if the `node_def` name is not valid.\n \"\"\"\n if not isinstance(node_def, node_def_pb2.NodeDef):\n raise TypeError(\"node_def needs to be a NodeDef: %s\" % node_def)\n if node_def.ByteSize() >= (1 << 31) or node_def.ByteSize() < 0:\n raise ValueError(\n \"Cannot create a tensor proto whose content is larger than 2GB.\")\n if not _VALID_OP_NAME_REGEX.match(node_def.name):\n raise ValueError(\"'%s' is not a valid node name\" % node_def.name)\n if not isinstance(g, Graph):\n raise TypeError(\"g needs to be a Graph: %s\" % g)\n self._node_def = copy.deepcopy(node_def)\n self._graph = g\n if inputs is None:\n inputs = []\n elif not isinstance(inputs, list):\n raise TypeError(\"inputs needs to be a list of Tensors: %s\" % inputs)\n self._inputs = list(inputs) # Defensive copy.\n for a in self._inputs:\n if not isinstance(a, Tensor):\n raise TypeError(\"input needs to be a Tensor: %s\" % a)\n # Mark that we consume the inputs.\n a._add_consumer(self) # pylint: disable=protected-access\n if output_types is None:\n output_types = []\n self._output_types = output_types\n self._outputs = [Tensor(self, i, output_type)\n for i, output_type in enumerate(output_types)]\n if input_types is None:\n input_types = [i.dtype.base_dtype for i in self._inputs]\n else:\n if not all(x.is_compatible_with(i.dtype)\n for i, x in zip(self._inputs, input_types)):\n raise TypeError(\"Inputs are not compatible with input types\")\n self._input_types = input_types\n\n # Build the list of control inputs.\n self._control_inputs = []\n if control_inputs:\n for c in control_inputs:\n c_op = None\n if isinstance(c, Operation):\n c_op = c\n elif isinstance(c, (Tensor, IndexedSlices)):\n c_op = c.op\n else:\n raise TypeError(\"Control input must be an Operation, \"\n \"a Tensor, or IndexedSlices: %s\" % c)\n self._control_inputs.append(c_op)\n\n self._original_op = original_op\n self._op_def = op_def\n self._traceback = _extract_stack()\n # Add this op to the current control flow context:\n self._control_flow_context = g._get_control_flow_context()\n if self._control_flow_context is not None:\n self._control_flow_context.AddOp(self)\n # NOTE(keveman): Control flow context's AddOp could be creating new ops and\n # setting op.inputs[index] = new_op. Thus the new ops' id could be larger\n # than this op's id even though this op depend on them. Therefore, delaying\n # assigning id to this op until all ops this could be dependent on are\n # created.\n self._id_value = self._graph._next_id() # pylint: disable=protected-access\n self._recompute_node_def()\n\n def colocation_groups(self):\n \"\"\"Returns the list of colocation groups of the op.\"\"\"\n default_colocation_group = [compat.as_bytes(\"loc:@%s\" %\n self._node_def.name)]\n if \"_class\" not in self._node_def.attr:\n # This op has no explicit colocation group, so it is itself its\n # own root of a colocation group.\n return default_colocation_group\n\n attr_groups = [class_name\n for class_name in self.get_attr(\"_class\")\n if class_name.startswith(b\"loc:@\")]\n\n # If there are no colocation groups in the explicit _class field,\n # return the default colocation group.\n return attr_groups if attr_groups else default_colocation_group\n\n def values(self):\n \"\"\"DEPRECATED: Use outputs.\"\"\"\n return tuple(self.outputs)\n\n def _get_control_flow_context(self):\n \"\"\"Returns the control flow context of this op.\n\n Returns:\n A context object.\n \"\"\"\n return self._control_flow_context\n\n def _set_control_flow_context(self, context):\n \"\"\"Sets the current control flow context of this op.\n\n Args:\n context: a context object.\n \"\"\"\n self._control_flow_context = context\n\n @property\n def name(self):\n \"\"\"The full name of this operation.\"\"\"\n return self._node_def.name\n\n @property\n def _id(self):\n \"\"\"The unique integer id of this operation.\"\"\"\n return self._id_value\n\n @property\n def device(self):\n \"\"\"The name of the device to which this op has been assigned, if any.\n\n Returns:\n The string name of the device to which this op has been\n assigned, or an empty string if it has not been assigned to a\n device.\n \"\"\"\n return self._node_def.device\n\n def _set_device(self, device):\n \"\"\"Set the device of this operation.\n\n Args:\n device: string or device.. The device to set.\n \"\"\"\n self._node_def.device = _device_string(device)\n\n def _add_input(self, tensor, dtype=None):\n \"\"\"Add a new input to this operation.\n\n Args:\n tensor: the Tensor to add as an input.\n dtype: tf.DType: type of the input; defaults to\n the tensor's dtype.\n\n Raises:\n TypeError: if tensor is not a Tensor,\n or if input tensor type is not convertible to dtype.\n ValueError: if the Tensor is from a different graph.\n \"\"\"\n if not isinstance(tensor, Tensor):\n raise TypeError(\"tensor must be a Tensor: %s\" % tensor)\n _assert_same_graph(self, tensor)\n if dtype is None:\n dtype = tensor.dtype\n else:\n dtype = dtypes.as_dtype(dtype)\n if not dtype.is_compatible_with(tensor.dtype):\n raise TypeError(\n \"Cannot convert a tensor of type %s to an input of type %s\"\n % (tensor.dtype.name, dtype.name))\n self._inputs.append(tensor)\n self._input_types.append(dtype)\n tensor._add_consumer(self) # pylint: disable=protected-access\n self._recompute_node_def()\n\n def _update_input(self, index, tensor, dtype=None):\n \"\"\"Update the input to this operation at the given index.\n\n NOTE: This is for TF internal use only. Please don't use it.\n\n Args:\n index: the index of the input to update.\n tensor: the Tensor to be used as the input at the given index.\n dtype: tf.DType: type of the input; defaults to\n the tensor's dtype.\n\n Raises:\n TypeError: if tensor is not a Tensor,\n or if input tensor type is not convertible to dtype.\n ValueError: if the Tensor is from a different graph.\n \"\"\"\n if not isinstance(tensor, Tensor):\n raise TypeError(\"tensor must be a Tensor: %s\" % tensor)\n _assert_same_graph(self, tensor)\n if dtype is None:\n dtype = tensor.dtype\n else:\n dtype = dtypes.as_dtype(dtype)\n if not dtype.is_compatible_with(tensor.dtype):\n raise TypeError(\n \"Cannot convert a tensor of type %s to an input of type %s\"\n % (tensor.dtype.name, dtype.name))\n\n self._inputs[index].consumers().remove(self)\n self._inputs[index] = tensor\n self._input_types[index] = dtype\n tensor._add_consumer(self) # pylint: disable=protected-access\n self._recompute_node_def()\n\n def _add_control_inputs(self, ops):\n \"\"\"Add a list of new control inputs to this operation.\n\n Args:\n ops: the list of Operations to add as control input.\n\n Raises:\n TypeError: if ops is not a list of Operations.\n ValueError: if any op in ops is from a different graph.\n \"\"\"\n if ops:\n for op in ops:\n if not isinstance(op, Operation):\n raise TypeError(\"op must be an Operation: %s\" % op)\n _assert_same_graph(self, op)\n self._control_inputs.append(op)\n self._recompute_node_def()\n\n def _add_control_input(self, op):\n \"\"\"Add a new control input to this operation.\n\n Args:\n op: the Operation to add as control input.\n\n Raises:\n TypeError: if op is not an Operation.\n ValueError: if op is from a different graph.\n \"\"\"\n self._add_control_inputs([op])\n\n # Methods below are used when building the NodeDef and Graph proto.\n def _recompute_node_def(self):\n del self._node_def.input[:]\n self._node_def.input.extend([t._as_node_def_input() for t in self._inputs])\n if self._control_inputs:\n self._node_def.input.extend([\"^%s\" % op.name for op in\n self._control_inputs])\n\n def __str__(self):\n return str(self._node_def)\n\n def __repr__(self):\n return \"<tf.Operation '%s' type=%s>\" % (self.name, self.type)\n\n @property\n def outputs(self):\n \"\"\"The list of `Tensor` objects representing the outputs of this op.\"\"\"\n return self._outputs\n\n# pylint: disable=protected-access\n class _InputList(object):\n \"\"\"Immutable input list wrapper.\"\"\"\n\n def __init__(self, op):\n self._op = op\n\n def __iter__(self):\n return iter(self._op._inputs)\n\n def __len__(self):\n return len(self._op._inputs)\n\n def __bool__(self):\n return bool(self._op._inputs)\n\n # Python 3 wants __bool__, Python 2.7 wants __nonzero__\n __nonzero__ = __bool__\n\n def __getitem__(self, i):\n return self._op._inputs[i]\n# pylint: enable=protected-access\n\n @property\n def inputs(self):\n \"\"\"The list of `Tensor` objects representing the data inputs of this op.\"\"\"\n return Operation._InputList(self)\n\n @property\n def _input_dtypes(self):\n return self._input_types\n\n @property\n def control_inputs(self):\n \"\"\"The `Operation` objects on which this op has a control dependency.\n\n Before this op is executed, TensorFlow will ensure that the\n operations in `self.control_inputs` have finished executing. This\n mechanism can be used to run ops sequentially for performance\n reasons, or to ensure that the side effects of an op are observed\n in the correct order.\n\n Returns:\n A list of `Operation` objects.\n\n \"\"\"\n return self._control_inputs\n\n @property\n def type(self):\n \"\"\"The type of the op (e.g. `\"MatMul\"`).\"\"\"\n return self._node_def.op\n\n @property\n def graph(self):\n \"\"\"The `Graph` that contains this operation.\"\"\"\n return self._graph\n\n @property\n def node_def(self):\n \"\"\"Returns a serialized `NodeDef` representation of this operation.\n\n Returns:\n A\n [`NodeDef`](https://www.tensorflow.org/code/tensorflow/core/framework/node_def.proto)\n protocol buffer.\n \"\"\"\n return self._node_def\n\n @property\n def op_def(self):\n \"\"\"Returns the `OpDef` proto that represents the type of this op.\n\n Returns:\n An\n [`OpDef`](https://www.tensorflow.org/code/tensorflow/core/framework/op_def.proto)\n protocol buffer.\n \"\"\"\n return self._op_def\n\n @property\n def traceback(self):\n \"\"\"Returns the call stack from when this operation was constructed.\"\"\"\n return _convert_stack(self._traceback)\n\n def get_attr(self, name):\n \"\"\"Returns the value of the attr of this op with the given `name`.\n\n Args:\n name: The name of the attr to fetch.\n\n Returns:\n The value of the attr, as a Python object.\n\n Raises:\n ValueError: If this op does not have an attr with the given `name`.\n \"\"\"\n fields = [\"s\", \"i\", \"f\", \"b\", \"type\", \"shape\", \"tensor\"]\n if name not in self._node_def.attr:\n raise ValueError(\"No attr named '\" + name + \"' in \" +\n str(self._node_def))\n x = self._node_def.attr[name]\n # Treat an empty oneof value as an empty list.\n if not x.WhichOneof(\"value\"):\n return []\n if x.HasField(\"list\"):\n for f in fields:\n if getattr(x.list, f):\n return list(getattr(x.list, f))\n return []\n else:\n for f in fields:\n if x.HasField(f):\n return getattr(x, f)\n assert False, \"Unsupported field type in \" + str(x)\n\n def run(self, feed_dict=None, session=None):\n \"\"\"Runs this operation in a `Session`.\n\n Calling this method will execute all preceding operations that\n produce the inputs needed for this operation.\n\n *N.B.* Before invoking `Operation.run()`, its graph must have been\n launched in a session, and either a default session must be\n available, or `session` must be specified explicitly.\n\n Args:\n feed_dict: A dictionary that maps `Tensor` objects to feed values.\n See [`Session.run()`](../../api_docs/python/client.md#Session.run)\n for a description of the valid feed values.\n session: (Optional.) The `Session` to be used to run to this operation. If\n none, the default session will be used.\n \"\"\"\n _run_using_default_session(self, feed_dict, self.graph, session)\n\n\n_gradient_registry = registry.Registry(\"gradient\")\n\n\nclass RegisterGradient(object):\n \"\"\"A decorator for registering the gradient function for an op type.\n\n This decorator is only used when defining a new op type. For an op\n with `m` inputs and `n` outputs, the gradient function is a function\n that takes the original `Operation` and `n` `Tensor` objects\n (representing the gradients with respect to each output of the op),\n and returns `m` `Tensor` objects (representing the partial gradients\n with respect to each input of the op).\n\n For example, assuming that operations of type `\"Sub\"` take two\n inputs `x` and `y`, and return a single output `x - y`, the\n following gradient function would be registered:\n\n ```python\n @tf.RegisterGradient(\"Sub\")\n def _sub_grad(unused_op, grad):\n return grad, tf.negative(grad)\n ```\n\n The decorator argument `op_type` is the string type of an\n operation. This corresponds to the `OpDef.name` field for the proto\n that defines the operation.\n\n @@__init__\n \"\"\"\n\n def __init__(self, op_type):\n \"\"\"Creates a new decorator with `op_type` as the Operation type.\n\n Args:\n op_type: The string type of an operation. This corresponds to the\n `OpDef.name` field for the proto that defines the operation.\n \"\"\"\n if not isinstance(op_type, six.string_types):\n raise TypeError(\"op_type must be a string\")\n self._op_type = op_type\n\n def __call__(self, f):\n \"\"\"Registers the function `f` as gradient function for `op_type`.\"\"\"\n _gradient_registry.register(f, self._op_type)\n return f\n\n\ndef NotDifferentiable(op_type):\n \"\"\"Specifies that ops of type `op_type` is not differentiable.\n\n This function should *not* be used for operations that have a\n well-defined gradient that is not yet implemented.\n\n This function is only used when defining a new op type. It may be\n used for ops such as `tf.size()` that are not differentiable. For\n example:\n\n ```python\n tf.NotDifferentiable(\"Size\")\n ```\n\n The gradient computed for 'op_type' will then propagate zeros.\n\n For ops that have a well-defined gradient but are not yet implemented,\n no declaration should be made, and an error *must* be thrown if\n an attempt to request its gradient is made.\n\n Args:\n op_type: The string type of an operation. This corresponds to the\n `OpDef.name` field for the proto that defines the operation.\n\n Raises:\n TypeError: If `op_type` is not a string.\n\n \"\"\"\n if not isinstance(op_type, six.string_types):\n raise TypeError(\"op_type must be a string\")\n _gradient_registry.register(None, op_type)\n\n\n# Alias for the old name, will be eventually removed.\nNoGradient = NotDifferentiable\n\n\ndef get_gradient_function(op):\n \"\"\"Returns the function that computes gradients for \"op\".\"\"\"\n if not op.inputs: return None\n try:\n op_type = op.get_attr(\"_gradient_op_type\")\n except ValueError:\n op_type = op.type\n return _gradient_registry.lookup(op_type)\n\n\n_shape_registry = registry.Registry(\"shape functions\")\n_default_shape_function_registry = registry.Registry(\"default shape functions\")\n\n# These are set to common_shapes.call_cpp_shape_fn by op generated code\n# (generated by python_op_gen.cc).\n# It is set outside ops.py to avoid a circular dependency.\n_call_cpp_shape_fn = None\n_call_cpp_shape_fn_and_require_op = None\n\n\ndef _set_call_cpp_shape_fn(call_cpp_shape_fn):\n \"\"\"Sets default shape fns from passed common_shapes.call_cpp_shape_fn.\"\"\"\n global _call_cpp_shape_fn, _call_cpp_shape_fn_and_require_op\n if _call_cpp_shape_fn:\n return # already registered\n\n def call_without_requiring(op):\n return call_cpp_shape_fn(op, require_shape_fn=False)\n\n _call_cpp_shape_fn = call_without_requiring\n\n def call_with_requiring(op):\n return call_cpp_shape_fn(op, require_shape_fn=True)\n\n _call_cpp_shape_fn_and_require_op = call_with_requiring\n\n\nclass RegisterShape(object):\n \"\"\"No longer used. Was: A decorator for registering a shape function.\n\n Shape functions must now be registered via the SetShapeFn on the\n original Op specification in C++.\n\n \"\"\"\n\n def __init__(self, op_type):\n \"\"\"Saves the `op_type` as the `Operation` type.\"\"\"\n if not isinstance(op_type, six.string_types):\n raise TypeError(\"op_type must be a string\")\n self._op_type = op_type\n\n def __call__(self, f):\n \"\"\"Registers \"f\" as the shape function for \"op_type\".\"\"\"\n if f is None:\n assert _call_cpp_shape_fn\n\n # None is a special \"weak\" value that provides a default shape function,\n # and can be overridden by a non-None registration.\n try:\n _default_shape_function_registry.register(_call_cpp_shape_fn,\n self._op_type)\n except KeyError:\n # Ignore duplicate registrations of the weak value. This can\n # occur if the op library input to wrapper generation\n # inadvertently links in one or more of the standard op\n # libraries.\n pass\n else:\n _shape_registry.register(f, self._op_type)\n return f\n\n\ndef set_shapes_for_outputs(op):\n \"\"\"Uses the registered shape functions to set the shapes for op's outputs.\"\"\"\n try:\n shape_func = _shape_registry.lookup(op.type)\n except LookupError:\n try:\n shape_func = _default_shape_function_registry.lookup(op.type)\n except LookupError:\n shape_func = _call_cpp_shape_fn_and_require_op\n\n shapes = shape_func(op)\n if shapes is None:\n raise RuntimeError(\n \"Shape function for op %s did not return any shapes\" % op)\n elif isinstance(shapes, dict):\n # Returned by call_cpp_shape_fn\n shapes_dict = shapes\n shapes = shapes_dict[\"shapes\"]\n handle_shapes = shapes_dict[\"handle_shapes\"]\n handle_dtypes = shapes_dict[\"handle_dtypes\"]\n for output, handle_shape, handle_dtype in zip(op.outputs, handle_shapes, handle_dtypes):\n # pylint: disable=protected-access\n output._handle_shape = handle_shape\n output._handle_dtype = handle_dtype\n # pylint: enable=protected-access\n\n if len(op.outputs) != len(shapes):\n raise RuntimeError(\n \"Shape function for op %s returned %d shapes but expected %d %s %s\" %\n (op, len(shapes), len(op.outputs), shape_func.__name__, str(shapes)))\n for output, s in zip(op.outputs, shapes):\n output.set_shape(s)\n\n\nclass OpStats(object):\n \"\"\"A holder for statistics about an operator.\n\n This class holds information about the resource requirements for an op,\n including the size of its weight parameters on-disk and how many FLOPS it\n requires to execute forward inference.\n\n If you define a new operation, you can create a function that will return a\n set of information about its usage of the CPU and disk space when serialized.\n The function itself takes a Graph object that's been set up so you can call\n methods like get_tensor_by_name to help calculate the results, and a NodeDef\n argument.\n\n \"\"\"\n\n def __init__(self, statistic_type, value=None):\n \"\"\"Sets up the initial placeholders for the statistics.\"\"\"\n self.statistic_type = statistic_type\n self.value = value\n\n @property\n def statistic_type(self):\n return self._statistic_type\n\n @statistic_type.setter\n def statistic_type(self, statistic_type):\n self._statistic_type = statistic_type\n\n @property\n def value(self):\n return self._value\n\n @value.setter\n def value(self, value):\n self._value = value\n\n def __iadd__(self, other):\n if other.statistic_type != self.statistic_type:\n raise ValueError(\"Can't add an OpStat of type %s to one of %s.\",\n self.statistic_type, other.statistic_type)\n if self.value is None:\n self.value = other.value\n elif other.value is not None:\n self._value += other.value\n return self\n\n_stats_registry = registry.Registry(\"statistical functions\")\n\n\nclass RegisterStatistics(object):\n \"\"\"A decorator for registering the statistics function for an op type.\n\n This decorator can be defined for an op type so that it gives a\n report on the resources used by an instance of an operator, in the\n form of an OpStats object.\n\n Well-known types of statistics include these so far:\n\n - flops: When running a graph, the bulk of the computation happens doing\n numerical calculations like matrix multiplications. This type allows a node\n to return how many floating-point operations it takes to complete. The\n total number of FLOPs for a graph is a good guide to its expected latency.\n\n You can add your own statistics just by picking a new type string, registering\n functions for the ops you care about, and then calling get_stats_for_node_def.\n\n If a statistic for an op is registered multiple times, a KeyError will be\n raised.\n\n Since the statistics is counted on a per-op basis. It is not suitable for\n model parameters (capacity), which is expected to be counted only once, even\n if it is shared by multiple ops. (e.g. RNN)\n\n For example, you can define a new metric called doohickey for a Foo operation\n by placing this in your code:\n\n ```python\n @ops.RegisterStatistics(\"Foo\", \"doohickey\")\n def _calc_foo_bojangles(unused_graph, unused_node_def):\n return ops.OpStats(\"doohickey\", 20)\n ```\n\n Then in client code you can retrieve the value by making this call:\n\n ```python\n doohickey = ops.get_stats_for_node_def(graph, node_def, \"doohickey\")\n ```\n\n If the NodeDef is for an op with a registered doohickey function, you'll get\n back the calculated amount in doohickey.value, or None if it's not defined.\n\n \"\"\"\n\n def __init__(self, op_type, statistic_type):\n \"\"\"Saves the `op_type` as the `Operation` type.\"\"\"\n if not isinstance(op_type, six.string_types):\n raise TypeError(\"op_type must be a string.\")\n if \",\" in op_type:\n raise TypeError(\"op_type must not contain a comma.\")\n self._op_type = op_type\n if not isinstance(statistic_type, six.string_types):\n raise TypeError(\"statistic_type must be a string.\")\n if \",\" in statistic_type:\n raise TypeError(\"statistic_type must not contain a comma.\")\n self._statistic_type = statistic_type\n\n def __call__(self, f):\n \"\"\"Registers \"f\" as the statistics function for \"op_type\".\"\"\"\n _stats_registry.register(f, self._op_type + \",\" + self._statistic_type)\n return f\n\n\ndef get_stats_for_node_def(graph, node, statistic_type):\n \"\"\"Looks up the node's statistics function in the registry and calls it.\n\n This function takes a Graph object and a NodeDef from a GraphDef, and if\n there's an associated statistics method, calls it and returns a result. If no\n function has been registered for the particular node type, it returns an empty\n statistics object.\n\n Args:\n graph: A Graph object that's been set up with the node's graph.\n node: A NodeDef describing the operator.\n statistic_type: A string identifying the statistic we're interested in.\n Returns:\n An OpStats object containing information about resource usage.\n \"\"\"\n\n try:\n stats_func = _stats_registry.lookup(node.op + \",\" + statistic_type)\n result = stats_func(graph, node)\n except LookupError:\n result = OpStats(statistic_type)\n return result\n\n\ndef _name_from_scope_name(name):\n \"\"\"Returns the name of an op given the name of its scope.\n\n Args:\n name: the name of the scope.\n\n Returns:\n the name of the op (equal to scope name minus any trailing slash).\n \"\"\"\n return name[:-1] if name[-1] == \"/\" else name\n\n\nclass Graph(object):\n \"\"\"A TensorFlow computation, represented as a dataflow graph.\n\n A `Graph` contains a set of\n [`Operation`](../../api_docs/python/framework.md#Operation) objects,\n which represent units of computation; and\n [`Tensor`](../../api_docs/python/framework.md#Tensor) objects, which represent\n the units of data that flow between operations.\n\n A default `Graph` is always registered, and accessible by calling\n [`tf.get_default_graph()`](../../api_docs/python/framework.md#get_default_graph).\n To add an operation to the default graph, simply call one of the functions\n that defines a new `Operation`:\n\n ```python\n c = tf.constant(4.0)\n assert c.graph is tf.get_default_graph()\n ```\n\n Another typical usage involves the\n [`Graph.as_default()`](../../api_docs/python/framework.md#Graph.as_default)\n context manager, which overrides the current default graph for the\n lifetime of the context:\n\n ```python\n g = tf.Graph()\n with g.as_default():\n # Define operations and tensors in `g`.\n c = tf.constant(30.0)\n assert c.graph is g\n ```\n\n Important note: This class *is not* thread-safe for graph construction. All\n operations should be created from a single thread, or external\n synchronization must be provided. Unless otherwise specified, all methods\n are not thread-safe.\n\n @@__init__\n @@as_default\n @@as_graph_def\n @@finalize\n @@finalized\n\n @@control_dependencies\n @@device\n @@name_scope\n\n A `Graph` instance supports an arbitrary number of \"collections\"\n that are identified by name. For convenience when building a large\n graph, collections can store groups of related objects: for\n example, the `tf.Variable` uses a collection (named\n [`tf.GraphKeys.GLOBAL_VARIABLES`](../../api_docs/python/framework.md#GraphKeys)) for\n all variables that are created during the construction of a graph. The caller\n may define additional collections by specifying a new name.\n\n @@add_to_collection\n @@add_to_collections\n @@get_collection\n @@get_collection_ref\n\n @@as_graph_element\n @@get_operation_by_name\n @@get_tensor_by_name\n @@get_operations\n\n @@seed\n @@unique_name\n @@version\n @@graph_def_versions\n\n @@create_op\n @@gradient_override_map\n \"\"\"\n\n def __init__(self):\n \"\"\"Creates a new, empty Graph.\"\"\"\n # Protects the core state that may be accessed by multiple readers.\n # Only state that can be returned via public accessors (`as_graph_def()`,\n # `get_operations()`, `as_graph_element()`, `get_collection()`, and\n # `get_collection_ref()`) is by the lock. Thread-safety is provided on a\n # best-effort basis to support buggy programs, and is not guaranteed by the\n # public `tf.Graph` API.\n # NOTE(mrry): This does not protect the various stacks. A warning will\n # be reported if these are used from multiple threads\n self._lock = threading.Lock()\n self._nodes_by_id = dict() # GUARDED_BY(self._lock)\n self._next_id_counter = 0 # GUARDED_BY(self._lock)\n self._nodes_by_name = dict() # GUARDED_BY(self._lock)\n self._version = 0 # GUARDED_BY(self._lock)\n # Current name stack: uniquified names\n self._name_stack = \"\"\n # Maps a name used in the graph to the next id to use for that name.\n self._names_in_use = {}\n # Functions that will be applied to choose a device if none is specified.\n self._device_function_stack = []\n # Default original_op applied to new ops.\n self._default_original_op = None\n # Current control flow context. It could be either CondContext or\n # WhileContext defined in ops/control_flow_ops.py\n self._control_flow_context = None\n # A new node will depend of the union of all of the nodes in the stack.\n self._control_dependencies_stack = []\n # Arbritrary collections of objects.\n self._collections = {}\n # The graph-level random seed\n self._seed = None\n # A dictionary of attributes that should be applied to all ops.\n self._attr_scope_map = {}\n # A map from op type to the kernel label that should be used.\n self._op_to_kernel_label_map = {}\n # A map from op type to an alternative op type that should be used when\n # computing gradients.\n self._gradient_override_map = {}\n # True if the graph is considered \"finalized\". In that case no\n # new operations can be added.\n self._finalized = False\n # Functions defined in the graph\n self._functions = collections.OrderedDict()\n # Default GraphDef versions\n self._graph_def_versions = versions_pb2.VersionDef(\n producer=versions.GRAPH_DEF_VERSION,\n min_consumer=versions.GRAPH_DEF_VERSION_MIN_CONSUMER)\n self._building_function = False\n # Stack of colocate_with ops\n self._colocation_stack = []\n # Set of tensors that are dangerous to feed!\n self._unfeedable_tensors = set()\n # Set of operations that are dangerous to fetch!\n self._unfetchable_ops = set()\n # A map of tensor handle placeholder to tensor dtype.\n self._handle_feeders = {}\n # A map from tensor handle to its read op.\n self._handle_readers = {}\n # A map from tensor handle to its move op.\n self._handle_movers = {}\n # A map from tensor handle to its delete op.\n self._handle_deleters = {}\n # Resource container.\n self._container = \"\"\n self._registered_ops = op_def_registry.get_registered_ops()\n\n def _check_not_finalized(self):\n \"\"\"Check if the graph is finalized.\n\n Raises:\n RuntimeError: If the graph finalized.\n \"\"\"\n if self._finalized:\n raise RuntimeError(\"Graph is finalized and cannot be modified.\")\n\n def _add_op(self, op):\n \"\"\"Adds 'op' to the graph.\n\n Args:\n op: the Operator or Tensor to add.\n\n Raises:\n TypeError: if op is not an Operation or Tensor.\n ValueError: if the op.name or op._id are already used.\n \"\"\"\n self._check_not_finalized()\n if not isinstance(op, (Tensor, Operation)):\n raise TypeError(\"op must be a Tensor or Operation: %s\" % op)\n with self._lock:\n # pylint: disable=protected-access\n if op._id in self._nodes_by_id:\n raise ValueError(\"cannot add an op with id %d as it already \"\n \"exists in the graph\" % op._id)\n if op.name in self._nodes_by_name:\n raise ValueError(\"cannot add op with name %s as that name \"\n \"is already used\" % op.name)\n self._nodes_by_id[op._id] = op\n self._nodes_by_name[op.name] = op\n self._version = max(self._version, op._id)\n # pylint: enable=protected-access\n\n @property\n def version(self):\n \"\"\"Returns a version number that increases as ops are added to the graph.\n\n Note that this is unrelated to the\n [GraphDef version](#Graph.graph_def_version).\n \"\"\"\n if self._finalized:\n return self._version\n\n with self._lock:\n return self._version\n\n @property\n def graph_def_versions(self):\n \"\"\"The GraphDef version information of this graph.\n\n For details on the meaning of each version, see\n [`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto).\n\n Returns:\n A `VersionDef`.\n \"\"\"\n return self._graph_def_versions\n\n @property\n def seed(self):\n \"\"\"The graph-level random seed of this graph.\"\"\"\n return self._seed\n\n @seed.setter\n def seed(self, seed):\n self._seed = seed\n\n @property\n def finalized(self):\n \"\"\"True if this graph has been finalized.\"\"\"\n return self._finalized\n\n def finalize(self):\n \"\"\"Finalizes this graph, making it read-only.\n\n After calling `g.finalize()`, no new operations can be added to\n `g`. This method is used to ensure that no operations are added\n to a graph when it is shared between multiple threads, for example\n when using a [`QueueRunner`](../../api_docs/python/train.md#QueueRunner).\n \"\"\"\n self._finalized = True\n\n def _unsafe_unfinalize(self):\n \"\"\"Opposite of `finalize`. Internal interface.\n\n NOTE: Unfinalizing a graph could have negative impact on performance,\n especially in a multi-threaded environment. Unfinalizing a graph\n when it is in use by a Session may lead to undefined behavior. Ensure\n that all sessions using a graph are closed before calling this method.\n \"\"\"\n self._finalized = False\n\n def _get_control_flow_context(self):\n \"\"\"Returns the current control flow context.\n\n Returns:\n A context object.\n \"\"\"\n return self._control_flow_context\n\n def _set_control_flow_context(self, context):\n \"\"\"Sets the current control flow context.\n\n Args:\n context: a context object.\n \"\"\"\n self._control_flow_context = context\n\n def _as_graph_def(self, from_version=None, add_shapes=False):\n \"\"\"Returns a serialized `GraphDef` representation of this graph.\n\n The serialized `GraphDef` can be imported into another `Graph`\n (using [`import_graph_def()`](#import_graph_def)) or used with the\n [C++ Session API](../../api_docs/cc/index.md).\n\n This method is thread-safe.\n\n Args:\n from_version: Optional. If this is set, returns a `GraphDef`\n containing only the nodes that were added to this graph since\n its `version` property had the given value.\n add_shapes: If true, adds an \"_output_shapes\" list attr to each\n node with the inferred shapes of each of its outputs.\n\n Returns:\n A tuple containing a\n [`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto)\n protocol buffer, and the version of the graph to which that\n `GraphDef` corresponds.\n\n Raises:\n ValueError: If the `graph_def` would be too large.\n\n \"\"\"\n with self._lock:\n graph = graph_pb2.GraphDef()\n graph.versions.CopyFrom(self._graph_def_versions)\n bytesize = 0\n for op_id in sorted(self._nodes_by_id):\n op = self._nodes_by_id[op_id]\n if from_version is None or op_id > from_version:\n graph.node.extend([op.node_def])\n if op.outputs and add_shapes:\n assert \"_output_shapes\" not in graph.node[-1].attr\n graph.node[-1].attr[\"_output_shapes\"].list.shape.extend([\n output.get_shape().as_proto() for output in op.outputs])\n bytesize += op.node_def.ByteSize()\n if bytesize >= (1 << 31) or bytesize < 0:\n raise ValueError(\"GraphDef cannot be larger than 2GB.\")\n if self._functions:\n for f in self._functions.values():\n bytesize += f.definition.ByteSize()\n if bytesize >= (1 << 31) or bytesize < 0:\n raise ValueError(\"GraphDef cannot be larger than 2GB.\")\n graph.library.function.extend([f.definition])\n if f.grad_func_name:\n grad_def = function_pb2.GradientDef()\n grad_def.function_name = f.name\n grad_def.gradient_func = f.grad_func_name\n graph.library.gradient.extend([grad_def])\n return graph, self._version\n\n def as_graph_def(self, from_version=None, add_shapes=False):\n \"\"\"Returns a serialized `GraphDef` representation of this graph.\n\n The serialized `GraphDef` can be imported into another `Graph`\n (using [`import_graph_def()`](#import_graph_def)) or used with the\n [C++ Session API](../../api_docs/cc/index.md).\n\n This method is thread-safe.\n\n Args:\n from_version: Optional. If this is set, returns a `GraphDef`\n containing only the nodes that were added to this graph since\n its `version` property had the given value.\n add_shapes: If true, adds an \"_output_shapes\" list attr to each\n node with the inferred shapes of each of its outputs.\n\n Returns:\n A [`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto)\n protocol buffer.\n\n Raises:\n ValueError: If the `graph_def` would be too large.\n \"\"\"\n result, _ = self._as_graph_def(from_version, add_shapes)\n return result\n\n def _is_function(self, name):\n \"\"\"Tests whether 'name' is registered in this graph's function library.\n\n Args:\n name: string op name.\n Returns:\n bool indicating whether or not 'name' is registered in function library.\n \"\"\"\n return name in self._functions\n\n def _get_function(self, name):\n \"\"\"Returns the function definition for 'name'.\n\n Args:\n name: string function name.\n Returns:\n The function def proto.\n \"\"\"\n return self._functions.get(name, None)\n\n def _add_function(self, function):\n \"\"\"Adds a function to the graph.\n\n After the function has been added, you can call to the function by\n passing the function name in place of an op name to\n `Graph.create_op()`.\n\n Args:\n function: A `_DefinedFunction` object.\n\n\n Raises:\n ValueError: if another function is defined with the same name.\n \"\"\"\n name = function.name\n previous = self._functions.get(name, None)\n if previous:\n raise ValueError(\"Another function is already defined with that name\")\n # Sanity checks on gradient definition.\n if (function.grad_func_name is not None) and (\n function.python_grad_func is not None):\n raise ValueError(\"Gradient defined twice for function %s\" % name)\n # Need a new-enough consumer to support the functions we add to the graph.\n if self._graph_def_versions.min_consumer < 12:\n self._graph_def_versions.min_consumer = 12\n self._functions[name] = function\n\n @property\n def building_function(self):\n \"\"\"Returns True iff this graph represents a function.\"\"\"\n return self._building_function\n\n # Helper functions to create operations.\n def create_op(self, op_type, inputs, dtypes,\n input_types=None, name=None, attrs=None, op_def=None,\n compute_shapes=True, compute_device=True):\n \"\"\"Creates an `Operation` in this graph.\n\n This is a low-level interface for creating an `Operation`. Most\n programs will not call this method directly, and instead use the\n Python op constructors, such as `tf.constant()`, which add ops to\n the default graph.\n\n Args:\n op_type: The `Operation` type to create. This corresponds to the\n `OpDef.name` field for the proto that defines the operation.\n inputs: A list of `Tensor` objects that will be inputs to the `Operation`.\n dtypes: A list of `DType` objects that will be the types of the tensors\n that the operation produces.\n input_types: (Optional.) A list of `DType`s that will be the types of\n the tensors that the operation consumes. By default, uses the base\n `DType` of each input in `inputs`. Operations that expect\n reference-typed inputs must specify `input_types` explicitly.\n name: (Optional.) A string name for the operation. If not specified, a\n name is generated based on `op_type`.\n attrs: (Optional.) A dictionary where the key is the attribute name (a\n string) and the value is the respective `attr` attribute of the\n `NodeDef` proto that will represent the operation (an `AttrValue`\n proto).\n op_def: (Optional.) The `OpDef` proto that describes the `op_type` that\n the operation will have.\n compute_shapes: (Optional.) If True, shape inference will be performed\n to compute the shapes of the outputs.\n compute_device: (Optional.) If True, device functions will be executed\n to compute the device property of the Operation.\n\n Raises:\n TypeError: if any of the inputs is not a `Tensor`.\n ValueError: if colocation conflicts with existing device assignment.\n\n Returns:\n An `Operation` object.\n\n \"\"\"\n self._check_not_finalized()\n for idx, a in enumerate(inputs):\n if not isinstance(a, Tensor):\n raise TypeError(\"Input #%d is not a tensor: %s\" % (idx, a))\n if name is None:\n name = op_type\n # If a names ends with a '/' it is a \"name scope\" and we use it as-is,\n # after removing the trailing '/'.\n if name and name[-1] == \"/\":\n name = _name_from_scope_name(name)\n else:\n name = self.unique_name(name)\n\n node_def = _NodeDef(op_type, name, device=None, attrs=attrs)\n\n # Apply any additional attributes requested. Do not overwrite any existing\n # attributes.\n for key, value in self._attr_scope_map.items():\n if key not in node_def.attr:\n if callable(value):\n value = value(node_def)\n if not isinstance(value, (type(None), attr_value_pb2.AttrValue)):\n raise TypeError(\n \"Callable for scope map key '%s' must return either None or \"\n \"an AttrValue protocol buffer; but it returned: %s\" %\n (key, value))\n node_def.attr[key].CopyFrom(value)\n\n # Apply a kernel label if one has been specified for this op_type.\n try:\n kernel_label = self._op_to_kernel_label_map[op_type]\n node_def.attr[\"_kernel\"].CopyFrom(\n attr_value_pb2.AttrValue(s=compat.as_bytes(kernel_label)))\n except KeyError:\n pass\n\n # Apply the overriding op_type for gradients if one has been\n # specified for this op_type.\n try:\n mapped_op_type = self._gradient_override_map[op_type]\n node_def.attr[\"_gradient_op_type\"].CopyFrom(\n attr_value_pb2.AttrValue(s=compat.as_bytes(mapped_op_type)))\n except KeyError:\n pass\n\n control_inputs = self._control_dependencies_for_inputs(inputs)\n ret = Operation(node_def, self, inputs=inputs, output_types=dtypes,\n control_inputs=control_inputs, input_types=input_types,\n original_op=self._default_original_op, op_def=op_def)\n if compute_shapes:\n set_shapes_for_outputs(ret)\n self._add_op(ret)\n self._record_op_seen_by_control_dependencies(ret)\n\n if compute_device:\n self._apply_device_functions(ret)\n\n if self._colocation_stack:\n all_colocation_groups = []\n for colocation_op in self._colocation_stack:\n all_colocation_groups.extend(colocation_op.colocation_groups())\n if colocation_op.device:\n # Make this device match the device of the colocated op, to\n # provide consistency between the device and the colocation\n # property.\n if ret.device and ret.device != colocation_op.device:\n logging.warning(\"Tried to colocate %s with an op %s that had \"\n \"a different device: %s vs %s. \"\n \"Ignoring colocation property.\",\n name, colocation_op.name,\n ret.device, colocation_op.device)\n else:\n ret._set_device(colocation_op.device)\n\n all_colocation_groups = sorted(set(all_colocation_groups))\n ret.node_def.attr[\"_class\"].CopyFrom(attr_value_pb2.AttrValue(\n list=attr_value_pb2.AttrValue.ListValue(s=all_colocation_groups)))\n\n # Sets \"container\" attribute if\n # (1) self._container is not None\n # (2) \"is_stateful\" is set in OpDef\n # (3) \"container\" attribute is in OpDef\n # (4) \"container\" attribute is None\n if (self._container and\n op_type in self._registered_ops and\n self._registered_ops[op_type].is_stateful and\n \"container\" in ret.node_def.attr and\n not ret.node_def.attr[\"container\"].s):\n ret.node_def.attr[\"container\"].CopyFrom(\n attr_value_pb2.AttrValue(s=compat.as_bytes(self._container)))\n\n return ret\n\n def as_graph_element(self, obj, allow_tensor=True, allow_operation=True):\n \"\"\"Returns the object referred to by `obj`, as an `Operation` or `Tensor`.\n\n This function validates that `obj` represents an element of this\n graph, and gives an informative error message if it is not.\n\n This function is the canonical way to get/validate an object of\n one of the allowed types from an external argument reference in the\n Session API.\n\n This method may be called concurrently from multiple threads.\n\n Args:\n obj: A `Tensor`, an `Operation`, or the name of a tensor or operation.\n Can also be any object with an `_as_graph_element()` method that returns\n a value of one of these types.\n allow_tensor: If true, `obj` may refer to a `Tensor`.\n allow_operation: If true, `obj` may refer to an `Operation`.\n\n Returns:\n The `Tensor` or `Operation` in the Graph corresponding to `obj`.\n\n Raises:\n TypeError: If `obj` is not a type we support attempting to convert\n to types.\n ValueError: If `obj` is of an appropriate type but invalid. For\n example, an invalid string.\n KeyError: If `obj` is not an object in the graph.\n \"\"\"\n if self._finalized:\n return self._as_graph_element_locked(obj, allow_tensor, allow_operation)\n\n with self._lock:\n return self._as_graph_element_locked(obj, allow_tensor, allow_operation)\n\n def _as_graph_element_locked(self, obj, allow_tensor, allow_operation):\n \"\"\"See `Graph.as_graph_element()` for details.\"\"\"\n # The vast majority of this function is figuring\n # out what an API user might be doing wrong, so\n # that we can give helpful error messages.\n #\n # Ideally, it would be nice to split it up, but we\n # need context to generate nice error messages.\n\n if allow_tensor and allow_operation:\n types_str = \"Tensor or Operation\"\n elif allow_tensor:\n types_str = \"Tensor\"\n elif allow_operation:\n types_str = \"Operation\"\n else:\n raise ValueError(\"allow_tensor and allow_operation can't both be False.\")\n\n temp_obj = _as_graph_element(obj)\n if temp_obj is not None:\n obj = temp_obj\n\n # If obj appears to be a name...\n if isinstance(obj, compat.bytes_or_text_types):\n name = compat.as_str(obj)\n\n if \":\" in name and allow_tensor:\n # Looks like a Tensor name and can be a Tensor.\n try:\n op_name, out_n = name.split(\":\")\n out_n = int(out_n)\n except:\n raise ValueError(\"The name %s looks a like a Tensor name, but is \"\n \"not a valid one. Tensor names must be of the \"\n \"form \\\"<op_name>:<output_index>\\\".\" % repr(name))\n if op_name in self._nodes_by_name:\n op = self._nodes_by_name[op_name]\n else:\n raise KeyError(\"The name %s refers to a Tensor which does not \"\n \"exist. The operation, %s, does not exist in the \"\n \"graph.\" % (repr(name), repr(op_name)))\n try:\n return op.outputs[out_n]\n except:\n raise KeyError(\"The name %s refers to a Tensor which does not \"\n \"exist. The operation, %s, exists but only has \"\n \"%s outputs.\"\n % (repr(name), repr(op_name), len(op.outputs)))\n\n elif \":\" in name and not allow_tensor:\n # Looks like a Tensor name but can't be a Tensor.\n raise ValueError(\"Name %s appears to refer to a Tensor, not a %s.\"\n % (repr(name), types_str))\n\n elif \":\" not in name and allow_operation:\n # Looks like an Operation name and can be an Operation.\n if name not in self._nodes_by_name:\n raise KeyError(\"The name %s refers to an Operation not in the \"\n \"graph.\" % repr(name))\n return self._nodes_by_name[name]\n\n elif \":\" not in name and not allow_operation:\n # Looks like an Operation name but can't be an Operation.\n if name in self._nodes_by_name:\n # Yep, it's an Operation name\n err_msg = (\"The name %s refers to an Operation, not a %s.\"\n % (repr(name), types_str))\n else:\n err_msg = (\"The name %s looks like an (invalid) Operation name, \"\n \"not a %s.\" % (repr(name), types_str))\n err_msg += (\" Tensor names must be of the form \"\n \"\\\"<op_name>:<output_index>\\\".\")\n raise ValueError(err_msg)\n\n elif isinstance(obj, Tensor) and allow_tensor:\n # Actually obj is just the object it's referring to.\n if obj.graph is not self:\n raise ValueError(\"Tensor %s is not an element of this graph.\" % obj)\n return obj\n elif isinstance(obj, Operation) and allow_operation:\n # Actually obj is just the object it's referring to.\n if obj.graph is not self:\n raise ValueError(\"Operation %s is not an element of this graph.\" % obj)\n return obj\n else:\n # We give up!\n raise TypeError(\"Can not convert a %s into a %s.\"\n % (type(obj).__name__, types_str))\n\n def get_operations(self):\n \"\"\"Return the list of operations in the graph.\n\n You can modify the operations in place, but modifications\n to the list such as inserts/delete have no effect on the\n list of operations known to the graph.\n\n This method may be called concurrently from multiple threads.\n\n Returns:\n A list of Operations.\n \"\"\"\n if self._finalized:\n return list(self._nodes_by_id.values())\n\n with self._lock:\n return list(self._nodes_by_id.values())\n\n def get_operation_by_name(self, name):\n \"\"\"Returns the `Operation` with the given `name`.\n\n This method may be called concurrently from multiple threads.\n\n Args:\n name: The name of the `Operation` to return.\n\n Returns:\n The `Operation` with the given `name`.\n\n Raises:\n TypeError: If `name` is not a string.\n KeyError: If `name` does not correspond to an operation in this graph.\n \"\"\"\n\n if not isinstance(name, six.string_types):\n raise TypeError(\"Operation names are strings (or similar), not %s.\"\n % type(name).__name__)\n return self.as_graph_element(name, allow_tensor=False, allow_operation=True)\n\n def get_tensor_by_name(self, name):\n \"\"\"Returns the `Tensor` with the given `name`.\n\n This method may be called concurrently from multiple threads.\n\n Args:\n name: The name of the `Tensor` to return.\n\n Returns:\n The `Tensor` with the given `name`.\n\n Raises:\n TypeError: If `name` is not a string.\n KeyError: If `name` does not correspond to a tensor in this graph.\n \"\"\"\n # Names should be strings.\n if not isinstance(name, six.string_types):\n raise TypeError(\"Tensor names are strings (or similar), not %s.\"\n % type(name).__name__)\n return self.as_graph_element(name, allow_tensor=True, allow_operation=False)\n\n def _next_id(self):\n \"\"\"Id for next Operation instance. Also increments the internal id.\"\"\"\n self._check_not_finalized()\n with self._lock:\n self._next_id_counter += 1\n return self._next_id_counter\n\n @property\n def _last_id(self):\n return self._next_id_counter\n\n def as_default(self):\n \"\"\"Returns a context manager that makes this `Graph` the default graph.\n\n This method should be used if you want to create multiple graphs\n in the same process. For convenience, a global default graph is\n provided, and all ops will be added to this graph if you do not\n create a new graph explicitly. Use this method with the `with` keyword\n to specify that ops created within the scope of a block should be\n added to this graph.\n\n The default graph is a property of the current thread. If you\n create a new thread, and wish to use the default graph in that\n thread, you must explicitly add a `with g.as_default():` in that\n thread's function.\n\n The following code examples are equivalent:\n\n ```python\n # 1. Using Graph.as_default():\n g = tf.Graph()\n with g.as_default():\n c = tf.constant(5.0)\n assert c.graph is g\n\n # 2. Constructing and making default:\n with tf.Graph().as_default() as g:\n c = tf.constant(5.0)\n assert c.graph is g\n ```\n\n Returns:\n A context manager for using this graph as the default graph.\n \"\"\"\n return _default_graph_stack.get_controller(self)\n\n def add_to_collection(self, name, value):\n \"\"\"Stores `value` in the collection with the given `name`.\n\n Note that collections are not sets, so it is possible to add a value to\n a collection several times.\n\n Args:\n name: The key for the collection. The `GraphKeys` class\n contains many standard names for collections.\n value: The value to add to the collection.\n \"\"\"\n self._check_not_finalized()\n with self._lock:\n if name not in self._collections:\n self._collections[name] = [value]\n else:\n self._collections[name].append(value)\n\n def add_to_collections(self, names, value):\n \"\"\"Stores `value` in the collections given by `names`.\n\n Note that collections are not sets, so it is possible to add a value to\n a collection several times. This function makes sure that duplicates in\n `names` are ignored, but it will not check for pre-existing membership of\n `value` in any of the collections in `names`.\n\n `names` can be any iterable, but if `names` is a string, it is treated as a\n single collection name.\n\n Args:\n names: The keys for the collections to add to. The `GraphKeys` class\n contains many standard names for collections.\n value: The value to add to the collections.\n \"\"\"\n # Make sure names are unique, but treat strings as a single collection name\n names = (names,) if isinstance(names, six.string_types) else set(names)\n for name in names:\n self.add_to_collection(name, value)\n\n def get_collection_ref(self, name):\n \"\"\"Returns a list of values in the collection with the given `name`.\n\n If the collection exists, this returns the list itself, which can\n be modified in place to change the collection. If the collection does\n not exist, it is created as an empty list and the list is returned.\n\n This is different from `get_collection()` which always returns a copy of\n the collection list if it exists and never creates an empty collection.\n\n Args:\n name: The key for the collection. For example, the `GraphKeys` class\n contains many standard names for collections.\n\n Returns:\n The list of values in the collection with the given `name`, or an empty\n list if no value has been added to that collection.\n \"\"\"\n with self._lock:\n coll_list = self._collections.get(name, None)\n if coll_list is None:\n coll_list = []\n self._collections[name] = coll_list\n return coll_list\n\n def get_collection(self, name, scope=None):\n \"\"\"Returns a list of values in the collection with the given `name`.\n\n This is different from `get_collection_ref()` which always returns the\n actual collection list if it exists in that it returns a new list each time\n it is called.\n\n Args:\n name: The key for the collection. For example, the `GraphKeys` class\n contains many standard names for collections.\n scope: (Optional.) If supplied, the resulting list is filtered to include\n only items whose `name` attribute matches using `re.match`. Items\n without a `name` attribute are never returned if a scope is supplied and\n the choice or `re.match` means that a `scope` without special tokens\n filters by prefix.\n\n Returns:\n The list of values in the collection with the given `name`, or\n an empty list if no value has been added to that collection. The\n list contains the values in the order under which they were\n collected.\n \"\"\"\n with self._lock:\n coll_list = self._collections.get(name, None)\n if coll_list is None:\n return []\n if scope is None:\n return list(coll_list)\n else:\n c = []\n regex = re.compile(scope)\n for item in coll_list:\n if hasattr(item, \"name\") and regex.match(item.name):\n c.append(item)\n return c\n\n def get_all_collection_keys(self):\n \"\"\"Returns a list of collections used in this graph.\"\"\"\n with self._lock:\n return [x for x in self._collections if isinstance(x, six.string_types)]\n\n def clear_collection(self, name):\n \"\"\"Clears all values in a collection.\n\n Args:\n name: The key for the collection. The `GraphKeys` class contains many\n standard names for collections.\n \"\"\"\n self._check_not_finalized()\n with self._lock:\n if name in self._collections:\n del self._collections[name]\n\n @contextlib.contextmanager\n def _original_op(self, op):\n \"\"\"Python 'with' handler to help annotate ops with their originator.\n\n An op may have an 'original_op' property that indicates the op on which\n it was based. For example a replica op is based on the op that was\n replicated and a gradient op is based on the op that was differentiated.\n\n All ops created in the scope of this 'with' handler will have\n the given 'op' as their original op.\n\n Args:\n op: The Operation that all ops created in this scope will have as their\n original op.\n\n Yields:\n Nothing.\n \"\"\"\n old_original_op = self._default_original_op\n try:\n self._default_original_op = op\n yield\n finally:\n self._default_original_op = old_original_op\n\n # pylint: disable=g-doc-return-or-yield\n @contextlib.contextmanager\n def name_scope(self, name):\n r\"\"\"Returns a context manager that creates hierarchical names for operations.\n\n A graph maintains a stack of name scopes. A `with name_scope(...):`\n statement pushes a new name onto the stack for the lifetime of the context.\n\n The `name` argument will be interpreted as follows:\n\n * A string (not ending with '/') will create a new name scope, in which\n `name` is appended to the prefix of all operations created in the\n context. If `name` has been used before, it will be made unique by\n calling `self.unique_name(name)`.\n * A scope previously captured from a `with g.name_scope(...) as\n scope:` statement will be treated as an \"absolute\" name scope, which\n makes it possible to re-enter existing scopes.\n * A value of `None` or the empty string will reset the current name scope\n to the top-level (empty) name scope.\n\n For example:\n\n ```python\n with tf.Graph().as_default() as g:\n c = tf.constant(5.0, name=\"c\")\n assert c.op.name == \"c\"\n c_1 = tf.constant(6.0, name=\"c\")\n assert c_1.op.name == \"c_1\"\n\n # Creates a scope called \"nested\"\n with g.name_scope(\"nested\") as scope:\n nested_c = tf.constant(10.0, name=\"c\")\n assert nested_c.op.name == \"nested/c\"\n\n # Creates a nested scope called \"inner\".\n with g.name_scope(\"inner\"):\n nested_inner_c = tf.constant(20.0, name=\"c\")\n assert nested_inner_c.op.name == \"nested/inner/c\"\n\n # Create a nested scope called \"inner_1\".\n with g.name_scope(\"inner\"):\n nested_inner_1_c = tf.constant(30.0, name=\"c\")\n assert nested_inner_1_c.op.name == \"nested/inner_1/c\"\n\n # Treats `scope` as an absolute name scope, and\n # switches to the \"nested/\" scope.\n with g.name_scope(scope):\n nested_d = tf.constant(40.0, name=\"d\")\n assert nested_d.op.name == \"nested/d\"\n\n with g.name_scope(\"\"):\n e = tf.constant(50.0, name=\"e\")\n assert e.op.name == \"e\"\n ```\n\n The name of the scope itself can be captured by `with\n g.name_scope(...) as scope:`, which stores the name of the scope\n in the variable `scope`. This value can be used to name an\n operation that represents the overall result of executing the ops\n in a scope. For example:\n\n ```python\n inputs = tf.constant(...)\n with g.name_scope('my_layer') as scope:\n weights = tf.Variable(..., name=\"weights\")\n biases = tf.Variable(..., name=\"biases\")\n affine = tf.matmul(inputs, weights) + biases\n output = tf.nn.relu(affine, name=scope)\n ```\n\n NOTE: This constructor validates the given `name`. Valid scope\n names match one of the following regular expressions:\n\n [A-Za-z0-9.][A-Za-z0-9_.\\\\-/]* (for scopes at the root)\n [A-Za-z0-9_.\\\\-/]* (for other scopes)\n\n Args:\n name: A name for the scope.\n\n Returns:\n A context manager that installs `name` as a new name scope.\n\n Raises:\n ValueError: If `name` is not a valid scope name, according to the rules\n above.\n \"\"\"\n if name:\n if self._name_stack:\n # Scopes created in a nested scope may have initial characters\n # that are illegal as the initial character of an op name\n # (viz. '-', '\\', '/', and '_').\n if not _VALID_SCOPE_NAME_REGEX.match(name):\n raise ValueError(\"'%s' is not a valid scope name\" % name)\n else:\n # Scopes created in the root must match the more restrictive\n # op name regex, which constrains the initial character.\n if not _VALID_OP_NAME_REGEX.match(name):\n raise ValueError(\"'%s' is not a valid scope name\" % name)\n try:\n old_stack = self._name_stack\n if not name: # Both for name=None and name=\"\" we re-set to empty scope.\n new_stack = None\n elif name and name[-1] == \"/\":\n new_stack = _name_from_scope_name(name)\n else:\n new_stack = self.unique_name(name)\n self._name_stack = new_stack\n yield \"\" if new_stack is None else new_stack + \"/\"\n finally:\n self._name_stack = old_stack\n # pylint: enable=g-doc-return-or-yield\n\n def unique_name(self, name, mark_as_used=True):\n \"\"\"Return a unique operation name for `name`.\n\n Note: You rarely need to call `unique_name()` directly. Most of\n the time you just need to create `with g.name_scope()` blocks to\n generate structured names.\n\n `unique_name` is used to generate structured names, separated by\n `\"/\"`, to help identify operations when debugging a graph.\n Operation names are displayed in error messages reported by the\n TensorFlow runtime, and in various visualization tools such as\n TensorBoard.\n\n If `mark_as_used` is set to `True`, which is the default, a new\n unique name is created and marked as in use. If it's set to `False`,\n the unique name is returned without actually being marked as used.\n This is useful when the caller simply wants to know what the name\n to be created will be.\n\n Args:\n name: The name for an operation.\n mark_as_used: Whether to mark this name as being used.\n\n Returns:\n A string to be passed to `create_op()` that will be used\n to name the operation being created.\n \"\"\"\n if self._name_stack:\n name = self._name_stack + \"/\" + name\n i = self._names_in_use.get(name, 0)\n # Increment the number for \"name\".\n if mark_as_used:\n self._names_in_use[name] = i + 1\n if i > 0:\n base_name = name\n # Make sure the composed name is not already used.\n while name in self._names_in_use:\n name = \"%s_%d\" % (base_name, i)\n i += 1\n # Mark the composed name as used in case someone wants\n # to call unique_name(\"name_1\").\n if mark_as_used:\n self._names_in_use[name] = 1\n return name\n\n @contextlib.contextmanager\n def colocate_with(self, op, ignore_existing=False):\n \"\"\"Returns a context manager that specifies an op to colocate with.\n\n Note: this function is not for public use, only for internal libraries.\n\n For example:\n\n ```python\n a = tf.Variable([1.0])\n with g.colocate_with(a):\n b = tf.constant(1.0)\n c = tf.add(a, b)\n ```\n\n `b` and `c` will always be colocated with `a`, no matter where `a`\n is eventually placed.\n\n **NOTE** Using a colocation scope resets any existing device constraints.\n\n If `op` is `None` then `ignore_existing` must be `True` and the new\n scope resets all colocation and device constraints.\n\n Args:\n op: The op to colocate all created ops with, or `None`.\n ignore_existing: If true, only applies colocation of this op within\n the context, rather than applying all colocation properties\n on the stack. If `op` is `None`, this value must be `True`.\n\n Raises:\n ValueError: if op is None but ignore_existing is False.\n\n Yields:\n A context manager that specifies the op with which to colocate\n newly created ops.\n\n \"\"\"\n if op is None and not ignore_existing:\n raise ValueError(\n \"Trying to reset colocation (op is None) but \"\n \"ignore_existing is not True\")\n\n if op is not None and not isinstance(op, Operation):\n # We always want to colocate with the reference op.\n op = internal_convert_to_tensor_or_indexed_slices(op, as_ref=True).op\n\n # By default, colocate_with resets the device function stack,\n # since colocate_with is typically used in specific internal\n # library functions where colocation is intended to be \"stronger\"\n # than device functions.\n #\n # In the future, a caller may specify that device_functions win\n # over colocation, in which case we can add support.\n device_fn_tmp = self._device_function_stack\n self._device_function_stack = []\n\n if ignore_existing:\n current_stack = self._colocation_stack\n self._colocation_stack = []\n\n if op is not None:\n self._colocation_stack.append(op)\n\n try:\n yield\n finally:\n # Restore device function stack\n self._device_function_stack = device_fn_tmp\n if op is not None:\n self._colocation_stack.pop()\n\n # Reset the colocation stack if requested.\n if ignore_existing:\n self._colocation_stack = current_stack\n\n @contextlib.contextmanager\n def device(self, device_name_or_function):\n \"\"\"Returns a context manager that specifies the default device to use.\n\n The `device_name_or_function` argument may either be a device name\n string, a device function, or None:\n\n * If it is a device name string, all operations constructed in\n this context will be assigned to the device with that name, unless\n overridden by a nested `device()` context.\n * If it is a function, it will be treated as a function from\n Operation objects to device name strings, and invoked each time\n a new Operation is created. The Operation will be assigned to\n the device with the returned name.\n * If it is None, all `device()` invocations from the enclosing context\n will be ignored.\n\n For information about the valid syntax of device name strings, see\n the documentation in\n [`DeviceNameUtils`](https://www.tensorflow.org/code/tensorflow/core/util/device_name_utils.h).\n\n For example:\n\n ```python\n with g.device('/gpu:0'):\n # All operations constructed in this context will be placed\n # on GPU 0.\n with g.device(None):\n # All operations constructed in this context will have no\n # assigned device.\n\n # Defines a function from `Operation` to device string.\n def matmul_on_gpu(n):\n if n.type == \"MatMul\":\n return \"/gpu:0\"\n else:\n return \"/cpu:0\"\n\n with g.device(matmul_on_gpu):\n # All operations of type \"MatMul\" constructed in this context\n # will be placed on GPU 0; all other operations will be placed\n # on CPU 0.\n ```\n\n **N.B.** The device scope may be overridden by op wrappers or\n other library code. For example, a variable assignment op\n `v.assign()` must be colocated with the `tf.Variable` `v`, and\n incompatible device scopes will be ignored.\n\n Args:\n device_name_or_function: The device name or function to use in\n the context.\n\n Returns:\n A context manager that specifies the default device to use for newly\n created ops.\n\n \"\"\"\n if (device_name_or_function is not None\n and not callable(device_name_or_function)):\n device_function = pydev.merge_device(device_name_or_function)\n else:\n device_function = device_name_or_function\n\n try:\n self._device_function_stack.append(device_function)\n yield\n finally:\n self._device_function_stack.pop()\n\n def _apply_device_functions(self, op):\n \"\"\"Applies the current device function stack to the given operation.\"\"\"\n # Apply any device functions in reverse order, so that the most recently\n # pushed function has the first chance to apply a device to the op.\n # We apply here because the result can depend on the Operation's\n # signature, which is computed in the Operation constructor.\n for device_function in reversed(self._device_function_stack):\n if device_function is None:\n break\n op._set_device(device_function(op))\n\n # pylint: disable=g-doc-return-or-yield\n @contextlib.contextmanager\n def container(self, container_name):\n \"\"\"Returns a context manager that specifies the resource container to use.\n\n Stateful operations, such as variables and queues, can maintain their\n states on devices so that they can be shared by multiple processes.\n A resource container is a string name under which these stateful\n operations are tracked. These resources can be released or cleared\n with `tf.Session.reset()`.\n\n For example:\n\n ```python\n with g.container('experiment0'):\n # All stateful Operations constructed in this context will be placed\n # in resource container \"experiment0\".\n v1 = tf.Variable([1.0])\n v2 = tf.Variable([2.0])\n with g.container(\"experiment1\"):\n # All stateful Operations constructed in this context will be\n # placed in resource container \"experiment1\".\n v3 = tf.Variable([3.0])\n q1 = tf.FIFOQueue(10, tf.float32)\n # All stateful Operations constructed in this context will be\n # be created in the \"experiment0\".\n v4 = tf.Variable([4.0])\n q1 = tf.FIFOQueue(20, tf.float32)\n with g.container(\"\"):\n # All stateful Operations constructed in this context will be\n # be placed in the default resource container.\n v5 = tf.Variable([5.0])\n q3 = tf.FIFOQueue(30, tf.float32)\n\n # Resets container \"experiment0\", after which the state of v1, v2, v4, q1\n # will become undefined (such as uninitialized).\n tf.Session.reset(target, [\"experiment0\"])\n ```\n\n Args:\n container_name: container name string.\n\n Returns:\n A context manager for defining resource containers for stateful ops,\n yields the container name.\n \"\"\"\n original_container = self._container\n try:\n self._container = container_name\n yield self._container\n finally:\n self._container = original_container\n # pylint: enable=g-doc-return-or-yield\n\n class _ControlDependenciesController(object):\n \"\"\"Context manager for `control_dependencies()`.\"\"\"\n\n def __init__(self, graph, control_inputs):\n \"\"\"Create a new `_ControlDependenciesController`.\n\n A `_ControlDependenciesController` is the context manager for\n `with tf.control_dependencies()` blocks. These normally nest,\n as described in the documentation for `control_dependencies()`.\n\n The `control_inputs` argument list control dependencies that must be\n added to the current set of control dependencies. Because of\n uniquification the set can be empty even if the caller passed a list of\n ops. The special value `None` indicates that we want to start a new\n empty set of control dependencies instead of extending the current set.\n\n In that case we also clear the current control flow context, which is an\n additional mechanism to add control dependencies.\n\n Args:\n graph: The graph that this controller is managing.\n control_inputs: List of ops to use as control inputs in addition\n to the current control dependencies. None to indicate that\n the dependencies should be cleared.\n \"\"\"\n self._graph = graph\n if control_inputs is None:\n self._control_inputs = []\n self._new_stack = True\n else:\n self._control_inputs = control_inputs\n self._new_stack = False\n self._seen_nodes = set()\n self._old_stack = None\n self._old_control_flow_context = None\n\n# pylint: disable=protected-access\n def __enter__(self):\n if self._new_stack:\n # Clear the control_dependencies graph.\n self._old_stack = self._graph._control_dependencies_stack\n self._graph._control_dependencies_stack = []\n # Clear the control_flow_context too.\n self._old_control_flow_context = self._graph._get_control_flow_context()\n self._graph._set_control_flow_context(None)\n self._graph._push_control_dependencies_controller(self)\n\n def __exit__(self, unused_type, unused_value, unused_traceback):\n self._graph._pop_control_dependencies_controller(self)\n if self._new_stack:\n self._graph._control_dependencies_stack = self._old_stack\n self._graph._set_control_flow_context(self._old_control_flow_context)\n# pylint: enable=protected-access\n\n @property\n def control_inputs(self):\n return self._control_inputs\n\n def add_op(self, op):\n self._seen_nodes.add(op)\n\n def op_in_group(self, op):\n return op in self._seen_nodes\n\n def _push_control_dependencies_controller(self, controller):\n self._control_dependencies_stack.append(controller)\n\n def _pop_control_dependencies_controller(self, controller):\n assert self._control_dependencies_stack[-1] is controller\n self._control_dependencies_stack.pop()\n\n def _current_control_dependencies(self):\n ret = set()\n for controller in self._control_dependencies_stack:\n for op in controller.control_inputs:\n ret.add(op)\n return ret\n\n def _control_dependencies_for_inputs(self, input_tensors):\n \"\"\"For an op that takes `input_tensors` as inputs, compute control inputs.\n\n The returned control dependencies should yield an execution that\n is equivalent to adding all control inputs in\n self._control_dependencies_stack to a newly created op. However,\n this function attempts to prune the returned control dependencies\n by observing that nodes created within the same `with\n control_dependencies(...):` block may have data dependencies that make\n the explicit approach redundant.\n\n Args:\n input_tensors: The direct data dependencies for an op to be created.\n\n Returns:\n A list of control inputs for the op to be created.\n \"\"\"\n ret = []\n input_ops = set([t.op for t in input_tensors])\n for controller in self._control_dependencies_stack:\n # If any of the input_ops already depends on the inputs from controller,\n # we say that the new op is dominated (by that input), and we therefore\n # do not need to add control dependencies for this controller's inputs.\n dominated = False\n for op in input_ops:\n if controller.op_in_group(op):\n dominated = True\n break\n if not dominated:\n # Don't add a control input if we already have a data dependency on i.\n # NOTE(mrry): We do not currently track transitive data dependencies,\n # so we may add redundant control inputs.\n ret.extend([c for c in controller.control_inputs if c not in input_ops])\n return ret\n\n def _record_op_seen_by_control_dependencies(self, op):\n \"\"\"Record that the given op depends on all registered control dependencies.\n\n Args:\n op: An Operation.\n \"\"\"\n for controller in self._control_dependencies_stack:\n controller.add_op(op)\n\n def control_dependencies(self, control_inputs):\n \"\"\"Returns a context manager that specifies control dependencies.\n\n Use with the `with` keyword to specify that all operations constructed\n within the context should have control dependencies on\n `control_inputs`. For example:\n\n ```python\n with g.control_dependencies([a, b, c]):\n # `d` and `e` will only run after `a`, `b`, and `c` have executed.\n d = ...\n e = ...\n ```\n\n Multiple calls to `control_dependencies()` can be nested, and in\n that case a new `Operation` will have control dependencies on the union\n of `control_inputs` from all active contexts.\n\n ```python\n with g.control_dependencies([a, b]):\n # Ops constructed here run after `a` and `b`.\n with g.control_dependencies([c, d]):\n # Ops constructed here run after `a`, `b`, `c`, and `d`.\n ```\n\n You can pass None to clear the control dependencies:\n\n ```python\n with g.control_dependencies([a, b]):\n # Ops constructed here run after `a` and `b`.\n with g.control_dependencies(None):\n # Ops constructed here run normally, not waiting for either `a` or `b`.\n with g.control_dependencies([c, d]):\n # Ops constructed here run after `c` and `d`, also not waiting\n # for either `a` or `b`.\n ```\n\n *N.B.* The control dependencies context applies *only* to ops that\n are constructed within the context. Merely using an op or tensor\n in the context does not add a control dependency. The following\n example illustrates this point:\n\n ```python\n # WRONG\n def my_func(pred, tensor):\n t = tf.matmul(tensor, tensor)\n with tf.control_dependencies([pred]):\n # The matmul op is created outside the context, so no control\n # dependency will be added.\n return t\n\n # RIGHT\n def my_func(pred, tensor):\n with tf.control_dependencies([pred]):\n # The matmul op is created in the context, so a control dependency\n # will be added.\n return tf.matmul(tensor, tensor)\n ```\n\n Args:\n control_inputs: A list of `Operation` or `Tensor` objects which\n must be executed or computed before running the operations\n defined in the context. Can also be `None` to clear the control\n dependencies.\n\n Returns:\n A context manager that specifies control dependencies for all\n operations constructed within the context.\n\n Raises:\n TypeError: If `control_inputs` is not a list of `Operation` or\n `Tensor` objects.\n \"\"\"\n if control_inputs is None:\n return self._ControlDependenciesController(self, None)\n # First convert the inputs to ops, and deduplicate them.\n # NOTE(mrry): Other than deduplication, we do not currently track direct\n # or indirect dependencies between control_inputs, which may result in\n # redundant control inputs.\n control_ops = []\n current = self._current_control_dependencies()\n for c in control_inputs:\n c = self.as_graph_element(c)\n if isinstance(c, Tensor):\n c = c.op\n elif not isinstance(c, Operation):\n raise TypeError(\"Control input must be Operation or Tensor: %s\" % c)\n if c not in current:\n control_ops.append(c)\n current.add(c)\n return self._ControlDependenciesController(self, control_ops)\n\n # pylint: disable=g-doc-return-or-yield\n @contextlib.contextmanager\n def _attr_scope(self, attr_map):\n \"\"\"EXPERIMENTAL: A context manager for setting attributes on operators.\n\n This context manager can be used to add additional\n attributes to operators within the scope of the context.\n\n For example:\n\n with ops.Graph().as_default() as g:\n f_1 = Foo() # No extra attributes\n with g._attr_scope({\"_a\": tf.attr_value_pb2.AttrValue(b=False)}):\n f_2 = Foo() # Additional attribute _a=False\n with g._attr_scope({\"_a\": tf.attr_value_pb2.AttrValue(b=True)}):\n f_3 = Foo() # Additional attribute _a=False\n with g._attr_scope({\"_a\": None}):\n f_4 = Foo() # No additional attributes.\n\n Args:\n attr_map: A dictionary mapping attr name strings to\n AttrValue protocol buffers or None.\n\n Returns:\n A context manager that sets the kernel label to be used for one or more\n ops created in that context.\n\n Raises:\n TypeError: If attr_map is not a dictionary mapping\n strings to AttrValue protobufs.\n \"\"\"\n if not isinstance(attr_map, dict):\n raise TypeError(\"attr_map must be a dictionary mapping \"\n \"strings to AttrValue protocol buffers\")\n # The saved_attrs dictionary stores any currently-set labels that\n # will be overridden by this context manager.\n saved_attrs = {}\n # Install the given attribute\n for name, attr in attr_map.items():\n if not (isinstance(name, six.string_types) and\n (isinstance(attr, (type(None), attr_value_pb2.AttrValue)) or\n callable(attr))):\n raise TypeError(\"attr_map must be a dictionary mapping \"\n \"strings to AttrValue protocol buffers or \"\n \"callables that emit AttrValue protocol buffers\")\n try:\n saved_attrs[name] = self._attr_scope_map[name]\n except KeyError:\n pass\n if attr is None:\n del self._attr_scope_map[name]\n else:\n self._attr_scope_map[name] = attr\n try:\n yield # The code within the context runs here.\n finally:\n # Remove the attributes set for this context, and restore any saved\n # attributes.\n for name, attr in attr_map.items():\n try:\n self._attr_scope_map[name] = saved_attrs[name]\n except KeyError:\n del self._attr_scope_map[name]\n # pylint: enable=g-doc-return-or-yield\n\n # pylint: disable=g-doc-return-or-yield\n @contextlib.contextmanager\n def _kernel_label_map(self, op_to_kernel_label_map):\n \"\"\"EXPERIMENTAL: A context manager for setting kernel labels.\n\n This context manager can be used to select particular\n implementations of kernels within the scope of the context.\n\n For example:\n\n with ops.Graph().as_default() as g:\n f_1 = Foo() # Uses the default registered kernel for the Foo op.\n with g.kernel_label_map({\"Foo\": \"v_2\"}):\n f_2 = Foo() # Uses the registered kernel with label \"v_2\"\n # for the Foo op.\n with g.kernel_label_map({\"Foo\": \"v_3\"}):\n f_3 = Foo() # Uses the registered kernel with label \"v_3\"\n # for the Foo op.\n with g.kernel_label_map({\"Foo\": \"\"}):\n f_4 = Foo() # Uses the default registered kernel\n # for the Foo op.\n\n Args:\n op_to_kernel_label_map: A dictionary mapping op type strings to\n kernel label strings.\n\n Returns:\n A context manager that sets the kernel label to be used for one or more\n ops created in that context.\n\n Raises:\n TypeError: If op_to_kernel_label_map is not a dictionary mapping\n strings to strings.\n \"\"\"\n if not isinstance(op_to_kernel_label_map, dict):\n raise TypeError(\"op_to_kernel_label_map must be a dictionary mapping \"\n \"strings to strings\")\n # The saved_labels dictionary stores any currently-set labels that\n # will be overridden by this context manager.\n saved_labels = {}\n # Install the given label\n for op_type, label in op_to_kernel_label_map.items():\n if not (isinstance(op_type, six.string_types)\n and isinstance(label, six.string_types)):\n raise TypeError(\"op_to_kernel_label_map must be a dictionary mapping \"\n \"strings to strings\")\n try:\n saved_labels[op_type] = self._op_to_kernel_label_map[op_type]\n except KeyError:\n pass\n self._op_to_kernel_label_map[op_type] = label\n try:\n yield # The code within the context runs here.\n finally:\n # Remove the labels set for this context, and restore any saved labels.\n for op_type, label in op_to_kernel_label_map.items():\n try:\n self._op_to_kernel_label_map[op_type] = saved_labels[op_type]\n except KeyError:\n del self._op_to_kernel_label_map[op_type]\n # pylint: enable=g-doc-return-or-yield\n\n # pylint: disable=g-doc-return-or-yield\n @contextlib.contextmanager\n def gradient_override_map(self, op_type_map):\n \"\"\"EXPERIMENTAL: A context manager for overriding gradient functions.\n\n This context manager can be used to override the gradient function\n that will be used for ops within the scope of the context.\n\n For example:\n\n ```python\n @tf.RegisterGradient(\"CustomSquare\")\n def _custom_square_grad(op, grad):\n # ...\n\n with tf.Graph().as_default() as g:\n c = tf.constant(5.0)\n s_1 = tf.square(c) # Uses the default gradient for tf.square.\n with g.gradient_override_map({\"Square\": \"CustomSquare\"}):\n s_2 = tf.square(s_2) # Uses _custom_square_grad to compute the\n # gradient of s_2.\n ```\n\n Args:\n op_type_map: A dictionary mapping op type strings to alternative op\n type strings.\n\n Returns:\n A context manager that sets the alternative op type to be used for one\n or more ops created in that context.\n\n Raises:\n TypeError: If `op_type_map` is not a dictionary mapping strings to\n strings.\n \"\"\"\n if not isinstance(op_type_map, dict):\n raise TypeError(\"op_type_map must be a dictionary mapping \"\n \"strings to strings\")\n # The saved_mappings dictionary stores any currently-set mappings that\n # will be overridden by this context manager.\n saved_mappings = {}\n # Install the given label\n for op_type, mapped_op_type in op_type_map.items():\n if not (isinstance(op_type, six.string_types)\n and isinstance(mapped_op_type, six.string_types)):\n raise TypeError(\"op_type_map must be a dictionary mapping \"\n \"strings to strings\")\n try:\n saved_mappings[op_type] = self._gradient_override_map[op_type]\n except KeyError:\n pass\n self._gradient_override_map[op_type] = mapped_op_type\n try:\n yield # The code within the context runs here.\n finally:\n # Remove the labels set for this context, and restore any saved labels.\n for op_type, mapped_op_type in op_type_map.items():\n try:\n self._gradient_override_map[op_type] = saved_mappings[op_type]\n except KeyError:\n del self._gradient_override_map[op_type]\n # pylint: enable=g-doc-return-or-yield\n\n def prevent_feeding(self, tensor):\n \"\"\"Marks the given `tensor` as unfeedable in this graph.\"\"\"\n self._unfeedable_tensors.add(tensor)\n\n def is_feedable(self, tensor):\n \"\"\"Returns `True` if and only if `tensor` is feedable.\"\"\"\n return tensor not in self._unfeedable_tensors\n\n def prevent_fetching(self, op):\n \"\"\"Marks the given `op` as unfetchable in this graph.\"\"\"\n self._unfetchable_ops.add(op)\n\n def is_fetchable(self, tensor_or_op):\n \"\"\"Returns `True` if and only if `tensor_or_op` is fetchable.\"\"\"\n if isinstance(tensor_or_op, Tensor):\n return tensor_or_op.op not in self._unfetchable_ops\n else:\n return tensor_or_op not in self._unfetchable_ops\n\n\ndef device(device_name_or_function):\n \"\"\"Wrapper for `Graph.device()` using the default graph.\n\n See\n [`Graph.device()`](../../api_docs/python/framework.md#Graph.device)\n for more details.\n\n Args:\n device_name_or_function: The device name or function to use in\n the context.\n\n Returns:\n A context manager that specifies the default device to use for newly\n created ops.\n \"\"\"\n return get_default_graph().device(device_name_or_function)\n\n\ndef container(container_name):\n \"\"\"Wrapper for `Graph.container()` using the default graph.\n\n Args:\n container_name: The container string to use in the context.\n\n Returns:\n A context manager that specifies the default container to use for newly\n created stateful ops.\n \"\"\"\n return get_default_graph().container(container_name)\n\n\ndef colocate_with(op, ignore_existing=False):\n return get_default_graph().colocate_with(op, ignore_existing)\n\n\ndef control_dependencies(control_inputs):\n \"\"\"Wrapper for `Graph.control_dependencies()` using the default graph.\n\n See [`Graph.control_dependencies()`](../../api_docs/python/framework.md#Graph.control_dependencies)\n for more details.\n\n Args:\n control_inputs: A list of `Operation` or `Tensor` objects which\n must be executed or computed before running the operations\n defined in the context. Can also be `None` to clear the control\n dependencies.\n\n Returns:\n A context manager that specifies control dependencies for all\n operations constructed within the context.\n \"\"\"\n return get_default_graph().control_dependencies(control_inputs)\n\n\nclass _DefaultStack(threading.local):\n \"\"\"A thread-local stack of objects for providing implicit defaults.\"\"\"\n\n def __init__(self):\n super(_DefaultStack, self).__init__()\n self._enforce_nesting = True\n self.stack = []\n\n def get_default(self):\n return self.stack[-1] if len(self.stack) >= 1 else None\n\n def reset(self):\n self.stack = []\n\n @property\n def enforce_nesting(self):\n return self._enforce_nesting\n\n @enforce_nesting.setter\n def enforce_nesting(self, value):\n self._enforce_nesting = value\n\n @contextlib.contextmanager\n def get_controller(self, default):\n \"\"\"A context manager for manipulating a default stack.\"\"\"\n try:\n self.stack.append(default)\n yield default\n finally:\n if self._enforce_nesting:\n if self.stack[-1] is not default:\n raise AssertionError(\n \"Nesting violated for default stack of %s objects\"\n % type(default))\n self.stack.pop()\n else:\n self.stack.remove(default)\n\n_default_session_stack = _DefaultStack()\n\n\ndef default_session(session):\n \"\"\"Python \"with\" handler for defining a default session.\n\n This function provides a means of registering a session for handling\n Tensor.eval() and Operation.run() calls. It is primarily intended for use\n by session.Session, but can be used with any object that implements\n the Session.run() interface.\n\n Use with the \"with\" keyword to specify that Tensor.eval() and Operation.run()\n invocations within the scope of a block should be executed by a particular\n session.\n\n The default session applies to the current thread only, so it is always\n possible to inspect the call stack and determine the scope of a default\n session. If you create a new thread, and wish to use the default session\n in that thread, you must explicitly add a \"with ops.default_session(sess):\"\n block in that thread's function.\n\n Example:\n The following code examples are equivalent:\n\n # 1. Using the Session object directly:\n sess = ...\n c = tf.constant(5.0)\n sess.run(c)\n\n # 2. Using default_session():\n sess = ...\n with ops.default_session(sess):\n c = tf.constant(5.0)\n result = c.eval()\n\n # 3. Overriding default_session():\n sess = ...\n with ops.default_session(sess):\n c = tf.constant(5.0)\n with ops.default_session(...):\n c.eval(session=sess)\n\n Args:\n session: The session to be installed as the default session.\n\n Returns:\n A context manager for the default session.\n \"\"\"\n return _default_session_stack.get_controller(session)\n\n\ndef get_default_session():\n \"\"\"Returns the default session for the current thread.\n\n The returned `Session` will be the innermost session on which a\n `Session` or `Session.as_default()` context has been entered.\n\n NOTE: The default session is a property of the current thread. If you\n create a new thread, and wish to use the default session in that\n thread, you must explicitly add a `with sess.as_default():` in that\n thread's function.\n\n Returns:\n The default `Session` being used in the current thread.\n \"\"\"\n return _default_session_stack.get_default()\n\n\ndef _eval_using_default_session(tensors, feed_dict, graph, session=None):\n \"\"\"Uses the default session to evaluate one or more tensors.\n\n Args:\n tensors: A single Tensor, or a list of Tensor objects.\n feed_dict: A dictionary that maps Tensor objects (or tensor names) to lists,\n numpy ndarrays, TensorProtos, or strings.\n graph: The graph in which the tensors are defined.\n session: (Optional) A different session to use to evaluate \"tensors\".\n\n Returns:\n Either a single numpy ndarray if \"tensors\" is a single tensor; or a list\n of numpy ndarrays that each correspond to the respective element in\n \"tensors\".\n\n Raises:\n ValueError: If no default session is available; the default session\n does not have \"graph\" as its graph; or if \"session\" is specified,\n and it does not have \"graph\" as its graph.\n \"\"\"\n if session is None:\n session = get_default_session()\n if session is None:\n raise ValueError(\"Cannot evaluate tensor using `eval()`: No default \"\n \"session is registered. Use `with \"\n \"sess.as_default()` or pass an explicit session to \"\n \"`eval(session=sess)`\")\n if session.graph is not graph:\n raise ValueError(\"Cannot use the default session to evaluate tensor: \"\n \"the tensor's graph is different from the session's \"\n \"graph. Pass an explicit session to \"\n \"`eval(session=sess)`.\")\n else:\n if session.graph is not graph:\n raise ValueError(\"Cannot use the given session to evaluate tensor: \"\n \"the tensor's graph is different from the session's \"\n \"graph.\")\n return session.run(tensors, feed_dict)\n\n\ndef _run_using_default_session(operation, feed_dict, graph, session=None):\n \"\"\"Uses the default session to run \"operation\".\n\n Args:\n operation: The Operation to be run.\n feed_dict: A dictionary that maps Tensor objects (or tensor names) to lists,\n numpy ndarrays, TensorProtos, or strings.\n graph: The graph in which \"operation\" is defined.\n session: (Optional) A different session to use to run \"operation\".\n\n Raises:\n ValueError: If no default session is available; the default session\n does not have \"graph\" as its graph; or if \"session\" is specified,\n and it does not have \"graph\" as its graph.\n \"\"\"\n if session is None:\n session = get_default_session()\n if session is None:\n raise ValueError(\"Cannot execute operation using `run()`: No default \"\n \"session is registered. Use `with \"\n \"sess.as_default():` or pass an explicit session to \"\n \"`run(session=sess)`\")\n if session.graph is not graph:\n raise ValueError(\"Cannot use the default session to execute operation: \"\n \"the operation's graph is different from the \"\n \"session's graph. Pass an explicit session to \"\n \"run(session=sess).\")\n else:\n if session.graph is not graph:\n raise ValueError(\"Cannot use the given session to execute operation: \"\n \"the operation's graph is different from the session's \"\n \"graph.\")\n session.run(operation, feed_dict)\n\n\nclass _DefaultGraphStack(_DefaultStack):\n \"\"\"A thread-local stack of objects for providing an implicit default graph.\"\"\"\n\n def __init__(self):\n super(_DefaultGraphStack, self).__init__()\n self._global_default_graph = None\n\n def get_default(self):\n \"\"\"Override that returns a global default if the stack is empty.\"\"\"\n ret = super(_DefaultGraphStack, self).get_default()\n if ret is None:\n ret = self._GetGlobalDefaultGraph()\n return ret\n\n def _GetGlobalDefaultGraph(self):\n if self._global_default_graph is None:\n # TODO(mrry): Perhaps log that the default graph is being used, or set\n # provide some other feedback to prevent confusion when a mixture of\n # the global default graph and an explicit graph are combined in the\n # same process.\n self._global_default_graph = Graph()\n return self._global_default_graph\n\n def reset(self):\n super(_DefaultGraphStack, self).reset()\n self._global_default_graph = None\n\n_default_graph_stack = _DefaultGraphStack()\n\n\ndef reset_default_graph():\n \"\"\"Clears the default graph stack and resets the global default graph.\n\n NOTE: The default graph is a property of the current thread. This\n function applies only to the current thread. Calling this function while\n a `tf.Session` or `tf.InteractiveSession` is active will result in undefined\n behavior. Using any previously created `tf.Operation` or `tf.Tensor` objects\n after calling this function will result in undefined behavior.\n \"\"\"\n _default_graph_stack.reset()\n\n\ndef get_default_graph():\n \"\"\"Returns the default graph for the current thread.\n\n The returned graph will be the innermost graph on which a\n `Graph.as_default()` context has been entered, or a global default\n graph if none has been explicitly created.\n\n NOTE: The default graph is a property of the current thread. If you\n create a new thread, and wish to use the default graph in that\n thread, you must explicitly add a `with g.as_default():` in that\n thread's function.\n\n Returns:\n The default `Graph` being used in the current thread.\n \"\"\"\n return _default_graph_stack.get_default()\n\n\ndef _assert_same_graph(original_item, item):\n \"\"\"Fail if the 2 items are from different graphs.\n\n Args:\n original_item: Original item to check against.\n item: Item to check.\n\n Raises:\n ValueError: if graphs do not match.\n \"\"\"\n if original_item.graph is not item.graph:\n raise ValueError(\n \"%s must be from the same graph as %s.\" % (item, original_item))\n\n\ndef _get_graph_from_inputs(op_input_list, graph=None):\n \"\"\"Returns the appropriate graph to use for the given inputs.\n\n This library method provides a consistent algorithm for choosing the graph\n in which an Operation should be constructed:\n\n 1. If the default graph is being used to construct a function, we\n use the default graph.\n 2. If the \"graph\" is specified explicitly, we validate that all of the inputs\n in \"op_input_list\" are compatible with that graph.\n 3. Otherwise, we attempt to select a graph from the first Operation-\n or Tensor-valued input in \"op_input_list\", and validate that all other\n such inputs are in the same graph.\n 4. If the graph was not specified and it could not be inferred from\n \"op_input_list\", we attempt to use the default graph.\n\n Args:\n op_input_list: A list of inputs to an operation, which may include `Tensor`,\n `Operation`, and other objects that may be converted to a graph element.\n graph: (Optional) The explicit graph to use.\n\n Raises:\n TypeError: If op_input_list is not a list or tuple, or if graph is not a\n Graph.\n ValueError: If a graph is explicitly passed and not all inputs are from it,\n or if the inputs are from multiple graphs, or we could not find a graph\n and there was no default graph.\n\n Returns:\n The appropriate graph to use for the given inputs.\n\n \"\"\"\n if get_default_graph().building_function:\n return get_default_graph()\n\n op_input_list = tuple(op_input_list) # Handle generators correctly\n if graph and not isinstance(graph, Graph):\n raise TypeError(\"Input graph needs to be a Graph: %s\" % graph)\n\n # 1. We validate that all of the inputs are from the same graph. This is\n # either the supplied graph parameter, or the first one selected from one\n # the graph-element-valued inputs. In the latter case, we hold onto\n # that input in original_graph_element so we can provide a more\n # informative error if a mismatch is found.\n original_graph_element = None\n for op_input in op_input_list:\n # Determine if this is a valid graph_element.\n graph_element = None\n if isinstance(op_input, (Operation, _TensorLike)):\n graph_element = op_input\n else:\n graph_element = _as_graph_element(op_input)\n\n if graph_element is not None:\n if not graph:\n original_graph_element = graph_element\n graph = graph_element.graph\n elif original_graph_element is not None:\n _assert_same_graph(original_graph_element, graph_element)\n elif graph_element.graph is not graph:\n raise ValueError(\n \"%s is not from the passed-in graph.\" % graph_element)\n\n # 2. If all else fails, we use the default graph, which is always there.\n return graph or get_default_graph()\n\n\nclass GraphKeys(object):\n \"\"\"Standard names to use for graph collections.\n\n The standard library uses various well-known names to collect and\n retrieve values associated with a graph. For example, the\n `tf.Optimizer` subclasses default to optimizing the variables\n collected under `tf.GraphKeys.TRAINABLE_VARIABLES` if none is\n specified, but it is also possible to pass an explicit list of\n variables.\n\n The following standard keys are defined:\n\n * `GLOBAL_VARIABLES`: the default collection of `Variable` objects, shared\n across distributed environment (model variables are subset of these). See\n [`tf.global_variables()`](../../api_docs/python/state_ops.md#global_variables)\n for more details.\n Commonly, all `TRAINABLE_VARIABLES` variables will be in `MODEL_VARIABLES`,\n and all `MODEL_VARIABLES` variables will be in `GLOBAL_VARIABLES`.\n * `LOCAL_VARIABLES`: the subset of `Variable` objects that are local to each\n machine. Usually used for temporarily variables, like counters.\n Note: use `tf.contrib.framework.local_variable` to add to this collection.\n * `MODEL_VARIABLES`: the subset of `Variable` objects that are used in the\n model for inference (feed forward). Note: use\n `tf.contrib.framework.model_variable` to add to this collection.\n * `TRAINABLE_VARIABLES`: the subset of `Variable` objects that will\n be trained by an optimizer. See\n [`tf.trainable_variables()`](../../api_docs/python/state_ops.md#trainable_variables)\n for more details.\n * `SUMMARIES`: the summary `Tensor` objects that have been created in the\n graph. See\n [`tf.summary.merge_all()`](../../api_docs/python/summary.md#merge_all)\n for more details.\n * `QUEUE_RUNNERS`: the `QueueRunner` objects that are used to\n produce input for a computation. See\n [`tf.start_queue_runners()`](../../api_docs/python/train.md#start_queue_runners)\n for more details.\n * `MOVING_AVERAGE_VARIABLES`: the subset of `Variable` objects that will also\n keep moving averages. See\n [`tf.moving_average_variables()`](../../api_docs/python/state_ops.md#moving_average_variables)\n for more details.\n * `REGULARIZATION_LOSSES`: regularization losses collected during graph\n construction.\n * `WEIGHTS`: weights inside neural network layers\n * `BIASES`: biases inside neural network layers\n * `ACTIVATIONS`: activations of neural network layers\n \"\"\"\n\n # Key to collect Variable objects that are global (shared across machines).\n # Default collection for all variables, except local ones.\n GLOBAL_VARIABLES = \"variables\"\n # Key to collect local variables that are local to the machine and are not\n # saved/restored.\n LOCAL_VARIABLES = \"local_variables\"\n # Key to collect model variables defined by layers.\n MODEL_VARIABLES = \"model_variables\"\n # Key to collect Variable objects that will be trained by the\n # optimizers.\n TRAINABLE_VARIABLES = \"trainable_variables\"\n # Key to collect summaries.\n SUMMARIES = \"summaries\"\n # Key to collect QueueRunners.\n QUEUE_RUNNERS = \"queue_runners\"\n # Key to collect table initializers.\n TABLE_INITIALIZERS = \"table_initializer\"\n # Key to collect asset filepaths. An asset represents an external resource\n # like a vocabulary file.\n ASSET_FILEPATHS = \"asset_filepaths\"\n # Key to collect Variable objects that keep moving averages.\n MOVING_AVERAGE_VARIABLES = \"moving_average_variables\"\n # Key to collect regularization losses at graph construction.\n REGULARIZATION_LOSSES = \"regularization_losses\"\n # Key to collect concatenated sharded variables.\n CONCATENATED_VARIABLES = \"concatenated_variables\"\n # Key to collect savers.\n SAVERS = \"savers\"\n # Key to collect weights\n WEIGHTS = \"weights\"\n # Key to collect biases\n BIASES = \"biases\"\n # Key to collect activations\n ACTIVATIONS = \"activations\"\n # Key to collect update_ops\n UPDATE_OPS = \"update_ops\"\n # Key to collect losses\n LOSSES = \"losses\"\n # Key to collect BaseSaverBuilder.SaveableObject instances for checkpointing.\n SAVEABLE_OBJECTS = \"saveable_objects\"\n # Key to collect all shared resources used by the graph which need to be\n # initialized once per cluster.\n RESOURCES = \"resources\"\n # Key to collect all shared resources used in this graph which need to be\n # initialized once per session.\n LOCAL_RESOURCES = \"local_resources\"\n # Trainable resource-style variables.\n TRAINABLE_RESOURCE_VARIABLES = \"trainable_resource_variables\"\n\n # Key to indicate various ops.\n INIT_OP = \"init_op\"\n LOCAL_INIT_OP = \"local_init_op\"\n READY_OP = \"ready_op\"\n READY_FOR_LOCAL_INIT_OP = \"ready_for_local_init_op\"\n SUMMARY_OP = \"summary_op\"\n GLOBAL_STEP = \"global_step\"\n\n # Used to count the number of evaluations performed during a single evaluation\n # run.\n EVAL_STEP = \"eval_step\"\n TRAIN_OP = \"train_op\"\n\n # Key for control flow context.\n COND_CONTEXT = \"cond_context\"\n WHILE_CONTEXT = \"while_context\"\n\n @decorator_utils.classproperty\n def VARIABLES(cls): # pylint: disable=no-self-argument\n logging.warning(\"VARIABLES collection name is deprecated, \"\n \"please use GLOBAL_VARIABLES instead; \"\n \"VARIABLES will be removed after 2017-03-02.\")\n return cls.GLOBAL_VARIABLES\n\n\ndef add_to_collection(name, value):\n \"\"\"Wrapper for `Graph.add_to_collection()` using the default graph.\n\n See [`Graph.add_to_collection()`](../../api_docs/python/framework.md#Graph.add_to_collection)\n for more details.\n\n Args:\n name: The key for the collection. For example, the `GraphKeys` class\n contains many standard names for collections.\n value: The value to add to the collection.\n \"\"\"\n get_default_graph().add_to_collection(name, value)\n\n\ndef add_to_collections(names, value):\n \"\"\"Wrapper for `Graph.add_to_collections()` using the default graph.\n\n See [`Graph.add_to_collections()`](../../api_docs/python/framework.md#Graph.add_to_collections)\n for more details.\n\n Args:\n names: The key for the collections. The `GraphKeys` class\n contains many standard names for collections.\n value: The value to add to the collections.\n \"\"\"\n get_default_graph().add_to_collections(names, value)\n\n\ndef get_collection_ref(key):\n \"\"\"Wrapper for `Graph.get_collection_ref()` using the default graph.\n\n See [`Graph.get_collection_ref()`](../../api_docs/python/framework.md#Graph.get_collection_ref)\n for more details.\n\n Args:\n key: The key for the collection. For example, the `GraphKeys` class\n contains many standard names for collections.\n\n Returns:\n The list of values in the collection with the given `name`, or an empty\n list if no value has been added to that collection. Note that this returns\n the collection list itself, which can be modified in place to change the\n collection.\n \"\"\"\n return get_default_graph().get_collection_ref(key)\n\n\ndef get_collection(key, scope=None):\n \"\"\"Wrapper for `Graph.get_collection()` using the default graph.\n\n See [`Graph.get_collection()`](../../api_docs/python/framework.md#Graph.get_collection)\n for more details.\n\n Args:\n key: The key for the collection. For example, the `GraphKeys` class\n contains many standard names for collections.\n scope: (Optional.) If supplied, the resulting list is filtered to include\n only items whose `name` attribute matches using `re.match`. Items\n without a `name` attribute are never returned if a scope is supplied and\n the choice or `re.match` means that a `scope` without special tokens\n filters by prefix.\n\n Returns:\n The list of values in the collection with the given `name`, or\n an empty list if no value has been added to that collection. The\n list contains the values in the order under which they were\n collected.\n \"\"\"\n return get_default_graph().get_collection(key, scope)\n\n\ndef get_all_collection_keys():\n \"\"\"Returns a list of collections used in the default graph.\"\"\"\n return get_default_graph().get_all_collection_keys()\n\n\n# pylint: disable=g-doc-return-or-yield\[email protected]\ndef name_scope(name, default_name=None, values=None):\n \"\"\"Returns a context manager for use when defining a Python op.\n\n This context manager validates that the given `values` are from the\n same graph, makes that graph the default graph, and pushes a\n name scope in that graph (see\n [`Graph.name_scope()`](../../api_docs/python/framework.md#Graph.name_scope)\n for more details on that).\n\n For example, to define a new Python op called `my_op`:\n\n ```python\n def my_op(a, b, c, name=None):\n with tf.name_scope(name, \"MyOp\", [a, b, c]) as scope:\n a = tf.convert_to_tensor(a, name=\"a\")\n b = tf.convert_to_tensor(b, name=\"b\")\n c = tf.convert_to_tensor(c, name=\"c\")\n # Define some computation that uses `a`, `b`, and `c`.\n return foo_op(..., name=scope)\n ```\n\n Args:\n name: The name argument that is passed to the op function.\n default_name: The default name to use if the `name` argument is `None`.\n values: The list of `Tensor` arguments that are passed to the op function.\n\n Returns:\n A context manager for use in defining Python ops. Yields the name scope.\n\n Raises:\n ValueError: if neither `name` nor `default_name` is provided\n but `values` are.\n \"\"\"\n n = default_name if name is None else name\n if n is None and values is not None:\n # We only raise an error if values is not None (provided) because currently\n # tf.name_scope(None) (values=None then) is sometimes used as an idiom\n # to reset to top scope.\n raise ValueError(\n \"At least one of name (%s) and default_name (%s) must be provided.\" % (\n name, default_name))\n if values is None:\n values = []\n g = _get_graph_from_inputs(values)\n with g.as_default(), g.name_scope(n) as scope:\n yield scope\n# pylint: enable=g-doc-return-or-yield\n\n\ndef strip_name_scope(name, export_scope):\n \"\"\"Removes name scope from a name.\n\n Args:\n name: A `string` name.\n export_scope: Optional `string`. Name scope to remove.\n\n Returns:\n Name with name scope removed, or the original name if export_scope\n is None.\n \"\"\"\n if export_scope:\n # Strips export_scope/, export_scope///,\n # ^export_scope/, loc:@export_scope/.\n str_to_replace = r\"([\\^]|loc:@|^)\" + export_scope + r\"[\\/]+(.*)\"\n return re.sub(str_to_replace, r\"\\1\\2\", compat.as_str(name), count=1)\n else:\n return name\n\n\ndef prepend_name_scope(name, import_scope):\n \"\"\"Prepends name scope to a name.\n\n Args:\n name: A `string` name.\n import_scope: Optional `string`. Name scope to add.\n\n Returns:\n Name with name scope added, or the original name if import_scope\n is None.\n \"\"\"\n if import_scope:\n str_to_replace = r\"([\\^]|loc:@|^)(.*)\"\n return re.sub(str_to_replace, r\"\\1\" + import_scope + r\"/\\2\",\n compat.as_str(name))\n else:\n return name\n\n\n# pylint: disable=g-doc-return-or-yield\[email protected]\ndef op_scope(values, name, default_name=None):\n \"\"\"DEPRECATED. Same as name_scope above, just different argument order.\"\"\"\n logging.warn(\"tf.op_scope(values, name, default_name) is deprecated,\"\n \" use tf.name_scope(name, default_name, values)\")\n with name_scope(name, default_name=default_name, values=values) as scope:\n yield scope\n\n\n_proto_function_registry = registry.Registry(\"proto functions\")\n\n\ndef register_proto_function(collection_name, proto_type=None, to_proto=None,\n from_proto=None):\n \"\"\"Registers `to_proto` and `from_proto` functions for collection_name.\n\n `to_proto` function converts a Python object to the corresponding protocol\n buffer, and returns the protocol buffer.\n\n `from_proto` function converts protocol buffer into a Python object, and\n returns the object..\n\n Args:\n collection_name: Name of the collection.\n proto_type: Protobuf type, such as `saver_pb2.SaverDef`,\n `variable_pb2.VariableDef`, `queue_runner_pb2.QueueRunnerDef`..\n to_proto: Function that implements Python object to protobuf conversion.\n from_proto: Function that implements protobuf to Python object conversion.\n \"\"\"\n if to_proto and not callable(to_proto):\n raise TypeError(\"to_proto must be callable.\")\n if from_proto and not callable(from_proto):\n raise TypeError(\"from_proto must be callable.\")\n\n _proto_function_registry.register((proto_type, to_proto, from_proto),\n collection_name)\n\n\ndef get_collection_proto_type(collection_name):\n \"\"\"Returns the proto_type for collection_name.\"\"\"\n try:\n return _proto_function_registry.lookup(collection_name)[0]\n except LookupError:\n return None\n\n\ndef get_to_proto_function(collection_name):\n \"\"\"Returns the to_proto function for collection_name.\"\"\"\n try:\n return _proto_function_registry.lookup(collection_name)[1]\n except LookupError:\n return None\n\n\ndef get_from_proto_function(collection_name):\n \"\"\"Returns the from_proto function for collection_name.\"\"\"\n try:\n return _proto_function_registry.lookup(collection_name)[2]\n except LookupError:\n return None\n\n\ndef _operation_conversion_error(op, dtype=None, name=None, as_ref=False):\n \"\"\"Produce a nice error if someone converts an Operation to a Tensor.\"\"\"\n raise TypeError(\n (\"Can't convert Operation '%s' to Tensor \"\n \"(target dtype=%r, name=%r, as_ref=%r)\") %\n (op.name, dtype, name, as_ref))\n\n\nregister_tensor_conversion_function(Operation, _operation_conversion_error)\n"
] | [
[
"tensorflow.python.framework.device.merge_device",
"tensorflow.python.platform.tf_logging.warning",
"tensorflow.python.framework.registry.Registry",
"tensorflow.core.framework.function_pb2.GradientDef",
"tensorflow.python.platform.tf_logging.warn",
"tensorflow.python.util.compat.as_bytes",
"tensorflow.python.framework.op_def_registry.get_registered_ops",
"tensorflow.python.framework.dtypes.as_dtype",
"tensorflow.core.framework.node_def_pb2.NodeDef",
"tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto",
"tensorflow.core.framework.versions_pb2.VersionDef",
"tensorflow.python.util.compat.as_str",
"tensorflow.core.framework.attr_value_pb2.AttrValue.ListValue",
"tensorflow.python.framework.tensor_shape.unknown_shape",
"tensorflow.core.framework.graph_pb2.GraphDef"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
LordRaivo/ToxicBot | [
"ebc09064afef0f4af5def1022eada9ef109d27ac"
] | [
"quantize_models.py"
] | [
"import torch\nimport torch.nn as nn\nimport models\nimport os\nimport pickle\nimport glob\nimport json\nimport numpy as np\n\nbackend = 'fbgemm'\ndef split_path(path):\n\t_, path = os.path.splitdrive(path)\n\tfolders = []\n\twhile 1:\n\t\tpath, folder = os.path.split(path)\n\t\tif folder != \"\":\n\t\t\tfolders.append(folder)\n\t\telif path == \"\\\\\" or path == \"\":\n\t\t\tbreak\n\tfolders.reverse()\n\treturn folders\n\nif __name__ == \"__main__\":\n\tfolder = 'models'\n\tfor path in glob.glob(f'{folder}/*/'):\n\t\tmodel_name = split_path(path)[-1].split('_')[0]\n\t\tmodel_class = getattr(models, model_name)\n\t\tmodelpath = os.path.join(path, 'model.pt')\n\t\tsmallmodelpath = os.path.join(path, 'model_sml.pt')\n\t\targspath = os.path.join(path, 'args.txt')\n\t\t\n\t\twith open(argspath, 'r') as f:\n\t\t\targs = json.loads(f.readline())\n\t\t\t\n\t\tmodel = model_class(**args)\n\t\tmodel.load_state_dict(torch.load(modelpath, map_location=torch.device('cpu')))\n\t\tmodel = model.half()\n\t\tmodel.eval()\n\t\ttorch.save(model.state_dict(), smallmodelpath)"
] | [
[
"torch.device"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
fuxingwang2018/HCLIMAI | [
"8673d1b2cb9c5c17e70ba523fa64a8579c48798a"
] | [
"PreProcessing/compare_3km_12km_snapshot.py"
] | [
"\n#%matplotlib inline\nimport matplotlib.pyplot as plt\nimport netCDF4\nplt.switch_backend('agg')\nfrom map_plot import MapPlot\nimport numpy as np\n\ndata_folder = '/nobackup/rossby26/users/sm_fuxwa/AI/standard_data/'\nfig_out_path = '/home/sm_fuxwa/Figures/AI/'\n\n# 3km: tas, pr \n# 12km: ta500, ta700, ta850, ta950, \n#\thus500, hus700, hus850, hus950, \n#\tua500, ua700, ua850, ua950, \n#\tva500, va700, va850, va950, \n#\tphi500, phi700, phi850, phi950,\n# tas, pr\nvar = 'tas' \nexp_name = '3km' # 'EOBS20', '3km', '12km'\n\nplot_period = '1h'\n\nif plot_period == '1h':\n rec_start = 6590\n rec_end = rec_start + 1\n ymdhm = 200010011330\n scale_factor = 3600 \nelif plot_period == '1d':\n rec_start = 6577\n rec_end = 6601\n ymdhm = 20001001\n scale_factor = 86400 \n\nmonth = 10\nperiod = '200001010000-200912312300' #'200001010000-200912312100' #'200001010030-200912312330'\nfreq='1hr'\nmonth_dic = {\t'1':'January',\n\t\t'2':'February',\n\t\t'3':'March',\n\t\t'4':'April',\n\t\t'5':'May',\n\t\t'6':'June',\n\t\t'7':'July',\n\t\t'8':'August',\n\t\t'9':'September',\n\t\t'10':'October',\n\t\t'11':'November',\n\t\t'12':'December'\t\t}\n\nfilein = data_folder + '/' + str(exp_name) + '/' + str(freq) + '/' + str(var) + '/' + str(var) + '_' + str(exp_name) + '_' + str(freq) + '_' + str(period) + '.nc'\n#width_def = 12E5\n#height_def = 8E5\n#lat_0_def = 46.0\n#lon_0_def = 11.0\n\nwidth_def = 4E5\nheight_def = 3E5\nlat_0_def = 46.6\nlon_0_def = 11.0\n#if exp_name == '12km':\n# width_def = 12E5\n# height_def = 8E5\n# lat_0_def = 46.0\n# lon_0_def = 11.0 #14.0\n#elif exp_name == '3km':\n# width_def = 12E5\n# height_def = 8E5\n# lat_0_def = 46.0 #45.5\n# lon_0_def = 11.0 #16.0\n\n\nfig_title = \" \"\nlat_name = 'lat' #'latitude'\nlon_name = 'lon' #'longitude'\nproj_def = 'lcc' # lcc, cyl, ortho\nres_def = 'i'\nfig_type = '.png'\nlabel_def = ''\nextend_def = 'max' #'min', 'max', 'neither', 'both'\ncmap_def = 'rainbow'\n#cmap_def = 'RdBu_r'\nif 'tas' in var:\n variable_list = ['tas']\n unit = 'K'\n extend_def = 'both'\n if month >= 5 and month <= 8:\n scale_min_def = 275\n scale_max_def = 305\n else:\n scale_min_def = 255\n scale_max_def = 285\nelif var == 'pr':\n variable_list = ['pr']\n scale_min_def = 0.0\n if plot_period == '1h':\n scale_max_def = 12.0\n unit = 'mm/hour'\n elif plot_period == '1d':\n scale_max_def = 150.0\n unit = 'mm/day'\n\nnc = netCDF4.Dataset(filein)\nlat_sim = nc.variables[lat_name][:]\nlon_sim = nc.variables[lon_name][:]\nif np.array(lat_sim).ndim == 1 and np.array(lon_sim).ndim == 1: \n lon_sim_2d, lat_sim_2d = np.meshgrid(lon_sim, lat_sim)\nelif np.array(lat_sim).ndim == 2 and np.array(lon_sim).ndim == 2: \n lon_sim_2d = lon_sim\n lat_sim_2d = lat_sim\n#print nc.variables.keys()\n\n# examine the variables\nfor var_to_plot in variable_list:\n\n\t# average over all steps\n var_sim_3d = nc.variables[var_to_plot][:,:,:]\n #var_sim_2d = var_sim_3d[rec_start - 1 : rec_end - 1, :, :] * scale_factor #np.nanmean(var_sim_3d, axis=0)\n var_sim_2d = np.nanmean(var_sim_3d[rec_start - 1 : rec_end - 1, :, :], axis=0) * scale_factor\n \n title_def = var_to_plot + '(' + unit + ')' \n fig_out = str(fig_out_path) + exp_name + '_' + var_to_plot + '_' + str(plot_period) + '_' + str(ymdhm) + fig_type\n\n map_plot = MapPlot(fig_out, proj_def, res_def, width_def, height_def, lat_0_def, lon_0_def)\n map_plot.Plot_2DField(lat_sim_2d, lon_sim_2d, var_sim_2d[:,:], scale_min_def, scale_max_def, title_def, label_def, cmap_def, extend_def)\n #map_plot.Plot_ortho(lat_sim_2d, lon_sim_2d, title_def)\n\n"
] | [
[
"matplotlib.pyplot.switch_backend",
"numpy.array",
"numpy.meshgrid",
"numpy.nanmean"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mdrews93/pybaseball | [
"0dab4a2a3e27dd9fa27285d63a1f6f829dfcf4c5"
] | [
"pybaseball/league_batting_stats.py"
] | [
"import requests\nimport pandas as pd\nimport datetime\nimport io\nfrom bs4 import BeautifulSoup\n\n\ndef validate_datestring(date_text):\n try:\n datetime.datetime.strptime(date_text, '%Y-%m-%d')\n except ValueError:\n raise ValueError(\"Incorrect data format, should be YYYY-MM-DD\")\n\ndef sanitize_input(start_dt, end_dt):\n # if no dates are supplied, assume they want yesterday's data\n # send a warning in case they wanted to specify\n if start_dt is None and end_dt is None:\n today = datetime.datetime.today()\n start_dt = (today - datetime.timedelta(1)).strftime(\"%Y-%m-%d\")\n end_dt = today.strftime(\"%Y-%m-%d\")\n print(\"Warning: no date range supplied. Returning yesterday's data. For a different date range, try batting_stats_range(start_dt, end_dt) or batting_stats(season).\")\n\n #if only one date is supplied, assume they only want that day's stats\n #query in this case is from date 1 to date 1\n if start_dt is None:\n start_dt = end_dt\n if end_dt is None:\n end_dt = start_dt\n #if end date occurs before start date, swap them\n if end_dt < start_dt:\n temp = start_dt\n start_dt = end_dt\n end_dt = temp\n\n # now that both dates are not None, make sure they are valid date strings\n validate_datestring(start_dt)\n validate_datestring(end_dt)\n return start_dt, end_dt\n\ndef get_soup(start_dt, end_dt):\n # get most recent standings if date not specified\n # if((start_dt is None) or (end_dt is None)):\n # print('Error: a date range needs to be specified')\n # return None\n url = \"http://www.baseball-reference.com/leagues/daily.cgi?user_team=&bust_cache=&type=b&lastndays=7&dates=fromandto&fromandto={}.{}&level=mlb&franch=&stat=&stat_value=0\".format(start_dt, end_dt)\n s = requests.get(url).content\n return BeautifulSoup(s, \"html.parser\")\n\n\ndef get_id_table(soup):\n table = soup.find_all('table')[0]\n data = []\n headings = [th.get_text() for th in table.find(\"tr\").find_all(\"th\")][1:]\n data.append(headings)\n table_body = table.find('tbody')\n rows = table_body.find_all('tr')\n for row in rows:\n cols = row.find_all('td')\n try:\n pid = cols[0][\"data-append-csv\"].split(\"=\")[-1]\n cols = [ele.text.strip() for ele in cols]\n cols[0] = pid\n data.append([ele for ele in cols])\n except:\n pass\n data = pd.DataFrame(data)\n data = data.rename(columns=data.iloc[0])\n data = data.reindex(data.index.drop(0))\n return data\n\n\ndef get_table(soup):\n table = soup.find_all('table')[0]\n data = []\n headings = [th.get_text() for th in table.find(\"tr\").find_all(\"th\")][1:]\n data.append(headings)\n table_body = table.find('tbody')\n rows = table_body.find_all('tr')\n for row in rows:\n cols = row.find_all('td')\n cols = [ele.text.strip() for ele in cols]\n data.append([ele for ele in cols])\n data = pd.DataFrame(data)\n data = data.rename(columns=data.iloc[0])\n data = data.reindex(data.index.drop(0))\n return data\n\n\ndef batting_stats_range_by_id(start_dt=None, end_dt=None):\n \"\"\"\n Get all batting stats for a set time range. This can be the past week, the\n month of August, anything. Just supply the start and end date in YYYY-MM-DD\n format.\n \"\"\"\n # make sure date inputs are valid\n start_dt, end_dt = sanitize_input(start_dt, end_dt)\n if datetime.datetime.strptime(start_dt, \"%Y-%m-%d\").year < 2008:\n raise ValueError(\"Year must be 2008 or later\")\n if datetime.datetime.strptime(end_dt, \"%Y-%m-%d\").year < 2008:\n raise ValueError(\"Year must be 2008 or later\")\n # retrieve html from baseball reference\n soup = get_soup(start_dt, end_dt)\n table = get_id_table(soup)\n table = table.dropna(how='all') # drop if all columns are NA\n # scraped data is initially in string format.\n # convert the necessary columns to numeric.\n for column in ['Age', '#days', 'G', 'PA', 'AB', 'R', 'H', '2B', '3B',\n 'HR', 'RBI', 'BB', 'IBB', 'SO', 'HBP', 'SH', 'SF', 'GDP',\n 'SB', 'CS', 'BA', 'OBP', 'SLG', 'OPS']:\n #table[column] = table[column].astype('float')\n table[column] = pd.to_numeric(table[column])\n #table['column'] = table['column'].convert_objects(convert_numeric=True)\n table = table.drop('', 1)\n return table\n\n\ndef batting_stats_range(start_dt=None, end_dt=None):\n \"\"\"\n Get all batting stats for a set time range. This can be the past week, the\n month of August, anything. Just supply the start and end date in YYYY-MM-DD\n format.\n \"\"\"\n # make sure date inputs are valid\n start_dt, end_dt = sanitize_input(start_dt, end_dt)\n if datetime.datetime.strptime(start_dt, \"%Y-%m-%d\").year < 2008:\n raise ValueError(\"Year must be 2008 or later\")\n if datetime.datetime.strptime(end_dt, \"%Y-%m-%d\").year < 2008:\n raise ValueError(\"Year must be 2008 or later\")\n # retrieve html from baseball reference\n soup = get_soup(start_dt, end_dt)\n table = get_table(soup)\n table = table.dropna(how='all') # drop if all columns are NA\n # scraped data is initially in string format.\n # convert the necessary columns to numeric.\n for column in ['Age', '#days', 'G', 'PA', 'AB', 'R', 'H', '2B', '3B',\n 'HR', 'RBI', 'BB', 'IBB', 'SO', 'HBP', 'SH', 'SF', 'GDP',\n 'SB', 'CS', 'BA', 'OBP', 'SLG', 'OPS']:\n #table[column] = table[column].astype('float')\n table[column] = pd.to_numeric(table[column])\n #table['column'] = table['column'].convert_objects(convert_numeric=True)\n table = table.drop('', 1)\n return table\n\n\ndef batting_stats_bref(season=None):\n \"\"\"\n Get all batting stats for a set season. If no argument is supplied, gives\n stats for current season to date.\n \"\"\"\n if season is None:\n season = datetime.datetime.today().strftime(\"%Y\")\n season = str(season)\n start_dt = season + '-03-01' #opening day is always late march or early april\n end_dt = season + '-11-01' #season is definitely over by November\n return(batting_stats_range(start_dt, end_dt))\n\n\ndef bwar_bat(return_all=False):\n \"\"\"\n Get data from war_daily_bat table. Returns WAR, its components, and a few other useful stats. \n To get all fields from this table, supply argument return_all=True. \n \"\"\"\n url = \"http://www.baseball-reference.com/data/war_daily_bat.txt\"\n s = requests.get(url).content\n c=pd.read_csv(io.StringIO(s.decode('utf-8')))\n if return_all:\n return c\n else:\n cols_to_keep = ['name_common', 'mlb_ID', 'player_ID', 'year_ID', 'team_ID', 'stint_ID', 'lg_ID',\n 'pitcher','G', 'PA', 'salary', 'runs_above_avg', 'runs_above_avg_off','runs_above_avg_def',\n 'WAR_rep','WAA','WAR']\n return c[cols_to_keep]"
] | [
[
"pandas.to_numeric",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
khushjammu/dqn_zoo | [
"249af96717d605cc1a62fc2b69941881c9661249"
] | [
"dqn_zoo/networks_test.py"
] | [
"# Copyright 2019 DeepMind Technologies Limited. 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 networks.\"\"\"\n\n# pylint: disable=g-bad-import-order\n\nimport haiku as hk\nimport jax\nfrom jax.config import config\nimport jax.numpy as jnp\nimport numpy as np\nimport tree\n\nfrom dqn_zoo import networks\nfrom absl.testing import absltest\n\n\ndef _sample_input(input_shape):\n return jnp.zeros((1,) + input_shape, dtype=jnp.float32)\n\n\nclass SimpleLayersTest(absltest.TestCase):\n\n def test_linear(self):\n layer = hk.transform(networks.linear(4))\n params = layer.init(jax.random.PRNGKey(1), _sample_input((3,)))\n self.assertCountEqual(['linear'], params)\n lin_params = params['linear']\n self.assertCountEqual(['w', 'b'], lin_params)\n self.assertEqual((3, 4), lin_params['w'].shape)\n self.assertEqual((4,), lin_params['b'].shape)\n\n def test_conv(self):\n layer = hk.transform(networks.conv(4, (3, 3), 2))\n params = layer.init(jax.random.PRNGKey(1), _sample_input((7, 7, 3)))\n self.assertCountEqual(['conv2_d'], params)\n conv_params = params['conv2_d']\n self.assertCountEqual(['w', 'b'], conv_params)\n self.assertEqual((3, 3, 3, 4), conv_params['w'].shape)\n self.assertEqual((4,), conv_params['b'].shape)\n\n\nclass LinearWithSharedBiasTest(absltest.TestCase):\n\n def setUp(self):\n super().setUp()\n rng_key = jax.random.PRNGKey(1)\n self.init_rng_key, self.apply_rng_key = jax.random.split(rng_key)\n self.input_shape = (4,)\n self.output_shape = (3,)\n self.weights_shape = (self.input_shape[0], self.output_shape[0])\n network_fn = networks.linear_with_shared_bias(self.output_shape[0])\n self.network = hk.transform(network_fn)\n\n def test_bias_parameter_shape(self):\n params = self.network.init(self.init_rng_key,\n _sample_input(self.input_shape))\n self.assertLen(tree.flatten(params), 2)\n\n def check_params(path, param):\n if path[-1] == 'b':\n self.assertNotEqual(self.output_shape, param.shape)\n self.assertEqual((1,), param.shape)\n elif path[-1] == 'w':\n self.assertEqual(self.weights_shape, param.shape)\n else:\n self.fail('Unexpected parameter %s.' % path)\n\n tree.map_structure_with_path(check_params, params)\n\n def test_output_shares_bias(self):\n bias = 1.23\n params = self.network.init(self.init_rng_key,\n _sample_input(self.input_shape))\n\n def replace_params(path, param):\n if path[-1] == 'b':\n return jnp.ones_like(param) * bias\n else:\n return jnp.zeros_like(param)\n\n params = tree.map_structure_with_path(replace_params, params)\n output = self.network.apply(params, self.apply_rng_key,\n jnp.zeros((1,) + self.input_shape))\n self.assertEqual((1,) + self.output_shape, output.shape)\n np.testing.assert_allclose([bias] * self.output_shape[0], list(output[0]))\n\n\nclass NoisyLinearTest(absltest.TestCase):\n\n def setUp(self):\n super().setUp()\n rng_key = jax.random.PRNGKey(1)\n self.init_rng_key, self.apply_rng_key = jax.random.split(rng_key)\n self.input_shape = (4,)\n self.output_shape = (3,)\n self.network_fn = networks.noisy_linear(self.output_shape[0], 0.1)\n self.network = hk.transform(self.network_fn)\n self.params = self.network.init(self.init_rng_key,\n _sample_input(self.input_shape))\n self.inputs = jnp.zeros((2,) + self.input_shape)\n\n def test_basic(self):\n self.network.apply(self.params, self.apply_rng_key, self.inputs)\n\n def test_error_raised_if_rng_is_not_passed_in(self):\n with self.assertRaisesRegex(ValueError, 'must be called with an RNG'):\n self.network.apply(self.params, self.inputs)\n\n def test_error_raised_if_transformed_without_rng_1(self):\n network = hk.without_apply_rng(hk.transform(self.network_fn))\n with self.assertRaisesRegex(ValueError, 'PRNGKey'):\n network.apply(self.params, self.inputs)\n\n def test_error_raised_if_transformed_without_rng_2(self):\n network = hk.without_apply_rng(hk.transform(self.network_fn))\n with self.assertRaisesRegex(TypeError, 'positional argument'):\n network.apply(self.params, self.apply_rng_key, self.inputs)\n\n def test_same_rng_produces_same_outputs(self):\n outputs_1 = self.network.apply(self.params, self.apply_rng_key, self.inputs)\n outputs_2 = self.network.apply(self.params, self.apply_rng_key, self.inputs)\n np.testing.assert_allclose(outputs_1, outputs_2)\n\n def test_different_rngs_produce_different_outputs(self):\n rng_1, rng_2 = jax.random.split(jax.random.PRNGKey(1))\n outputs_1 = self.network.apply(self.params, rng_1, self.inputs)\n outputs_2 = self.network.apply(self.params, rng_2, self.inputs)\n self.assertFalse(np.allclose(outputs_1, outputs_2))\n\n def test_number_of_params_with_bias_correct(self):\n net_fn = networks.noisy_linear(self.output_shape[0], 0.1, with_bias=True)\n network = hk.transform(net_fn)\n params = network.init(self.init_rng_key, _sample_input(self.input_shape))\n self.assertCountEqual(['mu', 'sigma'], params)\n self.assertCountEqual(['b', 'w'], params['mu'])\n self.assertCountEqual(['b', 'w'], params['sigma'])\n\n def test_number_of_params_without_bias_correct(self):\n net_fn = networks.noisy_linear(self.output_shape[0], 0.1, with_bias=False)\n network = hk.transform(net_fn)\n params = network.init(self.init_rng_key, _sample_input(self.input_shape))\n self.assertCountEqual(['mu', 'sigma'], params)\n self.assertCountEqual(['w'], params['mu'])\n self.assertCountEqual(['b', 'w'], params['sigma'])\n\n def test_sigma_params_are_constant(self):\n self.assertCountEqual(['mu', 'sigma'], self.params)\n sigma_params = self.params['sigma']\n sigma_w_values = np.unique(sigma_params['w'])\n sigma_b_values = np.unique(sigma_params['b'])\n self.assertLen(sigma_w_values, 1)\n self.assertLen(sigma_b_values, 1)\n value = 0.1 / np.sqrt(self.input_shape[0])\n self.assertAlmostEqual(value, sigma_w_values)\n self.assertAlmostEqual(value, sigma_b_values)\n\n\nif __name__ == '__main__':\n config.update('jax_numpy_rank_promotion', 'raise')\n absltest.main()\n"
] | [
[
"numpy.sqrt",
"numpy.allclose",
"numpy.unique",
"numpy.testing.assert_allclose"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
daq-tools/PyTables | [
"0949d41e611e6882a49248c6d82b1da9a994e788",
"0949d41e611e6882a49248c6d82b1da9a994e788",
"0949d41e611e6882a49248c6d82b1da9a994e788",
"0949d41e611e6882a49248c6d82b1da9a994e788"
] | [
"bench/sqlite3-search-bench.py",
"bench/keysort.py",
"tables/tests/test_attributes.py",
"tables/scripts/pttree.py"
] | [
"import os\nimport os.path\nfrom time import perf_counter as clock\nimport numpy\nimport random\n\n# in order to always generate the same random sequence\nrandom.seed(19)\n\n\ndef fill_arrays(start, stop):\n col_i = numpy.arange(start, stop, dtype=numpy.int32)\n if userandom:\n col_j = numpy.random.uniform(0, nrows, stop - start)\n else:\n col_j = numpy.array(col_i, dtype=numpy.float64)\n return col_i, col_j\n\n# Generator for ensure pytables benchmark compatibility\n\n\ndef int_generator(nrows):\n step = 1000 * 100\n j = 0\n for i in range(nrows):\n if i >= step * j:\n stop = (j + 1) * step\n if stop > nrows: # Seems unnecessary\n stop = nrows\n col_i, col_j = fill_arrays(i, stop)\n j += 1\n k = 0\n yield (col_i[k], col_j[k])\n k += 1\n\n\ndef int_generator_slow(nrows):\n for i in range(nrows):\n if userandom:\n yield (i, float(random.randint(0, nrows)))\n else:\n yield (i, float(i))\n\n\ndef open_db(filename, remove=0):\n if remove and os.path.exists(filename):\n os.remove(filename)\n con = sqlite.connect(filename)\n cur = con.cursor()\n return con, cur\n\n\ndef create_db(filename, nrows):\n con, cur = open_db(filename, remove=1)\n cur.execute(\"create table ints(i integer, j real)\")\n t1 = clock()\n # This is twice as fast as a plain loop\n cur.executemany(\"insert into ints(i,j) values (?,?)\", int_generator(nrows))\n con.commit()\n ctime = clock() - t1\n if verbose:\n print(f\"insert time: {ctime:.5f}\")\n print(f\"Krows/s: {nrows / 1000 / ctime:.5f}\")\n close_db(con, cur)\n\n\ndef index_db(filename):\n con, cur = open_db(filename)\n t1 = clock()\n cur.execute(\"create index ij on ints(j)\")\n con.commit()\n itime = clock() - t1\n if verbose:\n print(f\"index time: {itime:.5f}\")\n print(f\"Krows/s: {nrows / itime:.5f}\")\n # Close the DB\n close_db(con, cur)\n\n\ndef query_db(filename, rng):\n con, cur = open_db(filename)\n t1 = clock()\n ntimes = 10\n for i in range(ntimes):\n # between clause does not seem to take advantage of indexes\n # cur.execute(\"select j from ints where j between %s and %s\" % \\\n cur.execute(\"select i from ints where j >= %s and j <= %s\" %\n # cur.execute(\"select i from ints where i >= %s and i <=\n # %s\" %\n (rng[0] + i, rng[1] + i))\n results = cur.fetchall()\n con.commit()\n qtime = (clock() - t1) / ntimes\n if verbose:\n print(f\"query time: {qtime:.5f}\")\n print(f\"Mrows/s: {nrows / 1000 / qtime:.5f}\")\n print(results)\n close_db(con, cur)\n\n\ndef close_db(con, cur):\n cur.close()\n con.close()\n\nif __name__ == \"__main__\":\n import sys\n import getopt\n try:\n import psyco\n psyco_imported = 1\n except:\n psyco_imported = 0\n\n usage = \"\"\"usage: %s [-v] [-p] [-m] [-i] [-q] [-c] [-R range] [-n nrows] file\n -v verbose\n -p use \"psyco\" if available\n -m use random values to fill the table\n -q do query\n -c create the database\n -i index the table\n -2 use sqlite2 (default is use sqlite3)\n -R select a range in a field in the form \"start,stop\" (def \"0,10\")\n -n sets the number of rows (in krows) in each table\n \\n\"\"\" % sys.argv[0]\n\n try:\n opts, pargs = getopt.getopt(sys.argv[1:], 'vpmiqc2R:n:')\n except:\n sys.stderr.write(usage)\n sys.exit(0)\n\n # default options\n verbose = 0\n usepsyco = 0\n userandom = 0\n docreate = 0\n createindex = 0\n doquery = 0\n sqlite_version = \"3\"\n rng = [0, 10]\n nrows = 1\n\n # Get the options\n for option in opts:\n if option[0] == '-v':\n verbose = 1\n elif option[0] == '-p':\n usepsyco = 1\n elif option[0] == '-m':\n userandom = 1\n elif option[0] == '-i':\n createindex = 1\n elif option[0] == '-q':\n doquery = 1\n elif option[0] == '-c':\n docreate = 1\n elif option[0] == \"-2\":\n sqlite_version = \"2\"\n elif option[0] == '-R':\n rng = [int(i) for i in option[1].split(\",\")]\n elif option[0] == '-n':\n nrows = int(option[1])\n\n # Catch the hdf5 file passed as the last argument\n filename = pargs[0]\n\n if sqlite_version == \"2\":\n import sqlite\n else:\n from pysqlite2 import dbapi2 as sqlite\n\n if verbose:\n print(\"pysqlite version:\", sqlite.version)\n if userandom:\n print(\"using random values\")\n\n if docreate:\n if verbose:\n print(\"writing %s krows\" % nrows)\n if psyco_imported and usepsyco:\n psyco.bind(create_db)\n nrows *= 1000\n create_db(filename, nrows)\n\n if createindex:\n index_db(filename)\n\n if doquery:\n query_db(filename, rng)\n",
"from tables.indexesextension import keysort\nimport numpy\nfrom time import perf_counter as clock\n\nN = 1000 * 1000\nrnd = numpy.random.randint(N, size=N)\n\nfor dtype1 in ('S6', 'b1',\n 'i1', 'i2', 'i4', 'i8',\n 'u1', 'u2', 'u4', 'u8', 'f4', 'f8'):\n for dtype2 in ('u4', 'i8'):\n print(\"dtype array1, array2-->\", dtype1, dtype2)\n a = numpy.array(rnd, dtype1)\n b = numpy.arange(N, dtype=dtype2)\n c = a.copy()\n\n t1 = clock()\n d = c.argsort()\n # c.sort()\n # e=c\n e = c[d]\n f = b[d]\n tref = clock() - t1\n print(\"normal sort time-->\", tref)\n\n t1 = clock()\n keysort(a, b)\n tks = clock() - t1\n print(\"keysort time-->\", tks, \" {:.2f}x\".format(tref / tks))\n assert numpy.alltrue(a == e)\n #assert numpy.alltrue(b == d)\n assert numpy.alltrue(f == d)\n",
"\"\"\"This test unit checks node attributes that are persistent (AttributeSet).\"\"\"\n\nimport sys\nimport datetime\nimport warnings\nfrom distutils.version import LooseVersion\n\nimport numpy\nfrom numpy.testing import assert_array_equal, assert_almost_equal\n\nimport tables\nfrom tables import (IsDescription, Int32Atom, StringCol, IntCol, Int16Col,\n FloatCol, Float32Col)\nfrom tables.exceptions import DataTypeWarning\nfrom tables.parameters import NODE_CACHE_SLOTS\nfrom tables.tests import common\nfrom tables.tests.common import unittest, test_filename\nfrom tables.tests.common import PyTablesTestCase as TestCase\n\n\nclass Record(IsDescription):\n var1 = StringCol(itemsize=4) # 4-character String\n var2 = IntCol() # integer\n var3 = Int16Col() # short integer\n var4 = FloatCol() # double (double-precision)\n var5 = Float32Col() # float (single-precision)\n\n\nclass CreateTestCase(common.TempFileMixin, TestCase):\n def setUp(self):\n super().setUp()\n self.root = self.h5file.root\n\n # Create a table object\n self.table = self.h5file.create_table(self.root, 'atable',\n Record, \"Table title\")\n # Create an array object\n self.array = self.h5file.create_array(self.root, 'anarray',\n [1], \"Array title\")\n # Create a group object\n self.group = self.h5file.create_group(self.root, 'agroup',\n \"Group title\")\n\n def test01_setAttributes(self):\n \"\"\"Checking setting large string attributes (File methods)\"\"\"\n\n attrlength = 2048\n # Try to put a long string attribute on a group object\n self.h5file.set_node_attr(self.root.agroup, \"attr1\", \"p\" * attrlength)\n\n # Now, try with a Table object\n self.h5file.set_node_attr(self.root.atable, \"attr1\", \"a\" * attrlength)\n\n # Finally, try with an Array object\n self.h5file.set_node_attr(self.root.anarray, \"attr1\", \"n\" * attrlength)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+', node_cache_slots=self.node_cache_slots)\n self.root = self.h5file.root\n\n self.assertEqual(self.h5file.get_node_attr(self.root.agroup, 'attr1'),\n \"p\" * attrlength)\n self.assertEqual(self.h5file.get_node_attr(self.root.atable, 'attr1'),\n \"a\" * attrlength)\n self.assertEqual(self.h5file.get_node_attr(self.root.anarray, 'attr1'),\n \"n\" * attrlength)\n\n def reopen(self):\n # Reopen\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+', node_cache_slots=self.node_cache_slots)\n self.root = self.h5file.root\n\n def check_missing(self,name):\n self.reopen()\n self.assertNotIn(name, self.root.agroup._v_attrs)\n self.assertNotIn(name, self.root.atable.attrs)\n self.assertNotIn(name, self.root.anarray.attrs)\n\n\n def check_name(self, name, val = ''):\n \"\"\"Check validity of attribute name filtering\"\"\"\n self.check_missing(name)\n # Using File methods\n self.h5file.set_node_attr(self.root.agroup, name, val)\n self.h5file.set_node_attr(self.root.atable, name, val)\n self.h5file.set_node_attr(self.root.anarray, name, val)\n # Check File methods\n self.reopen()\n self.assertEqual(self.h5file.get_node_attr(self.root.agroup, name),val)\n self.assertEqual(self.h5file.get_node_attr(self.root.atable, name),val)\n self.assertEqual(self.h5file.get_node_attr(self.root.anarray, name),val)\n # Remove, file methods\n self.h5file.del_node_attr(self.root.agroup, name)\n self.h5file.del_node_attr(self.root.atable, name)\n self.h5file.del_node_attr(self.root.anarray, name)\n self.check_missing(name)\n\n # Using Node methods\n self.root.agroup._f_setattr(name, val)\n self.root.atable.set_attr(name, val)\n self.root.anarray.set_attr(name, val)\n # Check Node methods\n self.reopen()\n self.assertEqual(self.root.agroup._f_getattr(name), val)\n self.assertEqual(self.root.atable.get_attr(name), val)\n self.assertEqual(self.root.anarray.get_attr(name), val)\n self.root.agroup._f_delattr(name)\n self.root.atable.del_attr(name)\n self.root.anarray.del_attr(name)\n self.check_missing(name)\n\n # Using AttributeSet methods\n setattr(self.root.agroup._v_attrs, name, val)\n setattr(self.root.atable.attrs, name, val)\n setattr(self.root.anarray.attrs, name, val)\n # Check AttributeSet methods\n self.reopen()\n self.assertEqual(getattr(self.root.agroup._v_attrs, name), val)\n self.assertEqual(getattr(self.root.atable.attrs, name), val)\n self.assertEqual(getattr(self.root.anarray.attrs, name), val)\n delattr(self.root.agroup._v_attrs,name)\n delattr(self.root.atable.attrs, name)\n delattr(self.root.anarray.attrs, name)\n self.check_missing(name)\n\n # Using dict []\n self.root.agroup._v_attrs[name]=val\n self.root.atable.attrs[name]=val\n self.root.anarray.attrs[name]=val\n # Check dict []\n self.reopen()\n self.assertEqual(self.root.agroup._v_attrs[name], val)\n self.assertEqual(self.root.atable.attrs[name], val)\n self.assertEqual(self.root.anarray.attrs[name], val)\n del self.root.agroup._v_attrs[name]\n del self.root.atable.attrs[name]\n del self.root.anarray.attrs[name]\n self.check_missing(name)\n\n def test01a_setAttributes(self):\n \"\"\"Checking attribute names validity\"\"\"\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', tables.NaturalNameWarning)\n self.check_name('a')\n self.check_name('a:b')\n self.check_name('/a/b')\n self.check_name('.')\n self.assertRaises(ValueError, self.check_name, '')\n self.assertRaises(ValueError, self.check_name, '__members__')\n self.assertRaises(TypeError, self.check_name, 0)\n\n def test02_setAttributes(self):\n \"\"\"Checking setting large string attributes (Node methods)\"\"\"\n\n attrlength = 2048\n # Try to put a long string attribute on a group object\n self.root.agroup._f_setattr('attr1', \"p\" * attrlength)\n # Now, try with a Table object\n self.root.atable.set_attr('attr1', \"a\" * attrlength)\n\n # Finally, try with an Array object\n self.root.anarray.set_attr('attr1', \"n\" * attrlength)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+', node_cache_slots=self.node_cache_slots)\n self.root = self.h5file.root\n\n self.assertEqual(self.root.agroup._f_getattr(\n 'attr1'), \"p\" * attrlength)\n self.assertEqual(self.root.atable.get_attr(\"attr1\"), \"a\" * attrlength)\n self.assertEqual(self.root.anarray.get_attr(\"attr1\"), \"n\" * attrlength)\n\n def test03_setAttributes(self):\n \"\"\"Checking setting large string attributes (AttributeSet methods)\"\"\"\n\n attrlength = 2048\n # Try to put a long string attribute on a group object\n self.group._v_attrs.attr1 = \"p\" * attrlength\n # Now, try with a Table object\n self.table.attrs.attr1 = \"a\" * attrlength\n # Finally, try with an Array object\n self.array.attrs.attr1 = \"n\" * attrlength\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+', node_cache_slots=self.node_cache_slots)\n self.root = self.h5file.root\n\n # This should work even when the node cache is disabled\n self.assertEqual(self.root.agroup._v_attrs.attr1, \"p\" * attrlength)\n self.assertEqual(self.root.atable.attrs.attr1, \"a\" * attrlength)\n self.assertEqual(self.root.anarray.attrs.attr1, \"n\" * attrlength)\n\n def test04_listAttributes(self):\n \"\"\"Checking listing attributes.\"\"\"\n\n # With a Group object\n self.group._v_attrs.pq = \"1\"\n self.group._v_attrs.qr = \"2\"\n self.group._v_attrs.rs = \"3\"\n if common.verbose:\n print(\"Attribute list:\", self.group._v_attrs._f_list())\n\n # Now, try with a Table object\n self.table.attrs.a = \"1\"\n self.table.attrs.c = \"2\"\n self.table.attrs.b = \"3\"\n if common.verbose:\n print(\"Attribute list:\", self.table.attrs._f_list())\n\n # Finally, try with an Array object\n self.array.attrs.k = \"1\"\n self.array.attrs.j = \"2\"\n self.array.attrs.i = \"3\"\n if common.verbose:\n print(\"Attribute list:\", self.array.attrs._f_list())\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+', node_cache_slots=self.node_cache_slots)\n self.root = self.h5file.root\n\n agroup = self.root.agroup\n self.assertEqual(agroup._v_attrs._f_list(\"user\"), [\"pq\", \"qr\", \"rs\"])\n self.assertEqual(agroup._v_attrs._f_list(\"sys\"),\n ['CLASS', 'TITLE', 'VERSION'])\n self.assertEqual(agroup._v_attrs._f_list(\"all\"),\n ['CLASS', 'TITLE', 'VERSION', \"pq\", \"qr\", \"rs\"])\n\n atable = self.root.atable\n self.assertEqual(atable.attrs._f_list(), [\"a\", \"b\", \"c\"])\n self.assertEqual(atable.attrs._f_list(\"sys\"),\n ['CLASS',\n 'FIELD_0_FILL', 'FIELD_0_NAME',\n 'FIELD_1_FILL', 'FIELD_1_NAME',\n 'FIELD_2_FILL', 'FIELD_2_NAME',\n 'FIELD_3_FILL', 'FIELD_3_NAME',\n 'FIELD_4_FILL', 'FIELD_4_NAME',\n 'NROWS',\n 'TITLE', 'VERSION'])\n self.assertEqual(atable.attrs._f_list(\"all\"),\n ['CLASS',\n 'FIELD_0_FILL', 'FIELD_0_NAME',\n 'FIELD_1_FILL', 'FIELD_1_NAME',\n 'FIELD_2_FILL', 'FIELD_2_NAME',\n 'FIELD_3_FILL', 'FIELD_3_NAME',\n 'FIELD_4_FILL', 'FIELD_4_NAME',\n 'NROWS',\n 'TITLE', 'VERSION',\n \"a\", \"b\", \"c\"])\n\n anarray = self.root.anarray\n self.assertEqual(anarray.attrs._f_list(), [\"i\", \"j\", \"k\"])\n self.assertEqual(\n anarray.attrs._f_list(\"sys\"),\n ['CLASS', 'FLAVOR', 'TITLE', 'VERSION'])\n self.assertEqual(\n anarray.attrs._f_list(\"all\"),\n ['CLASS', 'FLAVOR', 'TITLE', 'VERSION', \"i\", \"j\", \"k\"])\n\n def test05_removeAttributes(self):\n \"\"\"Checking removing attributes.\"\"\"\n\n # With a Group object\n self.group._v_attrs.pq = \"1\"\n self.group._v_attrs.qr = \"2\"\n self.group._v_attrs.rs = \"3\"\n # delete an attribute\n del self.group._v_attrs.pq\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+', node_cache_slots=self.node_cache_slots)\n self.root = self.h5file.root\n\n agroup = self.root.agroup\n if common.verbose:\n print(\"Attribute list:\", agroup._v_attrs._f_list())\n # Check the local attributes names\n self.assertEqual(agroup._v_attrs._f_list(), [\"qr\", \"rs\"])\n if common.verbose:\n print(\"Attribute list in disk:\", agroup._v_attrs._f_list(\"all\"))\n # Check the disk attribute names\n self.assertEqual(agroup._v_attrs._f_list(\"all\"),\n ['CLASS', 'TITLE', 'VERSION', \"qr\", \"rs\"])\n\n # delete an attribute (__delattr__ method)\n del agroup._v_attrs.qr\n if common.verbose:\n print(\"Attribute list:\", agroup._v_attrs._f_list())\n # Check the local attributes names\n self.assertEqual(agroup._v_attrs._f_list(), [\"rs\"])\n if common.verbose:\n print(\"Attribute list in disk:\", agroup._v_attrs._f_list())\n # Check the disk attribute names\n self.assertEqual(agroup._v_attrs._f_list(\"all\"),\n ['CLASS', 'TITLE', 'VERSION', \"rs\"])\n\n def test05b_removeAttributes(self):\n \"\"\"Checking removing attributes (using File.del_node_attr())\"\"\"\n\n # With a Group object\n self.group._v_attrs.pq = \"1\"\n self.group._v_attrs.qr = \"2\"\n self.group._v_attrs.rs = \"3\"\n # delete an attribute\n self.h5file.del_node_attr(self.group, \"pq\")\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+', node_cache_slots=self.node_cache_slots)\n self.root = self.h5file.root\n\n agroup = self.root.agroup\n if common.verbose:\n print(\"Attribute list:\", agroup._v_attrs._f_list())\n # Check the local attributes names\n self.assertEqual(agroup._v_attrs._f_list(), [\"qr\", \"rs\"])\n if common.verbose:\n print(\"Attribute list in disk:\", agroup._v_attrs._f_list(\"all\"))\n # Check the disk attribute names\n self.assertEqual(agroup._v_attrs._f_list(\"all\"),\n ['CLASS', 'TITLE', 'VERSION', \"qr\", \"rs\"])\n\n # delete an attribute (File.del_node_attr method)\n self.h5file.del_node_attr(self.root, \"qr\", \"agroup\")\n if common.verbose:\n print(\"Attribute list:\", agroup._v_attrs._f_list())\n # Check the local attributes names\n self.assertEqual(agroup._v_attrs._f_list(), [\"rs\"])\n if common.verbose:\n print(\"Attribute list in disk:\", agroup._v_attrs._f_list())\n # Check the disk attribute names\n self.assertEqual(agroup._v_attrs._f_list(\"all\"),\n ['CLASS', 'TITLE', 'VERSION', \"rs\"])\n\n def test06_removeAttributes(self):\n \"\"\"Checking removing system attributes.\"\"\"\n\n # remove a system attribute\n if common.verbose:\n print(\"Before removing CLASS attribute\")\n print(\"System attrs:\", self.group._v_attrs._v_attrnamessys)\n del self.group._v_attrs.CLASS\n self.assertEqual(self.group._v_attrs._f_list(\"sys\"),\n ['TITLE', 'VERSION'])\n if common.verbose:\n print(\"After removing CLASS attribute\")\n print(\"System attrs:\", self.group._v_attrs._v_attrnamessys)\n\n def test07_renameAttributes(self):\n \"\"\"Checking renaming attributes.\"\"\"\n\n # With a Group object\n self.group._v_attrs.pq = \"1\"\n self.group._v_attrs.qr = \"2\"\n self.group._v_attrs.rs = \"3\"\n # rename an attribute\n self.group._v_attrs._f_rename(\"pq\", \"op\")\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+', node_cache_slots=self.node_cache_slots)\n self.root = self.h5file.root\n\n agroup = self.root.agroup\n if common.verbose:\n print(\"Attribute list:\", agroup._v_attrs._f_list())\n # Check the local attributes names (alphabetically sorted)\n self.assertEqual(agroup._v_attrs._f_list(), [\"op\", \"qr\", \"rs\"])\n if common.verbose:\n print(\"Attribute list in disk:\", agroup._v_attrs._f_list(\"all\"))\n # Check the disk attribute names (not sorted)\n self.assertEqual(agroup._v_attrs._f_list(\"all\"),\n ['CLASS', 'TITLE', 'VERSION', \"op\", \"qr\", \"rs\"])\n\n def test08_renameAttributes(self):\n \"\"\"Checking renaming system attributes.\"\"\"\n\n if common.verbose:\n print(\"Before renaming CLASS attribute\")\n print(\"All attrs:\", self.group._v_attrs._v_attrnames)\n # rename a system attribute\n self.group._v_attrs._f_rename(\"CLASS\", \"op\")\n if common.verbose:\n print(\"After renaming CLASS attribute\")\n print(\"All attrs:\", self.group._v_attrs._v_attrnames)\n\n # Check the disk attribute names (not sorted)\n agroup = self.root.agroup\n self.assertEqual(agroup._v_attrs._f_list(\"all\"),\n ['TITLE', 'VERSION', \"op\"])\n\n def test09_overwriteAttributes(self):\n \"\"\"Checking overwriting attributes.\"\"\"\n\n # With a Group object\n self.group._v_attrs.pq = \"1\"\n self.group._v_attrs.qr = \"2\"\n self.group._v_attrs.rs = \"3\"\n # overwrite attributes\n self.group._v_attrs.pq = \"4\"\n self.group._v_attrs.qr = 2\n self.group._v_attrs.rs = [1, 2, 3]\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+', node_cache_slots=self.node_cache_slots)\n self.root = self.h5file.root\n\n agroup = self.root.agroup\n if common.verbose:\n print(\"Value of Attribute pq:\", agroup._v_attrs.pq)\n # Check the local attributes names (alphabetically sorted)\n self.assertEqual(agroup._v_attrs.pq, \"4\")\n self.assertEqual(agroup._v_attrs.qr, 2)\n self.assertEqual(agroup._v_attrs.rs, [1, 2, 3])\n if common.verbose:\n print(\"Attribute list in disk:\", agroup._v_attrs._f_list(\"all\"))\n # Check the disk attribute names (not sorted)\n self.assertEqual(agroup._v_attrs._f_list(\"all\"),\n ['CLASS', 'TITLE', 'VERSION', \"pq\", \"qr\", \"rs\"])\n\n def test10a_copyAttributes(self):\n \"\"\"Checking copying attributes.\"\"\"\n\n # With a Group object\n self.group._v_attrs.pq = \"1\"\n self.group._v_attrs.qr = \"2\"\n self.group._v_attrs.rs = \"3\"\n # copy all attributes from \"/agroup\" to \"/atable\"\n self.group._v_attrs._f_copy(self.root.atable)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+', node_cache_slots=self.node_cache_slots)\n self.root = self.h5file.root\n\n atable = self.root.atable\n if common.verbose:\n print(\"Attribute list:\", atable._v_attrs._f_list())\n # Check the local attributes names (alphabetically sorted)\n self.assertEqual(atable._v_attrs._f_list(), [\"pq\", \"qr\", \"rs\"])\n if common.verbose:\n print(\"Complete attribute list:\", atable._v_attrs._f_list(\"all\"))\n # Check the disk attribute names (not sorted)\n self.assertEqual(atable._v_attrs._f_list(\"all\"),\n ['CLASS',\n 'FIELD_0_FILL', 'FIELD_0_NAME',\n 'FIELD_1_FILL', 'FIELD_1_NAME',\n 'FIELD_2_FILL', 'FIELD_2_NAME',\n 'FIELD_3_FILL', 'FIELD_3_NAME',\n 'FIELD_4_FILL', 'FIELD_4_NAME',\n 'NROWS',\n 'TITLE', 'VERSION',\n \"pq\", \"qr\", \"rs\"])\n\n def test10b_copyAttributes(self):\n \"\"\"Checking copying attributes (copy_node_attrs)\"\"\"\n\n # With a Group object\n self.group._v_attrs.pq = \"1\"\n self.group._v_attrs.qr = \"2\"\n self.group._v_attrs.rs = \"3\"\n # copy all attributes from \"/agroup\" to \"/atable\"\n self.h5file.copy_node_attrs(self.group, self.root.atable)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+', node_cache_slots=self.node_cache_slots)\n self.root = self.h5file.root\n\n atable = self.root.atable\n if common.verbose:\n print(\"Attribute list:\", atable._v_attrs._f_list())\n # Check the local attributes names (alphabetically sorted)\n self.assertEqual(atable._v_attrs._f_list(), [\"pq\", \"qr\", \"rs\"])\n if common.verbose:\n print(\"Complete attribute list:\", atable._v_attrs._f_list(\"all\"))\n # Check the disk attribute names (not sorted)\n self.assertEqual(atable._v_attrs._f_list(\"all\"),\n ['CLASS',\n 'FIELD_0_FILL', 'FIELD_0_NAME',\n 'FIELD_1_FILL', 'FIELD_1_NAME',\n 'FIELD_2_FILL', 'FIELD_2_NAME',\n 'FIELD_3_FILL', 'FIELD_3_NAME',\n 'FIELD_4_FILL', 'FIELD_4_NAME',\n 'NROWS',\n 'TITLE', 'VERSION',\n \"pq\", \"qr\", \"rs\"])\n\n def test10c_copyAttributes(self):\n \"\"\"Checking copying attributes during group copies.\"\"\"\n\n # With a Group object\n self.group._v_attrs['CLASS'] = \"GROUP2\"\n self.group._v_attrs['VERSION'] = \"1.3\"\n # copy \"/agroup\" to \"/agroup2\"\n self.h5file.copy_node(self.group, self.root, \"agroup2\")\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+', node_cache_slots=self.node_cache_slots)\n self.root = self.h5file.root\n\n agroup2 = self.root.agroup2\n if common.verbose:\n print(\"Complete attribute list:\", agroup2._v_attrs._f_list(\"all\"))\n self.assertEqual(agroup2._v_attrs['CLASS'], \"GROUP2\")\n self.assertEqual(agroup2._v_attrs['VERSION'], \"1.3\")\n\n def test10d_copyAttributes(self):\n \"\"\"Checking copying attributes during leaf copies.\"\"\"\n\n # With a Group object\n atable = self.root.atable\n atable._v_attrs['CLASS'] = \"TABLE2\"\n atable._v_attrs['VERSION'] = \"1.3\"\n # copy \"/agroup\" to \"/agroup2\"\n self.h5file.copy_node(atable, self.root, \"atable2\")\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+', node_cache_slots=self.node_cache_slots)\n self.root = self.h5file.root\n\n atable2 = self.root.atable2\n if common.verbose:\n print(\"Complete attribute list:\", atable2._v_attrs._f_list(\"all\"))\n self.assertEqual(atable2._v_attrs['CLASS'], \"TABLE2\")\n self.assertEqual(atable2._v_attrs['VERSION'], \"1.3\")\n\n def test11a_getitem(self):\n \"\"\"Checking the __getitem__ interface.\"\"\"\n\n attrs = self.group._v_attrs\n attrs.pq = \"1\"\n self.assertEqual(attrs['pq'], \"1\")\n\n def test11b_setitem(self):\n \"\"\"Checking the __setitem__ interface.\"\"\"\n\n attrs = self.group._v_attrs\n attrs['pq'] = \"2\"\n self.assertEqual(attrs['pq'], \"2\")\n\n def test11c_delitem(self):\n \"\"\"Checking the __delitem__ interface.\"\"\"\n\n attrs = self.group._v_attrs\n attrs.pq = \"1\"\n del attrs['pq']\n self.assertNotIn('pq', attrs._f_list())\n\n def test11d_KeyError(self):\n \"\"\"Checking that KeyError is raised in __getitem__/__delitem__.\"\"\"\n\n attrs = self.group._v_attrs\n self.assertRaises(KeyError, attrs.__getitem__, 'pq')\n self.assertRaises(KeyError, attrs.__delitem__, 'pq')\n\n def test_2d_non_contiguous(self):\n \"\"\"Checking setting 2D and non-contiguous NumPy attributes\"\"\"\n\n # Regression for gh-176 numpy.\n # In the views old implementation PyTAbles performa a copy of the\n # array:\n #\n # value = numpy.array(value)\n #\n # in order to get a contiguous array.\n # Unfortunately array with swapped axis are copyed as they are so\n # thay are stored in to HDF5 attributes without being actually\n # contiguous and ths causes an error whn they are restored.\n\n data = numpy.array([[0, 1], [2, 3]])\n\n self.array.attrs['a'] = data\n self.array.attrs['b'] = data.T.copy()\n self.array.attrs['c'] = data.T\n\n assert_array_equal(self.array.attrs['a'], data)\n assert_array_equal(self.array.attrs['b'], data.T)\n assert_array_equal(self.array.attrs['c'], data.T) # AssertionError!\n\n def test12_dir(self):\n \"\"\"Checking AttributeSet.__dir__\"\"\"\n\n if common.verbose:\n print('\\n', '-=' * 30)\n print(\"Running %s.test12_dir...\" % self.__class__.__name__)\n\n attrset = self.group._v_attrs\n\n user_attr = 'good_attr'\n sys_attr = 'BETTER_ATTR'\n for a in [user_attr, sys_attr]:\n attrset[a] = 1\n\n bad_user = '5bad'\n bad_sys = 'SYS%'\n for a in [bad_user, bad_sys]:\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', tables.NaturalNameWarning)\n attrset[a] = 1\n\n completions = dir(attrset)\n\n ## Check some regular attributes.\n #\n self.assertIn('__class__', completions)\n self.assertIn('_f_copy', completions)\n self.assertEqual(completions.count('_f_copy'), 1)\n\n ## Check SYS attrs.\n #\n self.assertNotIn(bad_sys, completions)\n self.assertIn(sys_attr, completions)\n self.assertEqual(completions.count(sys_attr), 1)\n\n ## Check USER attrs.\n #\n self.assertIn(user_attr, completions)\n self.assertNotIn(bad_user, completions)\n self.assertEqual(completions.count(user_attr), 1)\n\n # Now check all for no duplicates.\n self.assertSequenceEqual(sorted(set(completions)),\n sorted(completions))\n\n\nclass NotCloseCreate(CreateTestCase):\n close = False\n node_cache_slots = NODE_CACHE_SLOTS\n open_kwargs = dict(node_cache_slots=node_cache_slots)\n\n\nclass CloseCreate(CreateTestCase):\n close = True\n node_cache_slots = NODE_CACHE_SLOTS\n open_kwargs = dict(node_cache_slots=node_cache_slots)\n\n\nclass NoCacheNotCloseCreate(CreateTestCase):\n close = False\n node_cache_slots = 0\n open_kwargs = dict(node_cache_slots=node_cache_slots)\n\n\nclass NoCacheCloseCreate(CreateTestCase):\n close = True\n node_cache_slots = 0\n open_kwargs = dict(node_cache_slots=node_cache_slots)\n\n\nclass DictCacheNotCloseCreate(CreateTestCase):\n close = False\n node_cache_slots = -NODE_CACHE_SLOTS\n open_kwargs = dict(node_cache_slots=node_cache_slots)\n\n\nclass DictCacheCloseCreate(CreateTestCase):\n close = True\n node_cache_slots = -NODE_CACHE_SLOTS\n open_kwargs = dict(node_cache_slots=node_cache_slots)\n\n\nclass TypesTestCase(common.TempFileMixin, TestCase):\n\n def setUp(self):\n self.open_kwargs = {'allow_padding': self.allow_padding}\n super().setUp()\n self.root = self.h5file.root\n\n # Create an array object\n self.array = self.h5file.create_array(self.root, 'anarray',\n [1], \"Array title\")\n # Create a group object\n self.group = self.h5file.create_group(self.root, 'agroup',\n \"Group title\")\n\n def test00a_setBoolAttributes(self):\n \"\"\"Checking setting Bool attributes (scalar, Python case)\"\"\"\n\n self.array.attrs.pq = True\n self.array.attrs.qr = False\n self.array.attrs.rs = True\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n print(\"qr -->\", self.array.attrs.qr)\n print(\"rs -->\", self.array.attrs.rs)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n self.assertEqual(self.root.anarray.attrs.pq, True)\n self.assertEqual(self.root.anarray.attrs.qr, False)\n self.assertEqual(self.root.anarray.attrs.rs, True)\n\n def test00b_setBoolAttributes(self):\n \"\"\"Checking setting Bool attributes (scalar, NumPy case)\"\"\"\n\n self.array.attrs.pq = numpy.bool_(True)\n self.array.attrs.qr = numpy.bool_(False)\n self.array.attrs.rs = numpy.bool_(True)\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n print(\"qr -->\", self.array.attrs.qr)\n print(\"rs -->\", self.array.attrs.rs)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n self.assertIsInstance(self.root.anarray.attrs.pq, numpy.bool_)\n self.assertIsInstance(self.root.anarray.attrs.qr, numpy.bool_)\n self.assertIsInstance(self.root.anarray.attrs.rs, numpy.bool_)\n self.assertEqual(self.root.anarray.attrs.pq, True)\n self.assertEqual(self.root.anarray.attrs.qr, False)\n self.assertEqual(self.root.anarray.attrs.rs, True)\n\n def test00c_setBoolAttributes(self):\n \"\"\"Checking setting Bool attributes (NumPy, 0-dim case)\"\"\"\n\n self.array.attrs.pq = numpy.array(True)\n self.array.attrs.qr = numpy.array(False)\n self.array.attrs.rs = numpy.array(True)\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n print(\"qr -->\", self.array.attrs.qr)\n print(\"rs -->\", self.array.attrs.rs)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n self.assertEqual(self.root.anarray.attrs.pq, True)\n self.assertEqual(self.root.anarray.attrs.qr, False)\n self.assertEqual(self.root.anarray.attrs.rs, True)\n\n def test00d_setBoolAttributes(self):\n \"\"\"Checking setting Bool attributes (NumPy, multidim case)\"\"\"\n\n self.array.attrs.pq = numpy.array([True])\n self.array.attrs.qr = numpy.array([[False]])\n self.array.attrs.rs = numpy.array([[True, False], [True, False]])\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n print(\"qr -->\", self.array.attrs.qr)\n print(\"rs -->\", self.array.attrs.rs)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n assert_array_equal(self.root.anarray.attrs.pq, numpy.array([True]))\n assert_array_equal(self.root.anarray.attrs.qr, numpy.array([[False]]))\n assert_array_equal(self.root.anarray.attrs.rs,\n numpy.array([[True, False], [True, False]]))\n\n def test01a_setIntAttributes(self):\n \"\"\"Checking setting Int attributes (scalar, Python case)\"\"\"\n\n self.array.attrs.pq = 1\n self.array.attrs.qr = 2\n self.array.attrs.rs = 3\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n print(\"qr -->\", self.array.attrs.qr)\n print(\"rs -->\", self.array.attrs.rs)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n self.assertIsInstance(self.root.anarray.attrs.pq, numpy.int_)\n self.assertIsInstance(self.root.anarray.attrs.qr, numpy.int_)\n self.assertIsInstance(self.root.anarray.attrs.rs, numpy.int_)\n self.assertEqual(self.root.anarray.attrs.pq, 1)\n self.assertEqual(self.root.anarray.attrs.qr, 2)\n self.assertEqual(self.root.anarray.attrs.rs, 3)\n\n def test01b_setIntAttributes(self):\n \"\"\"Checking setting Int attributes (scalar, NumPy case)\"\"\"\n\n # 'UInt64' not supported on Win\n checktypes = ['int8', 'int16', 'int32', 'int64',\n 'uint8', 'uint16', 'uint32']\n\n for dtype in checktypes:\n setattr(self.array.attrs, dtype, numpy.array(1, dtype=dtype))\n\n # Check the results\n if common.verbose:\n for dtype in checktypes:\n print(\"type, value-->\", dtype,\n getattr(self.array.attrs, dtype))\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n for dtype in checktypes:\n assert_array_equal(getattr(self.array.attrs, dtype),\n numpy.array(1, dtype=dtype))\n\n def test01c_setIntAttributes(self):\n \"\"\"Checking setting Int attributes (unidimensional NumPy case)\"\"\"\n\n # 'UInt64' not supported on Win\n checktypes = ['int8', 'int16', 'int32', 'int64',\n 'uint8', 'uint16', 'uint32']\n\n for dtype in checktypes:\n setattr(self.array.attrs, dtype, numpy.array([1, 2], dtype=dtype))\n\n # Check the results\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n for dtype in checktypes:\n if common.verbose:\n print(\"type, value-->\", dtype,\n getattr(self.array.attrs, dtype))\n assert_array_equal(getattr(self.array.attrs, dtype),\n numpy.array([1, 2], dtype=dtype))\n\n def test01d_setIntAttributes(self):\n \"\"\"Checking setting Int attributes (unidimensional, non-contiguous)\"\"\"\n\n # 'UInt64' not supported on Win\n checktypes = ['int8', 'int16', 'int32', 'int64',\n 'uint8', 'uint16', 'uint32']\n\n for dtype in checktypes:\n arr = numpy.array([1, 2, 3, 4], dtype=dtype)[::2]\n setattr(self.array.attrs, dtype, arr)\n\n # Check the results\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n for dtype in checktypes:\n arr = numpy.array([1, 2, 3, 4], dtype=dtype)[::2]\n if common.verbose:\n print(\"type, value-->\", dtype,\n getattr(self.array.attrs, dtype))\n assert_array_equal(getattr(self.array.attrs, dtype), arr)\n\n def test01e_setIntAttributes(self):\n \"\"\"Checking setting Int attributes (bidimensional NumPy case)\"\"\"\n\n # 'UInt64' not supported on Win\n checktypes = ['int8', 'int16', 'int32', 'int64',\n 'uint8', 'uint16', 'uint32']\n\n for dtype in checktypes:\n setattr(self.array.attrs, dtype,\n numpy.array([[1, 2], [2, 3]], dtype=dtype))\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n # Check the results\n for dtype in checktypes:\n if common.verbose:\n print(\"type, value-->\", dtype,\n getattr(self.array.attrs, dtype))\n assert_array_equal(getattr(self.array.attrs, dtype),\n numpy.array([[1, 2], [2, 3]], dtype=dtype))\n\n def test02a_setFloatAttributes(self):\n \"\"\"Checking setting Float (double) attributes.\"\"\"\n\n # Set some attrs\n self.array.attrs.pq = 1.0\n self.array.attrs.qr = 2.0\n self.array.attrs.rs = 3.0\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n print(\"qr -->\", self.array.attrs.qr)\n print(\"rs -->\", self.array.attrs.rs)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n self.assertIsInstance(self.root.anarray.attrs.pq, numpy.float_)\n self.assertIsInstance(self.root.anarray.attrs.qr, numpy.float_)\n self.assertIsInstance(self.root.anarray.attrs.rs, numpy.float_)\n self.assertEqual(self.root.anarray.attrs.pq, 1.0)\n self.assertEqual(self.root.anarray.attrs.qr, 2.0)\n self.assertEqual(self.root.anarray.attrs.rs, 3.0)\n\n def test02b_setFloatAttributes(self):\n \"\"\"Checking setting Float attributes (scalar, NumPy case)\"\"\"\n\n checktypes = ['float32', 'float64']\n\n for dtype in checktypes:\n setattr(self.array.attrs, dtype,\n numpy.array(1.1, dtype=dtype))\n\n # Check the results\n if common.verbose:\n for dtype in checktypes:\n print(\"type, value-->\", dtype,\n getattr(self.array.attrs, dtype))\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n for dtype in checktypes:\n # assert getattr(self.array.attrs, dtype) == 1.1\n # In order to make Float32 tests pass. This is legal, not a trick.\n assert_almost_equal(getattr(self.array.attrs, dtype), 1.1)\n\n def test02c_setFloatAttributes(self):\n \"\"\"Checking setting Float attributes (unidimensional NumPy case)\"\"\"\n\n checktypes = ['float32', 'float64']\n\n for dtype in checktypes:\n setattr(self.array.attrs, dtype,\n numpy.array([1.1, 2.1], dtype=dtype))\n\n # Check the results\n if common.verbose:\n for dtype in checktypes:\n print(\"type, value-->\", dtype,\n getattr(self.array.attrs, dtype))\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n for dtype in checktypes:\n assert_array_equal(getattr(self.array.attrs, dtype),\n numpy.array([1.1, 2.1], dtype=dtype))\n\n def test02d_setFloatAttributes(self):\n \"\"\"Checking setting Float attributes (unidimensional,\n non-contiguous)\"\"\"\n\n checktypes = ['float32', 'float64']\n\n for dtype in checktypes:\n arr = numpy.array([1.1, 2.1, 3.1, 4.1], dtype=dtype)[1::2]\n setattr(self.array.attrs, dtype, arr)\n\n # Check the results\n if common.verbose:\n for dtype in checktypes:\n print(\"type, value-->\", dtype,\n getattr(self.array.attrs, dtype))\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n for dtype in checktypes:\n arr = numpy.array([1.1, 2.1, 3.1, 4.1], dtype=dtype)[1::2]\n assert_array_equal(getattr(self.array.attrs, dtype), arr)\n\n def test02e_setFloatAttributes(self):\n \"\"\"Checking setting Int attributes (bidimensional NumPy case)\"\"\"\n\n checktypes = ['float32', 'float64']\n\n for dtype in checktypes:\n setattr(self.array.attrs, dtype,\n numpy.array([[1.1, 2.1], [2.1, 3.1]], dtype=dtype))\n\n # Check the results\n if common.verbose:\n for dtype in checktypes:\n print(\"type, value-->\", dtype,\n getattr(self.array.attrs, dtype))\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n for dtype in checktypes:\n assert_array_equal(\n getattr(self.array.attrs, dtype),\n numpy.array([[1.1, 2.1], [2.1, 3.1]], dtype=dtype))\n\n def test03_setObjectAttributes(self):\n \"\"\"Checking setting Object attributes.\"\"\"\n\n # Set some attrs\n self.array.attrs.pq = [1.0, 2]\n self.array.attrs.qr = (1, 2)\n self.array.attrs.rs = {\"ddf\": 32.1, \"dsd\": 1}\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n print(\"qr -->\", self.array.attrs.qr)\n print(\"rs -->\", self.array.attrs.rs)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n self.assertEqual(self.root.anarray.attrs.pq, [1.0, 2])\n self.assertEqual(self.root.anarray.attrs.qr, (1, 2))\n self.assertEqual(self.root.anarray.attrs.rs, {\"ddf\": 32.1, \"dsd\": 1})\n\n def test04a_setStringAttributes(self):\n \"\"\"Checking setting string attributes (scalar case)\"\"\"\n\n self.array.attrs.pq = 'foo'\n self.array.attrs.qr = 'bar'\n self.array.attrs.rs = 'baz'\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n print(\"qr -->\", self.array.attrs.qr)\n print(\"rs -->\", self.array.attrs.rs)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n self.assertIsInstance(self.root.anarray.attrs.pq, numpy.str_)\n self.assertIsInstance(self.root.anarray.attrs.qr, numpy.str_)\n self.assertIsInstance(self.root.anarray.attrs.rs, numpy.str_)\n self.assertEqual(self.root.anarray.attrs.pq, 'foo')\n self.assertEqual(self.root.anarray.attrs.qr, 'bar')\n self.assertEqual(self.root.anarray.attrs.rs, 'baz')\n\n def test04b_setStringAttributes(self):\n \"\"\"Checking setting string attributes (unidimensional 1-elem case)\"\"\"\n\n self.array.attrs.pq = numpy.array(['foo'])\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n assert_array_equal(self.root.anarray.attrs.pq, numpy.array(['foo']))\n\n def test04c_setStringAttributes(self):\n \"\"\"Checking setting string attributes (empty unidimensional\n 1-elem case)\"\"\"\n\n self.array.attrs.pq = numpy.array([''])\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n\n assert_array_equal(self.root.anarray.attrs.pq,\n numpy.array(['']))\n\n def test04d_setStringAttributes(self):\n \"\"\"Checking setting string attributes (unidimensional 2-elem case)\"\"\"\n\n self.array.attrs.pq = numpy.array(['foo', 'bar3'])\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n assert_array_equal(self.root.anarray.attrs.pq,\n numpy.array(['foo', 'bar3']))\n\n def test04e_setStringAttributes(self):\n \"\"\"Checking setting string attributes (empty unidimensional\n 2-elem case)\"\"\"\n\n self.array.attrs.pq = numpy.array(['', ''])\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n assert_array_equal(self.root.anarray.attrs.pq, numpy.array(['', '']))\n\n def test04f_setStringAttributes(self):\n \"\"\"Checking setting string attributes (bidimensional 4-elem case)\"\"\"\n\n self.array.attrs.pq = numpy.array([['foo', 'foo2'],\n ['foo3', 'foo4']])\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n assert_array_equal(self.root.anarray.attrs.pq,\n numpy.array([['foo', 'foo2'],\n ['foo3', 'foo4']]))\n\n def test05a_setComplexAttributes(self):\n \"\"\"Checking setting Complex (python) attributes.\"\"\"\n\n # Set some attrs\n self.array.attrs.pq = 1.0 + 2j\n self.array.attrs.qr = 2.0 + 3j\n self.array.attrs.rs = 3.0 + 4j\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n print(\"qr -->\", self.array.attrs.qr)\n print(\"rs -->\", self.array.attrs.rs)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n self.assertIsInstance(self.root.anarray.attrs.pq, numpy.complex_)\n self.assertIsInstance(self.root.anarray.attrs.qr, numpy.complex_)\n self.assertIsInstance(self.root.anarray.attrs.rs, numpy.complex_)\n self.assertEqual(self.root.anarray.attrs.pq, 1.0 + 2j)\n self.assertEqual(self.root.anarray.attrs.qr, 2.0 + 3j)\n self.assertEqual(self.root.anarray.attrs.rs, 3.0 + 4j)\n\n def test05b_setComplexAttributes(self):\n \"\"\"Checking setting Complex attributes (scalar, NumPy case)\"\"\"\n\n checktypes = ['complex64', 'complex128']\n\n for dtype in checktypes:\n setattr(self.array.attrs, dtype,\n numpy.array(1.1 + 2j, dtype=dtype))\n\n # Check the results\n if common.verbose:\n for dtype in checktypes:\n print(\"type, value-->\", dtype,\n getattr(self.array.attrs, dtype))\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n for dtype in checktypes:\n # assert getattr(self.array.attrs, dtype) == 1.1 + 2j\n # In order to make Complex32 tests pass.\n assert_almost_equal(getattr(self.array.attrs, dtype), 1.1 + 2j)\n\n def test05c_setComplexAttributes(self):\n \"\"\"Checking setting Complex attributes (unidimensional NumPy case)\"\"\"\n\n checktypes = ['complex64', 'complex128']\n\n for dtype in checktypes:\n setattr(self.array.attrs, dtype,\n numpy.array([1.1, 2.1], dtype=dtype))\n\n # Check the results\n if common.verbose:\n for dtype in checktypes:\n print(\"type, value-->\", dtype,\n getattr(self.array.attrs, dtype))\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n for dtype in checktypes:\n assert_array_equal(getattr(self.array.attrs, dtype),\n numpy.array([1.1, 2.1], dtype=dtype))\n\n def test05d_setComplexAttributes(self):\n \"\"\"Checking setting Int attributes (bidimensional NumPy case)\"\"\"\n\n checktypes = ['complex64', 'complex128']\n\n for dtype in checktypes:\n setattr(self.array.attrs, dtype,\n numpy.array([[1.1, 2.1], [2.1, 3.1]], dtype=dtype))\n\n # Check the results\n if common.verbose:\n for dtype in checktypes:\n print(\"type, value-->\",\n dtype, getattr(self.array.attrs, dtype))\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n for dtype in checktypes:\n assert_array_equal(\n getattr(self.array.attrs, dtype),\n numpy.array([[1.1, 2.1], [2.1, 3.1]], dtype=dtype))\n\n def test06a_setUnicodeAttributes(self):\n \"\"\"Checking setting unicode attributes (scalar case)\"\"\"\n\n self.array.attrs.pq = 'para\\u0140lel'\n self.array.attrs.qr = '' # check #213 or gh-64\n self.array.attrs.rs = 'baz'\n\n # Check the results\n if common.verbose:\n if sys.platform != 'win32':\n # It seems that Windows cannot print this\n print(\"pq -->\", repr(self.array.attrs.pq))\n # XXX: try to use repr instead\n # print(\"pq -->\", repr(self.array.attrs.pq))\n print(\"qr -->\", self.array.attrs.qr)\n print(\"rs -->\", self.array.attrs.rs)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n self.assertIsInstance(self.array.attrs.pq, numpy.unicode_)\n self.assertIsInstance(self.array.attrs.qr, numpy.unicode_)\n self.assertIsInstance(self.array.attrs.rs, numpy.unicode_)\n self.assertEqual(self.array.attrs.pq, 'para\\u0140lel')\n self.assertEqual(self.array.attrs.qr, '')\n self.assertEqual(self.array.attrs.rs, 'baz')\n\n def test06b_setUnicodeAttributes(self):\n \"\"\"Checking setting unicode attributes (unidimensional 1-elem case)\"\"\"\n\n self.array.attrs.pq = numpy.array(['para\\u0140lel'])\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n assert_array_equal(self.array.attrs.pq,\n numpy.array(['para\\u0140lel']))\n\n def test06c_setUnicodeAttributes(self):\n \"\"\"Checking setting unicode attributes (empty unidimensional\n 1-elem case)\"\"\"\n\n # The next raises a `TypeError` when unpickled. See:\n # http://projects.scipy.org/numpy/ticket/1037\n # self.array.attrs.pq = numpy.array([''])\n self.array.attrs.pq = numpy.array([''], dtype=\"U1\")\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n if common.verbose:\n print(\"pq -->\", repr(self.array.attrs.pq))\n\n assert_array_equal(self.array.attrs.pq,\n numpy.array([''], dtype=\"U1\"))\n\n def test06d_setUnicodeAttributes(self):\n \"\"\"Checking setting unicode attributes (unidimensional 2-elem case)\"\"\"\n\n self.array.attrs.pq = numpy.array(['para\\u0140lel', 'bar3'])\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n assert_array_equal(self.array.attrs.pq,\n numpy.array(['para\\u0140lel', 'bar3']))\n\n def test06e_setUnicodeAttributes(self):\n \"\"\"Checking setting unicode attributes (empty unidimensional\n 2-elem case)\"\"\"\n\n self.array.attrs.pq = numpy.array(['', ''], dtype=\"U1\")\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n assert_array_equal(self.array.attrs.pq,\n numpy.array(['', ''], dtype=\"U1\"))\n\n def test06f_setUnicodeAttributes(self):\n \"\"\"Checking setting unicode attributes (bidimensional 4-elem case)\"\"\"\n\n self.array.attrs.pq = numpy.array([['para\\u0140lel', 'foo2'],\n ['foo3', 'para\\u0140lel4']])\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n assert_array_equal(self.array.attrs.pq,\n numpy.array([['para\\u0140lel', 'foo2'],\n ['foo3', 'para\\u0140lel4']]))\n\n def test07a_setRecArrayAttributes(self):\n \"\"\"Checking setting RecArray (NumPy) attributes.\"\"\"\n\n dt = numpy.dtype('i4,f8', align=self.aligned)\n # Set some attrs\n self.array.attrs.pq = numpy.zeros(2, dt)\n self.array.attrs.qr = numpy.ones((2, 2), dt)\n self.array.attrs.rs = numpy.array([(1, 2.)], dt)\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n print(\"qr -->\", self.array.attrs.qr)\n print(\"rs -->\", self.array.attrs.rs)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n self.assertIsInstance(self.array.attrs.pq, numpy.ndarray)\n self.assertIsInstance(self.array.attrs.qr, numpy.ndarray)\n self.assertIsInstance(self.array.attrs.rs, numpy.ndarray)\n assert_array_equal(self.array.attrs.pq, numpy.zeros(2, dt))\n assert_array_equal(self.array.attrs.qr, numpy.ones((2, 2), dt))\n assert_array_equal(self.array.attrs.rs, numpy.array([(1, 2.)], dt))\n\n def test07b_setRecArrayAttributes(self):\n \"\"\"Checking setting nested RecArray (NumPy) attributes.\"\"\"\n\n # Build a nested dtype\n dt = numpy.dtype([('f1', [('f1', 'i2'), ('f2', 'f8')])])\n # Set some attrs\n self.array.attrs.pq = numpy.zeros(2, dt)\n self.array.attrs.qr = numpy.ones((2, 2), dt)\n self.array.attrs.rs = numpy.array([((1, 2.),)], dt)\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n print(\"qr -->\", self.array.attrs.qr)\n print(\"rs -->\", self.array.attrs.rs)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n self.assertIsInstance(self.array.attrs.pq, numpy.ndarray)\n self.assertIsInstance(self.array.attrs.qr, numpy.ndarray)\n self.assertIsInstance(self.array.attrs.rs, numpy.ndarray)\n assert_array_equal(self.array.attrs.pq, numpy.zeros(2, dt))\n assert_array_equal(self.array.attrs.qr, numpy.ones((2, 2), dt))\n assert_array_equal(self.array.attrs.rs, numpy.array([((1, 2),)], dt))\n\n def test07c_setRecArrayAttributes(self):\n \"\"\"Checking setting multidim nested RecArray (NumPy) attributes.\"\"\"\n\n # Build a nested dtype\n dt = numpy.dtype([('f1', [('f1', 'i2', (2,)), ('f2', 'f8')])], align=True)\n\n # Set some attrs\n self.array.attrs.pq = numpy.zeros(2, dt)\n self.array.attrs.qr = numpy.ones((2, 2), dt)\n self.array.attrs.rs = numpy.array([(([1, 3], 2.),)], dt)\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n print(\"qr -->\", self.array.attrs.qr)\n print(\"rs -->\", self.array.attrs.rs)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n self.assertIsInstance(self.array.attrs.pq, numpy.ndarray)\n self.assertIsInstance(self.array.attrs.qr, numpy.ndarray)\n self.assertIsInstance(self.array.attrs.rs, numpy.ndarray)\n assert_array_equal(self.array.attrs.pq, numpy.zeros(2, dt))\n assert_array_equal(self.array.attrs.qr, numpy.ones((2, 2), dt))\n assert_array_equal(self.array.attrs.rs, numpy.array(\n [(([1, 3], 2),)], dt))\n\n def test08_setRecArrayNotAllowPadding(self):\n \"\"\"Checking setting aligned RecArray (NumPy) attributes with `allow_aligned` param set to False when reopen.\"\"\"\n\n dt = numpy.dtype('i4,f8', align=self.aligned)\n # Set some attrs\n self.array.attrs.pq = numpy.zeros(2, dt)\n self.array.attrs.qr = numpy.ones((2, 2), dt)\n self.array.attrs.rs = numpy.array([(1, 2.)], dt)\n\n # Check the results\n if common.verbose:\n print(\"pq -->\", self.array.attrs.pq)\n print(\"qr -->\", self.array.attrs.qr)\n print(\"rs -->\", self.array.attrs.rs)\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+', allow_align=False)\n self.root = self.h5file.root\n self.array = self.h5file.root.anarray\n\n self.assertIsInstance(self.array.attrs.pq, numpy.ndarray)\n self.assertIsInstance(self.array.attrs.qr, numpy.ndarray)\n self.assertIsInstance(self.array.attrs.rs, numpy.ndarray)\n assert_array_equal(self.array.attrs.pq, numpy.zeros(2, dt))\n assert_array_equal(self.array.attrs.qr, numpy.ones((2, 2), dt))\n assert_array_equal(self.array.attrs.rs, numpy.array([(1, 2.)], dt))\n\n\nclass NotCloseTypesTestCase(TypesTestCase):\n allow_padding = False\n aligned = False\n close = False\n\n\nclass NoCloseAlignedTypesTestCase(TypesTestCase):\n allow_padding = True\n aligned = True\n close = False\n\n\nclass CloseNotAlignedPaddedTypesTestCase(TypesTestCase):\n allow_padding = False\n aligned = False\n close = True\n\n\nclass CloseTypesTestCase(TypesTestCase):\n allow_padding = True\n aligned = False\n close = True\n\n\nclass CloseAlignedTypesTestCase(TypesTestCase):\n allow_padding = False\n aligned = True\n close = True\n\nclass CloseAlignedPaddedTypesTestCase(TypesTestCase):\n allow_padding = True\n aligned = True\n close = True\n\n\nclass NoSysAttrsTestCase(common.TempFileMixin, TestCase):\n open_kwargs = dict(pytables_sys_attrs=False)\n\n def setUp(self):\n super().setUp()\n self.root = self.h5file.root\n\n # Create a table object\n self.table = self.h5file.create_table(self.root, 'atable',\n Record, \"Table title\")\n # Create an array object\n self.array = self.h5file.create_array(self.root, 'anarray',\n [1], \"Array title\")\n # Create a group object\n self.group = self.h5file.create_group(self.root, 'agroup',\n \"Group title\")\n\n def test00_listAttributes(self):\n \"\"\"Checking listing attributes (no system attrs version).\"\"\"\n\n # With a Group object\n self.group._v_attrs.pq = \"1\"\n self.group._v_attrs.qr = \"2\"\n self.group._v_attrs.rs = \"3\"\n if common.verbose:\n print(\"Attribute list:\", self.group._v_attrs._f_list())\n\n # Now, try with a Table object\n self.table.attrs.a = \"1\"\n self.table.attrs.c = \"2\"\n self.table.attrs.b = \"3\"\n if common.verbose:\n print(\"Attribute list:\", self.table.attrs._f_list())\n\n # Finally, try with an Array object\n self.array.attrs.k = \"1\"\n self.array.attrs.j = \"2\"\n self.array.attrs.i = \"3\"\n if common.verbose:\n print(\"Attribute list:\", self.array.attrs._f_list())\n\n if self.close:\n if common.verbose:\n print(\"(closing file version)\")\n self._reopen(mode='r+')\n self.root = self.h5file.root\n\n agroup = self.root.agroup\n self.assertEqual(agroup._v_attrs._f_list(\"user\"), [\"pq\", \"qr\", \"rs\"])\n self.assertEqual(agroup._v_attrs._f_list(\"sys\"), [])\n self.assertEqual(agroup._v_attrs._f_list(\"all\"), [\"pq\", \"qr\", \"rs\"])\n\n atable = self.root.atable\n self.assertEqual(atable.attrs._f_list(), [\"a\", \"b\", \"c\"])\n self.assertEqual(atable.attrs._f_list(\"sys\"), [])\n self.assertEqual(atable.attrs._f_list(\"all\"), [\"a\", \"b\", \"c\"])\n\n anarray = self.root.anarray\n self.assertEqual(anarray.attrs._f_list(), [\"i\", \"j\", \"k\"])\n self.assertEqual(anarray.attrs._f_list(\"sys\"), [])\n self.assertEqual(anarray.attrs._f_list(\"all\"), [\"i\", \"j\", \"k\"])\n\n\nclass NoSysAttrsNotClose(NoSysAttrsTestCase):\n close = False\n\n\nclass NoSysAttrsClose(NoSysAttrsTestCase):\n close = True\n\n\nclass CompatibilityTestCase(common.TestFileMixin, TestCase):\n h5fname = test_filename('issue_368.h5')\n\n @unittest.skipIf(LooseVersion(numpy.__version__) < '1.9.0',\n 'requires numpy >= 1.9')\n def test_pickled_unicode_attrs(self):\n # See also gh-368 and https://github.com/numpy/numpy/issues/4879.\n #\n # This is a compatibility test. In PyTables < 3.0 unicode\n # attributes were stored as pickld unicode stings.\n # In PyTables >= 3.0 unicode strings are stored as encoded utf-8\n # strings (the utf-8 marker is set at HDF5 level).\n #\n # In any case PyTables (>= 3.0) should be able to handle correctly\n # also data files genetated with older versions of PyTables.\n # Unfortunately a bug in numpy < 1.9\n # (https://github.com/numpy/numpy/issues/4879) makes it impossible\n # unpickle numpy arrays with dtype \"U\" resulting in an incorrect\n # behaviour of PyTables.\n\n self.assertEqual(\n self.h5file.get_node_attr('/', 'py2_pickled_unicode'), 'abc')\n\n\nclass PicklePy2UnpicklePy3TestCase(common.TestFileMixin, TestCase):\n h5fname = test_filename('issue_560.h5')\n\n def test_pickled_datetime_object(self):\n # See also gh-560\n #\n # Objects (classes) that are pickled using python 2 may contain\n # non-ascii characters in the pickled string. This will cause\n # a UnicodeDecodeError when unpickling on python 3.\n # Python 3.4 adds encoding='bytes' to fix this\n # http://bugs.python.org/issue6784\n # Objects pickled in the testfile have non-ascii chars in the\n # picklestring and will throw UnicodeDecodeError when unpickled\n # on python 3.\n\n # datetime will be unpickled with encoding='bytes'\n self.assertIsInstance(\n self.h5file.get_node_attr('/', 'py2_pickled_datetime'),\n datetime.datetime)\n # dict will be unpickled with encoding='latin1'\n d = self.h5file.get_node_attr('/', 'py2_pickled_dict')\n self.assertIsInstance(d, dict)\n self.assertEqual(d['s'], 'just a string')\n\nclass SegFaultPythonTestCase(common.TempFileMixin, TestCase):\n\n def test00_segfault(self):\n \"\"\"Checking workaround for Python unpickle problem (see #253).\"\"\"\n\n self.h5file.root._v_attrs.trouble1 = \"0\"\n self.assertEqual(self.h5file.root._v_attrs.trouble1, \"0\")\n self.h5file.root._v_attrs.trouble2 = \"0.\"\n self.assertEqual(self.h5file.root._v_attrs.trouble2, \"0.\")\n # Problem happens after reopening\n self._reopen()\n self.assertEqual(self.h5file.root._v_attrs.trouble1, \"0\")\n self.assertEqual(self.h5file.root._v_attrs.trouble2, \"0.\")\n if common.verbose:\n print(\"Great! '0' and '0.' values can be safely retrieved.\")\n\n\nclass EmbeddedNullsTestCase(common.TempFileMixin, TestCase):\n # See laso gh-371 (https://github.com/PyTables/PyTables/issues/371)\n\n def test_unicode(self):\n value = \"string with a null byte \\x00 in it\"\n\n self.h5file.root._v_attrs.name = value\n self.assertEqual(self.h5file.root._v_attrs.name, value)\n\n self._reopen()\n\n self.assertEqual(self.h5file.root._v_attrs.name, value)\n\n def test_bytes(self):\n value = b\"string with a null byte \\x00 in it\"\n\n self.h5file.root._v_attrs.name = value\n self.assertEqual(self.h5file.root._v_attrs.name, value)\n\n self._reopen()\n\n self.assertEqual(self.h5file.root._v_attrs.name, value)\n\n\nclass VlenStrAttrTestCase(TestCase):\n def setUp(self):\n super().setUp()\n self.h5fname = test_filename('vlstr_attr.h5')\n self.h5file = tables.open_file(self.h5fname)\n\n def tearDown(self):\n self.h5file.close()\n super().tearDown()\n\n def test01_vlen_str_scalar(self):\n \"\"\"Checking file with variable length string attributes.\"\"\"\n\n attr = \"vlen_str_scalar\"\n self.assertEqual(\n self.h5file.get_node_attr(\"/\", attr), attr.encode('ascii'))\n\n def test02_vlen_str_array(self):\n \"\"\"Checking file with variable length string attributes (1d).\"\"\"\n\n attr = \"vlen_str_array\"\n v = self.h5file.get_node_attr('/', attr)\n self.assertEqual(v.ndim, 1)\n for idx, item in enumerate(v):\n value = \"%s_%d\" % (attr, idx)\n self.assertEqual(item, value.encode('ascii'))\n\n def test03_vlen_str_matrix(self):\n \"\"\"Checking file with variable length string attributes (2d).\"\"\"\n\n attr = \"vlen_str_matrix\"\n m = self.h5file.get_node_attr('/', attr)\n self.assertEqual(m.ndim, 2)\n for row, rowdata in enumerate(m):\n for col, item in enumerate(rowdata):\n value = \"%s_%d%d\" % (attr, row, col)\n self.assertEqual(item, value.encode('ascii'))\n\n\nclass UnsupportedAttrTypeTestCase(common.TestFileMixin, TestCase):\n h5fname = test_filename('attr-u16.h5')\n\n def test00_unsupportedType(self):\n \"\"\"Checking file with unsupported type.\"\"\"\n\n self.assertWarns(DataTypeWarning, repr, self.h5file)\n\n\n# Test for specific system attributes\nclass SpecificAttrsTestCase(common.TempFileMixin, TestCase):\n\n def test00_earray(self):\n \"\"\"Testing EArray specific attrs (create).\"\"\"\n\n ea = self.h5file.create_earray('/', 'ea', Int32Atom(), (2, 0, 4))\n if common.verbose:\n print(\"EXTDIM-->\", ea.attrs.EXTDIM)\n self.assertEqual(ea.attrs.EXTDIM, 1)\n\n def test01_earray(self):\n \"\"\"Testing EArray specific attrs (open).\"\"\"\n\n ea = self.h5file.create_earray('/', 'ea', Int32Atom(), (0, 1, 4))\n self._reopen('r')\n ea = self.h5file.root.ea\n if common.verbose:\n print(\"EXTDIM-->\", ea.attrs.EXTDIM)\n self.assertEqual(ea.attrs.EXTDIM, 0)\n\n\ndef suite():\n theSuite = unittest.TestSuite()\n niter = 1\n\n for i in range(niter):\n theSuite.addTest(unittest.makeSuite(NotCloseCreate))\n theSuite.addTest(unittest.makeSuite(CloseCreate))\n theSuite.addTest(unittest.makeSuite(NoCacheNotCloseCreate))\n theSuite.addTest(unittest.makeSuite(NoCacheCloseCreate))\n theSuite.addTest(unittest.makeSuite(DictCacheNotCloseCreate))\n theSuite.addTest(unittest.makeSuite(DictCacheCloseCreate))\n theSuite.addTest(unittest.makeSuite(NotCloseTypesTestCase))\n theSuite.addTest(unittest.makeSuite(CloseTypesTestCase))\n theSuite.addTest(unittest.makeSuite(CloseNotAlignedPaddedTypesTestCase))\n theSuite.addTest(unittest.makeSuite(NoCloseAlignedTypesTestCase))\n theSuite.addTest(unittest.makeSuite(CloseAlignedTypesTestCase))\n theSuite.addTest(unittest.makeSuite(CloseAlignedPaddedTypesTestCase))\n theSuite.addTest(unittest.makeSuite(NoSysAttrsNotClose))\n theSuite.addTest(unittest.makeSuite(NoSysAttrsClose))\n theSuite.addTest(unittest.makeSuite(CompatibilityTestCase))\n theSuite.addTest(unittest.makeSuite(PicklePy2UnpicklePy3TestCase))\n theSuite.addTest(unittest.makeSuite(SegFaultPythonTestCase))\n theSuite.addTest(unittest.makeSuite(EmbeddedNullsTestCase))\n theSuite.addTest(unittest.makeSuite(VlenStrAttrTestCase))\n theSuite.addTest(unittest.makeSuite(UnsupportedAttrTypeTestCase))\n theSuite.addTest(unittest.makeSuite(SpecificAttrsTestCase))\n\n return theSuite\n\n\nif __name__ == '__main__':\n common.parse_argv(sys.argv)\n common.print_versions()\n unittest.main(defaultTest='suite')\n",
"########################################################################\n#\n# License: BSD\n# Created: November 8, 2014\n# Author: Alistair Muldal - [email protected]\n#\n# $Id$\n#\n########################################################################\n\n\"\"\"This utility prints the contents of an HDF5 file as a tree.\n\nPass the flag -h to this for help on usage.\n\n\"\"\"\n\nimport tables\nimport numpy as np\nimport os\nimport argparse\nfrom collections import defaultdict, deque\nimport warnings\n\n\ndef _get_parser():\n parser = argparse.ArgumentParser(\n description='''\n `pttree` is designed to give a quick overview of the contents of a\n PyTables HDF5 file by printing a depth-indented list of nodes, similar\n to the output of the Unix `tree` function.\n\n It can also display the size, shape and compression states of\n individual nodes, as well as summary information for the whole file.\n\n For a more verbose output (including metadata), see `ptdump`.\n ''')\n\n parser.add_argument(\n '-L', '--max-level', type=int, dest='max_depth',\n help='maximum branch depth of tree to display (-1 == no limit)',\n )\n parser.add_argument(\n '-S', '--sort-by', type=str, dest='sort_by',\n help='artificially order nodes, can be either \"size\", \"name\" or \"none\"'\n )\n parser.add_argument(\n '--print-size', action='store_true', dest='print_size',\n help='print size of each node/branch',\n )\n parser.add_argument(\n '--no-print-size', action='store_false', dest='print_size',\n )\n parser.add_argument(\n '--print-shape', action='store_true', dest='print_shape',\n help='print shape of each node',\n )\n parser.add_argument(\n '--no-print-shape', action='store_false', dest='print_shape',\n )\n parser.add_argument(\n '--print-compression', action='store_true', dest='print_compression',\n help='print compression library(level) for each compressed node',\n )\n parser.add_argument(\n '--no-print-compression', action='store_false',\n dest='print_compression',\n )\n parser.add_argument(\n '--print-percent', action='store_true', dest='print_percent',\n help='print size of each node as a %% of the total tree size on disk',\n )\n parser.add_argument(\n '--no-print-percent', action='store_false',\n dest='print_percent',\n )\n parser.add_argument(\n '--use-si-units', action='store_true', dest='use_si_units',\n help='report sizes in SI units (1 MB == 10^6 B)',\n )\n parser.add_argument(\n '--use-binary-units', action='store_false', dest='use_si_units',\n help='report sizes in binary units (1 MiB == 2^20 B)',\n )\n\n parser.add_argument('src', metavar='filename[:nodepath]',\n help='path to the root of the tree structure')\n\n parser.set_defaults(max_depth=1, sort_by=\"size\", print_size=True,\n print_percent=True, print_shape=False,\n print_compression=False, use_si_units=False)\n\n return parser\n\n\ndef main():\n\n parser = _get_parser()\n args = parser.parse_args()\n\n # Catch the files passed as the last arguments\n src = args.__dict__.pop('src').rsplit(':', 1)\n if len(src) == 1:\n filename, nodename = src[0], \"/\"\n else:\n filename, nodename = src\n if nodename == \"\":\n # case where filename == \"filename:\" instead of \"filename:/\"\n nodename = \"/\"\n\n with tables.open_file(filename, 'r') as f:\n tree_str = get_tree_str(f, nodename, **args.__dict__)\n print(tree_str)\n\n pass\n\n\ndef get_tree_str(f, where='/', max_depth=-1, print_class=True,\n print_size=True, print_percent=True, print_shape=False,\n print_compression=False, print_total=True, sort_by=None,\n use_si_units=False):\n \"\"\"\n Generate the ASCII string representing the tree structure, and the summary\n info (if requested)\n \"\"\"\n\n root = f.get_node(where)\n root._g_check_open()\n start_depth = root._v_depth\n if max_depth < 0:\n max_depth = os.sys.maxint\n\n b2h = bytes2human(use_si_units)\n\n # we will pass over each node in the tree twice\n\n # on the first pass we'll start at the root node and recurse down the\n # branches, finding all of the leaf nodes and calculating the total size\n # over all tables and arrays\n total_in_mem = 0\n total_on_disk = 0\n total_items = 0\n\n # defaultdicts for holding the cumulative branch sizes at each node\n in_mem = defaultdict(lambda: 0)\n on_disk = defaultdict(lambda: 0)\n leaf_count = defaultdict(lambda: 0)\n\n # keep track of node addresses within the HDF5 file so that we don't count\n # nodes with multiple references (i.e. hardlinks) multiple times\n ref_count = defaultdict(lambda: 0)\n ref_idx = defaultdict(lambda: 0)\n hl_addresses = defaultdict(lambda: None)\n hl_targets = defaultdict(lambda: '')\n\n stack = deque(root)\n leaves = deque()\n\n while stack:\n\n node = stack.pop()\n\n if isinstance(node, tables.link.Link):\n # we treat links like leaves, except we don't dereference them to\n # get their sizes or addresses\n leaves.append(node)\n continue\n\n path = node._v_pathname\n addr, rc = node._get_obj_info()\n ref_count[addr] += 1\n ref_idx[path] = ref_count[addr]\n hl_addresses[path] = addr\n\n if isinstance(node, tables.UnImplemented):\n leaves.append(node)\n\n elif isinstance(node, tables.Leaf):\n\n # only count the size of a hardlinked leaf the first time it is\n # visited\n if ref_count[addr] == 1:\n\n try:\n m = node.size_in_memory\n d = node.size_on_disk\n\n # size of this node\n in_mem[path] += m\n on_disk[path] += d\n leaf_count[path] += 1\n\n # total over all nodes\n total_in_mem += m\n total_on_disk += d\n total_items += 1\n\n # arbitrarily treat this node as the 'target' for all other\n # hardlinks that point to the same address\n hl_targets[addr] = path\n\n except NotImplementedError as e:\n # size_on_disk is not implemented for VLArrays\n warnings.warn(str(e))\n\n # push leaf nodes onto the stack for the next pass\n leaves.append(node)\n\n elif isinstance(node, tables.Group):\n\n # don't recurse down the same hardlinked branch multiple times!\n if ref_count[addr] == 1:\n stack.extend(list(node._v_children.values()))\n hl_targets[addr] = path\n\n # if we've already visited this group's address, treat it as a leaf\n # instead\n else:\n leaves.append(node)\n\n # on the second pass we start at each leaf and work upwards towards the\n # root node, computing the cumulative size of each branch at each node, and\n # instantiating a PrettyTree object for each node to create an ASCII\n # representation of the tree structure\n\n # this will store the PrettyTree objects for every node we're printing\n pretty = {}\n\n stack = leaves\n\n while stack:\n\n node = stack.pop()\n path = node._v_pathname\n\n parent = node._v_parent\n parent_path = parent._v_pathname\n\n # cumulative size at parent node\n in_mem[parent_path] += in_mem[path]\n on_disk[parent_path] += on_disk[path]\n leaf_count[parent_path] += leaf_count[path]\n\n depth = node._v_depth - start_depth\n\n # if we're deeper than the max recursion depth, we print nothing\n if not depth > max_depth:\n\n # create a PrettyTree representation of this node\n name = node._v_name\n if print_class:\n name += \" (%s)\" % node.__class__.__name__\n\n labels = []\n ratio = on_disk[path] / total_on_disk\n\n # if the address of this object has a ref_count > 1, it has\n # multiple hardlinks\n if ref_count[hl_addresses[path]] > 1:\n name += ', addr=%i, ref=%i/%i' % (\n hl_addresses[path], ref_idx[path],\n ref_count[hl_addresses[path]]\n )\n\n if isinstance(node, tables.link.Link):\n labels.append('softlink --> %s' % node.target)\n\n elif ref_idx[path] > 1:\n labels.append('hardlink --> %s'\n % hl_targets[hl_addresses[path]])\n\n elif isinstance(node, (tables.Array, tables.Table)):\n\n if print_size:\n sizestr = 'mem={}, disk={}'.format(\n b2h(in_mem[path]), b2h(on_disk[path]))\n if print_percent:\n sizestr += f' [{ratio:5.1%}]'\n labels.append(sizestr)\n\n if print_shape:\n labels.append('shape=%s' % repr(node.shape))\n\n if print_compression:\n lib = node.filters.complib\n level = node.filters.complevel\n if level:\n compstr = '%s(%i)' % (lib, level)\n else:\n compstr = 'None'\n labels.append('compression=%s' % compstr)\n\n # if we're at our max recursion depth, we'll print summary\n # information for this branch\n elif depth == max_depth:\n itemstr = '... %i leaves' % leaf_count[path]\n if print_size:\n itemstr += ', mem={}, disk={}'.format(\n b2h(in_mem[path]), b2h(on_disk[path]))\n if print_percent:\n itemstr += f' [{ratio:5.1%}]'\n labels.append(itemstr)\n\n # create a PrettyTree for this node, if one doesn't exist already\n if path not in pretty:\n pretty.update({path: PrettyTree()})\n pretty[path].name = name\n pretty[path].labels = labels\n if sort_by == 'size':\n # descending size order\n pretty[path].sort_by = -ratio\n elif sort_by == 'name':\n pretty[path].sort_by = node._v_name\n else:\n # natural order\n if path == '/':\n # root is not in root._v_children\n pretty[path].sort_by = 0\n else:\n pretty[path].sort_by = list(parent._v_children.values(\n )).index(node)\n\n # exclude root node or we'll get infinite recursions (since '/' is\n # the parent of '/')\n if path != '/':\n\n # create a PrettyTree for the parent of this node, if one\n # doesn't exist already\n if parent_path not in pretty:\n pretty.update({parent_path: PrettyTree()})\n\n # make this PrettyTree a child of the parent PrettyTree\n pretty[parent_path].add_child(pretty[path])\n\n if node is not root and parent not in stack:\n # we append to the 'bottom' of the stack, so that we exhaust all of\n # the nodes at this level before going up a level in the tree\n stack.appendleft(parent)\n\n out_str = '\\n' + '-' * 60 + '\\n' * 2\n out_str += str(pretty[root._v_pathname]) + '\\n' * 2\n\n if print_total:\n avg_ratio = total_on_disk / total_in_mem\n fsize = os.stat(f.filename).st_size\n\n out_str += '-' * 60 + '\\n'\n out_str += 'Total branch leaves: %i\\n' % total_items\n out_str += 'Total branch size: {} in memory, {} on disk\\n'.format(\n b2h(total_in_mem), b2h(total_on_disk))\n out_str += 'Mean compression ratio: %.2f\\n' % avg_ratio\n out_str += 'HDF5 file size: %s\\n' % b2h(fsize)\n out_str += '-' * 60 + '\\n'\n\n return out_str\n\n\nclass PrettyTree:\n\n \"\"\"\n\n A pretty ASCII representation of a recursive tree structure. Each node can\n have multiple labels, given as a list of strings.\n\n Example:\n --------\n\n A = PrettyTree('A', labels=['wow'])\n B = PrettyTree('B', labels=['such tree'])\n C = PrettyTree('C', children=[A, B])\n D = PrettyTree('D', labels=['so recursive'])\n root = PrettyTree('root', labels=['many nodes'], children=[C, D])\n print root\n\n Credit to Andrew Cooke's blog:\n <http://www.acooke.org/cute/ASCIIDispl0.html>\n\n \"\"\"\n\n def __init__(self, name=None, children=None, labels=None, sort_by=None):\n\n # NB: do NOT assign default list/dict arguments in the function\n # declaration itself - these objects are shared between ALL instances\n # of PrettyTree, and by assigning to them it's easy to get into\n # infinite recursions, e.g. when 'self in self.children == True'\n if children is None:\n children = []\n if labels is None:\n labels = []\n\n self.name = name\n self.children = children\n self.labels = labels\n self.sort_by = sort_by\n\n def add_child(self, child):\n # some basic checks to help to avoid infinite recursion\n assert child is not self\n assert self not in child.children\n if child not in self.children:\n self.children.append(child)\n\n def tree_lines(self):\n yield self.name\n for label in self.labels:\n yield ' ' + label\n children = sorted(self.children, key=(lambda c: c.sort_by))\n last = children[-1] if children else None\n for child in children:\n prefix = '`--' if child is last else '+--'\n for line in child.tree_lines():\n yield prefix + line\n prefix = ' ' if child is last else '| '\n\n def __str__(self):\n return \"\\n\".join(self.tree_lines())\n\n def __repr__(self):\n return f'<{self.__class__.__name__} at 0x{id(self):x}>'\n\n\ndef bytes2human(use_si_units=False):\n\n if use_si_units:\n prefixes = 'TB', 'GB', 'MB', 'kB', 'B'\n values = 1E12, 1E9, 1E6, 1E3, 1\n else:\n prefixes = 'TiB', 'GiB', 'MiB', 'KiB', 'B'\n values = 2 ** 40, 2 ** 30, 2 ** 20, 2 ** 10, 1\n\n def b2h(nbytes):\n\n for (prefix, value) in zip(prefixes, values):\n scaled = nbytes / value\n if scaled >= 1:\n break\n\n return f\"{scaled:.1f}{prefix}\"\n\n return b2h\n\n\ndef make_test_file(prefix='/tmp'):\n f = tables.open_file(os.path.join(prefix, 'test_pttree.hdf5'), 'w')\n\n g1 = f.create_group('/', 'group1')\n g1a = f.create_group(g1, 'group1a')\n g1b = f.create_group(g1, 'group1b')\n\n filters = tables.Filters(complevel=5, complib='bzip2')\n\n for gg in g1a, g1b:\n f.create_carray(gg, 'zeros128b', obj=np.zeros(32, dtype=np.float64),\n filters=filters)\n f.create_carray(gg, 'random128b', obj=np.random.rand(32),\n filters=filters)\n\n g2 = f.create_group('/', 'group2')\n\n softlink = f.create_soft_link(g2, 'softlink_g1_z128',\n '/group1/group1a/zeros128b')\n hardlink = f.create_hard_link(g2, 'hardlink_g1a_z128',\n '/group1/group1a/zeros128b')\n\n hlgroup = f.create_hard_link(g2, 'hardlink_g1a', '/group1/group1a')\n\n return f\n"
] | [
[
"numpy.arange",
"numpy.array",
"numpy.random.uniform"
],
[
"numpy.alltrue",
"numpy.arange",
"numpy.array",
"numpy.random.randint"
],
[
"numpy.dtype",
"numpy.ones",
"numpy.testing.assert_array_equal",
"numpy.array",
"numpy.bool_",
"numpy.zeros"
],
[
"numpy.zeros",
"numpy.random.rand"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Outflier/PyAV | [
"f3aa2336a9fddfc2ae46e15a26956da08153af7e"
] | [
"tests/test_filters.py"
] | [
"from fractions import Fraction\nfrom unittest import SkipTest\nimport errno\n\nimport numpy as np\n\nfrom av import AudioFrame, VideoFrame\nfrom av.audio.frame import format_dtypes\nfrom av.filter import Filter, Graph\nimport av\n\nfrom .common import Image, TestCase, fate_suite\n\n\ndef generate_audio_frame(\n frame_num, input_format=\"s16\", layout=\"stereo\", sample_rate=44100, frame_size=1024\n):\n \"\"\"\n Generate audio frame representing part of the sinusoidal wave\n :param input_format: default: s16\n :param layout: default: stereo\n :param sample_rate: default: 44100\n :param frame_size: default: 1024\n :param frame_num: frame number\n :return: audio frame for sinusoidal wave audio signal slice\n \"\"\"\n frame = AudioFrame(format=input_format, layout=layout, samples=frame_size)\n frame.sample_rate = sample_rate\n frame.pts = frame_num * frame_size\n\n for i in range(len(frame.layout.channels)):\n data = np.zeros(frame_size, dtype=format_dtypes[input_format])\n for j in range(frame_size):\n data[j] = np.sin(2 * np.pi * (frame_num + j) * (i + 1) / float(frame_size))\n frame.planes[i].update(data)\n\n return frame\n\n\ndef pull_until_blocked(graph):\n frames = []\n while True:\n try:\n frames.append(graph.pull())\n except av.utils.AVError as e:\n if e.errno != errno.EAGAIN:\n raise\n return frames\n\n\nclass TestFilters(TestCase):\n def test_filter_descriptor(self):\n\n f = Filter(\"testsrc\")\n self.assertEqual(f.name, \"testsrc\")\n self.assertEqual(f.description, \"Generate test pattern.\")\n self.assertFalse(f.dynamic_inputs)\n self.assertEqual(len(f.inputs), 0)\n self.assertFalse(f.dynamic_outputs)\n self.assertEqual(len(f.outputs), 1)\n self.assertEqual(f.outputs[0].name, \"default\")\n self.assertEqual(f.outputs[0].type, \"video\")\n\n def test_dynamic_filter_descriptor(self):\n\n f = Filter(\"split\")\n self.assertFalse(f.dynamic_inputs)\n self.assertEqual(len(f.inputs), 1)\n self.assertTrue(f.dynamic_outputs)\n self.assertEqual(len(f.outputs), 0)\n\n def test_generator_graph(self):\n\n graph = Graph()\n src = graph.add(\"testsrc\")\n lutrgb = graph.add(\n \"lutrgb\",\n \"r=maxval+minval-val:g=maxval+minval-val:b=maxval+minval-val\",\n name=\"invert\",\n )\n sink = graph.add(\"buffersink\")\n src.link_to(lutrgb)\n lutrgb.link_to(sink)\n\n # pads and links\n self.assertIs(src.outputs[0].link.output, lutrgb.inputs[0])\n self.assertIs(lutrgb.inputs[0].link.input, src.outputs[0])\n\n frame = sink.pull()\n self.assertIsInstance(frame, VideoFrame)\n\n if Image:\n frame.to_image().save(self.sandboxed(\"mandelbrot2.png\"))\n\n def test_auto_find_sink(self):\n\n graph = Graph()\n src = graph.add(\"testsrc\")\n src.link_to(graph.add(\"buffersink\"))\n graph.configure()\n\n frame = graph.pull()\n\n if Image:\n frame.to_image().save(self.sandboxed(\"mandelbrot3.png\"))\n\n def test_delegate_sink(self):\n\n graph = Graph()\n src = graph.add(\"testsrc\")\n src.link_to(graph.add(\"buffersink\"))\n graph.configure()\n\n frame = src.pull()\n\n if Image:\n frame.to_image().save(self.sandboxed(\"mandelbrot4.png\"))\n\n def test_haldclut_graph(self):\n\n raise SkipTest()\n\n graph = Graph()\n\n img = Image.open(fate_suite(\"png1/lena-rgb24.png\"))\n frame = VideoFrame.from_image(img)\n img_source = graph.add_buffer(frame)\n\n hald_img = Image.open(\"hald_7.png\")\n hald_frame = VideoFrame.from_image(hald_img)\n hald_source = graph.add_buffer(hald_frame)\n\n hald_filter = graph.add(\"haldclut\")\n\n sink = graph.add(\"buffersink\")\n\n img_source.link(0, hald_filter, 0)\n hald_source.link(0, hald_filter, 1)\n hald_filter.link(0, sink, 0)\n graph.config()\n\n self.assertIs(img_source.outputs[0].linked_to, hald_filter.inputs[0])\n self.assertIs(hald_source.outputs[0].linked_to, hald_filter.inputs[1])\n self.assertIs(hald_filter.outputs[0].linked_to, sink.inputs[0])\n\n hald_source.push(hald_frame)\n\n img_source.push(frame)\n\n frame = sink.pull()\n self.assertIsInstance(frame, VideoFrame)\n frame.to_image().save(self.sandboxed(\"filtered.png\"))\n\n def test_audio_buffer_sink(self):\n graph = Graph()\n audio_buffer = graph.add_abuffer(\n format=\"fltp\",\n sample_rate=48000,\n layout=\"stereo\",\n time_base=Fraction(1, 48000),\n )\n audio_buffer.link_to(graph.add(\"abuffersink\"))\n graph.configure()\n\n try:\n graph.pull()\n except OSError as e:\n # we haven't pushed any input so expect no frames / EAGAIN\n if e.errno != errno.EAGAIN:\n raise\n\n @staticmethod\n def link_nodes(*nodes):\n for c, n in zip(nodes, nodes[1:]):\n c.link_to(n)\n\n def test_audio_buffer_resample(self):\n graph = Graph()\n self.link_nodes(\n graph.add_abuffer(\n format=\"fltp\",\n sample_rate=48000,\n layout=\"stereo\",\n time_base=Fraction(1, 48000),\n ),\n graph.add(\n \"aformat\", \"sample_fmts=s16:sample_rates=44100:channel_layouts=stereo\"\n ),\n graph.add(\"abuffersink\"),\n )\n graph.configure()\n\n graph.push(\n generate_audio_frame(\n 0, input_format=\"fltp\", layout=\"stereo\", sample_rate=48000\n )\n )\n out_frame = graph.pull()\n self.assertEqual(out_frame.format.name, \"s16\")\n self.assertEqual(out_frame.layout.name, \"stereo\")\n self.assertEqual(out_frame.sample_rate, 44100)\n\n def test_audio_buffer_volume_filter(self):\n graph = Graph()\n self.link_nodes(\n graph.add_abuffer(\n format=\"fltp\",\n sample_rate=48000,\n layout=\"stereo\",\n time_base=Fraction(1, 48000),\n ),\n graph.add(\"volume\", volume=\"0.5\"),\n graph.add(\"abuffersink\"),\n )\n graph.configure()\n\n input_frame = generate_audio_frame(\n 0, input_format=\"fltp\", layout=\"stereo\", sample_rate=48000\n )\n graph.push(input_frame)\n\n out_frame = graph.pull()\n self.assertEqual(out_frame.format.name, \"fltp\")\n self.assertEqual(out_frame.layout.name, \"stereo\")\n self.assertEqual(out_frame.sample_rate, 48000)\n\n input_data = input_frame.to_ndarray()\n output_data = out_frame.to_ndarray()\n\n self.assertTrue(\n np.allclose(input_data * 0.5, output_data), \"Check that volume is reduced\"\n )\n\n def test_video_buffer(self):\n input_container = av.open(format=\"lavfi\", file=\"color=c=pink:duration=1:r=30\")\n input_video_stream = input_container.streams.video[0]\n\n graph = av.filter.Graph()\n buffer = graph.add_buffer(template=input_video_stream)\n bwdif = graph.add(\"bwdif\", \"send_field:tff:all\")\n buffersink = graph.add(\"buffersink\")\n buffer.link_to(bwdif)\n bwdif.link_to(buffersink)\n graph.configure()\n\n for frame in input_container.decode():\n self.assertEqual(frame.time_base, Fraction(1, 30))\n graph.push(frame)\n filtered_frames = pull_until_blocked(graph)\n\n if frame.pts == 0:\n # no output for the first input frame\n self.assertEqual(len(filtered_frames), 0)\n else:\n # we expect two filtered frames per input frame\n self.assertEqual(len(filtered_frames), 2)\n\n self.assertEqual(filtered_frames[0].pts, (frame.pts - 1) * 2)\n self.assertEqual(filtered_frames[0].time_base, Fraction(1, 60))\n\n self.assertEqual(filtered_frames[1].pts, (frame.pts - 1) * 2 + 1)\n self.assertEqual(filtered_frames[1].time_base, Fraction(1, 60))\n\n def test_EOF(self):\n input_container = av.open(format=\"lavfi\", file=\"color=c=pink:duration=1:r=30\")\n video_stream = input_container.streams.video[0]\n\n graph = av.filter.Graph()\n video_in = graph.add_buffer(template=video_stream)\n palette_gen_filter = graph.add(\"palettegen\")\n video_out = graph.add(\"buffersink\")\n video_in.link_to(palette_gen_filter)\n palette_gen_filter.link_to(video_out)\n graph.configure()\n\n for frame in input_container.decode(video=0):\n graph.push(frame)\n\n graph.push(None)\n\n # if we do not push None, we get a BlockingIOError\n palette_frame = graph.pull()\n\n self.assertIsInstance(palette_frame, av.VideoFrame)\n self.assertEqual(palette_frame.width, 16)\n self.assertEqual(palette_frame.height, 16)\n"
] | [
[
"numpy.zeros",
"numpy.allclose"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
rdiere/yfinance | [
"969eeb66b5bc98635aa0289c15a49246248910e4"
] | [
"yfinance/base.py"
] | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Yahoo! Finance market data downloader (+fix for Pandas Datareader)\n# https://github.com/ranaroussi/yfinance\n#\n# Copyright 2017-2019 Ran Aroussi\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\nfrom __future__ import print_function\n\nimport time as _time\nimport datetime as _datetime\nimport requests as _requests\nimport pandas as _pd\nimport numpy as _np\n\ntry:\n from urllib.parse import quote as urlencode\nexcept ImportError:\n from urllib import quote as urlencode\n\nfrom . import utils\n\n# import json as _json\n# import re as _re\n# import sys as _sys\n\nfrom . import shared\n\n\nclass TickerBase():\n def __init__(self, ticker):\n self.ticker = ticker.upper()\n self._history = None\n self._base_url = 'https://query1.finance.yahoo.com'\n self._scrape_url = 'https://finance.yahoo.com/quote'\n\n self._fundamentals = False\n self._info = None\n self._sustainability = None\n self._recommendations = None\n self._major_holders = None\n self._institutional_holders = None\n self._isin = None\n\n self._calendar = None\n self._expirations = {}\n\n self._earnings = {\n \"yearly\": utils.empty_df(),\n \"quarterly\": utils.empty_df()}\n self._financials = {\n \"yearly\": utils.empty_df(),\n \"quarterly\": utils.empty_df()}\n self._balancesheet = {\n \"yearly\": utils.empty_df(),\n \"quarterly\": utils.empty_df()}\n self._cashflow = {\n \"yearly\": utils.empty_df(),\n \"quarterly\": utils.empty_df()}\n\n def history(self, period=\"1mo\", interval=\"1d\",\n start=None, end=None, prepost=False, actions=True,\n auto_adjust=True, back_adjust=False,\n proxy=None, rounding=True, tz=None, **kwargs):\n \"\"\"\n :Parameters:\n period : str\n Valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max\n Either Use period parameter or use start and end\n interval : str\n Valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo\n Intraday data cannot extend last 60 days\n start: str\n Download start date string (YYYY-MM-DD) or _datetime.\n Default is 1900-01-01\n end: str\n Download end date string (YYYY-MM-DD) or _datetime.\n Default is now\n prepost : bool\n Include Pre and Post market data in results?\n Default is False\n auto_adjust: bool\n Adjust all OHLC automatically? Default is True\n back_adjust: bool\n Back-adjusted data to mimic true historical prices\n proxy: str\n Optional. Proxy server URL scheme. Default is None\n rounding: bool\n Round values to 2 decimal places?\n Optional. Default is False = precision suggested by Yahoo!\n tz: str\n Optional timezone locale for dates.\n (default data is returned as non-localized dates)\n **kwargs: dict\n debug: bool\n Optional. If passed as False, will suppress\n error message printing to console.\n \"\"\"\n\n if start or period is None or period.lower() == \"max\":\n if start is None:\n start = -2208988800\n elif isinstance(start, _datetime.datetime):\n start = int(_time.mktime(start.timetuple()))\n else:\n start = int(_time.mktime(\n _time.strptime(str(start), '%Y-%m-%d')))\n if end is None:\n end = int(_time.time())\n elif isinstance(end, _datetime.datetime):\n end = int(_time.mktime(end.timetuple()))\n else:\n end = int(_time.mktime(_time.strptime(str(end), '%Y-%m-%d')))\n\n params = {\"period1\": start, \"period2\": end}\n else:\n period = period.lower()\n params = {\"range\": period}\n\n params[\"interval\"] = interval.lower()\n params[\"includePrePost\"] = prepost\n params[\"events\"] = \"div,splits\"\n\n # 1) fix weired bug with Yahoo! - returning 60m for 30m bars\n if params[\"interval\"] == \"30m\":\n params[\"interval\"] = \"15m\"\n\n # setup proxy in requests format\n if proxy is not None:\n if isinstance(proxy, dict) and \"https\" in proxy:\n proxy = proxy[\"https\"]\n proxy = {\"https\": proxy}\n\n # Getting data from json\n url = \"{}/v8/finance/chart/{}\".format(self._base_url, self.ticker)\n data = _requests.get(url=url, params=params, proxies=proxy)\n if \"Will be right back\" in data.text:\n raise RuntimeError(\"*** YAHOO! FINANCE IS CURRENTLY DOWN! ***\\n\"\n \"Our engineers are working quickly to resolve \"\n \"the issue. Thank you for your patience.\")\n data = data.json()\n\n # Work with errors\n debug_mode = True\n if \"debug\" in kwargs and isinstance(kwargs[\"debug\"], bool):\n debug_mode = kwargs[\"debug\"]\n\n err_msg = \"No data found for this date range, symbol may be delisted\"\n if \"chart\" in data and data[\"chart\"][\"error\"]:\n err_msg = data[\"chart\"][\"error\"][\"description\"]\n shared._DFS[self.ticker] = utils.empty_df()\n shared._ERRORS[self.ticker] = err_msg\n if \"many\" not in kwargs and debug_mode:\n print('- %s: %s' % (self.ticker, err_msg))\n return shared._DFS[self.ticker]\n\n elif \"chart\" not in data or data[\"chart\"][\"result\"] is None or \\\n not data[\"chart\"][\"result\"]:\n shared._DFS[self.ticker] = utils.empty_df()\n shared._ERRORS[self.ticker] = err_msg\n if \"many\" not in kwargs and debug_mode:\n print('- %s: %s' % (self.ticker, err_msg))\n return shared._DFS[self.ticker]\n\n # parse quotes\n try:\n quotes = utils.parse_quotes(data[\"chart\"][\"result\"][0], tz)\n except Exception:\n shared._DFS[self.ticker] = utils.empty_df()\n shared._ERRORS[self.ticker] = err_msg\n if \"many\" not in kwargs and debug_mode:\n print('- %s: %s' % (self.ticker, err_msg))\n return shared._DFS[self.ticker]\n\n # 2) fix weired bug with Yahoo! - returning 60m for 30m bars\n if interval.lower() == \"30m\":\n quotes2 = quotes.resample('30T')\n quotes = _pd.DataFrame(index=quotes2.last().index, data={\n 'Open': quotes2['Open'].first(),\n 'High': quotes2['High'].max(),\n 'Low': quotes2['Low'].min(),\n 'Close': quotes2['Close'].last(),\n 'Adj Close': quotes2['Adj Close'].last(),\n 'Volume': quotes2['Volume'].sum()\n })\n try:\n quotes['Dividends'] = quotes2['Dividends'].max()\n except Exception:\n pass\n try:\n quotes['Stock Splits'] = quotes2['Dividends'].max()\n except Exception:\n pass\n\n if auto_adjust:\n quotes = utils.auto_adjust(quotes)\n elif back_adjust:\n quotes = utils.back_adjust(quotes)\n\n if rounding:\n quotes = _np.round(quotes, data[\n \"chart\"][\"result\"][0][\"meta\"][\"priceHint\"])\n quotes['Volume'] = quotes['Volume'].fillna(0).astype(_np.int64)\n\n quotes.dropna(inplace=True)\n\n # actions\n dividends, splits = utils.parse_actions(data[\"chart\"][\"result\"][0], tz)\n\n # combine\n df = _pd.concat([quotes, dividends, splits], axis=1, sort=True)\n df[\"Dividends\"].fillna(0, inplace=True)\n df[\"Stock Splits\"].fillna(0, inplace=True)\n\n # index eod/intraday\n df.index = df.index.tz_localize(\"UTC\").tz_convert(\n data[\"chart\"][\"result\"][0][\"meta\"][\"exchangeTimezoneName\"])\n\n if params[\"interval\"][-1] in {\"m\", \"h\"}:\n df.index.name = \"Datetime\"\n else:\n df.index = _pd.to_datetime(df.index.date)\n if tz is not None:\n df.index = df.index.tz_localize(tz)\n df.index.name = \"Date\"\n\n self._history = df.copy()\n\n if not actions:\n df.drop(columns=[\"Dividends\", \"Stock Splits\"], inplace=True)\n\n return df\n\n # ------------------------\n\n def _get_fundamentals(self, kind=None, proxy=None):\n def cleanup(data):\n df = _pd.DataFrame(data).drop(columns=['maxAge'])\n for col in df.columns:\n df[col] = _np.where(\n df[col].astype(str) == '-', _np.nan, df[col])\n\n df.set_index('endDate', inplace=True)\n try:\n df.index = _pd.to_datetime(df.index, unit='s')\n except ValueError:\n df.index = _pd.to_datetime(df.index)\n df = df.T\n df.columns.name = ''\n df.index.name = 'Breakdown'\n\n df.index = utils.camel2title(df.index)\n return df\n\n # setup proxy in requests format\n if proxy is not None:\n if isinstance(proxy, dict) and \"https\" in proxy:\n proxy = proxy[\"https\"]\n proxy = {\"https\": proxy}\n\n if self._fundamentals:\n return\n\n # get info and sustainability\n url = '%s/%s' % (self._scrape_url, self.ticker)\n data = utils.get_json(url, proxy)\n\n # holders\n url = \"{}/{}/holders\".format(self._scrape_url, self.ticker)\n holders = _pd.read_html(url)\n self._major_holders = holders[0]\n self._institutional_holders = holders[1]\n if 'Date Reported' in self._institutional_holders:\n self._institutional_holders['Date Reported'] = _pd.to_datetime(\n self._institutional_holders['Date Reported'])\n if '% Out' in self._institutional_holders:\n self._institutional_holders['% Out'] = self._institutional_holders[\n '% Out'].str.replace('%', '').astype(float)/100\n\n # sustainability\n d = {}\n if isinstance(data.get('esgScores'), dict):\n for item in data['esgScores']:\n if not isinstance(data['esgScores'][item], (dict, list)):\n d[item] = data['esgScores'][item]\n\n s = _pd.DataFrame(index=[0], data=d)[-1:].T\n s.columns = ['Value']\n s.index.name = '%.f-%.f' % (\n s[s.index == 'ratingYear']['Value'].values[0],\n s[s.index == 'ratingMonth']['Value'].values[0])\n\n self._sustainability = s[~s.index.isin(\n ['maxAge', 'ratingYear', 'ratingMonth'])]\n\n # info (be nice to python 2)\n self._info = {}\n items = ['summaryProfile', 'summaryDetail', 'quoteType',\n 'defaultKeyStatistics', 'assetProfile', 'summaryDetail']\n for item in items:\n if isinstance(data.get(item), dict):\n self._info.update(data[item])\n\n self._info['regularMarketPrice'] = self._info['regularMarketOpen']\n self._info['logo_url'] = \"\"\n try:\n domain = self._info['website'].split(\n '://')[1].split('/')[0].replace('www.', '')\n self._info['logo_url'] = 'https://logo.clearbit.com/%s' % domain\n except Exception:\n pass\n\n # events\n try:\n cal = _pd.DataFrame(\n data['calendarEvents']['earnings'])\n cal['earningsDate'] = _pd.to_datetime(\n cal['earningsDate'], unit='s')\n self._calendar = cal.T\n self._calendar.index = utils.camel2title(self._calendar.index)\n self._calendar.columns = ['Value']\n except Exception:\n pass\n\n # analyst recommendations\n try:\n rec = _pd.DataFrame(\n data['upgradeDowngradeHistory']['history'])\n rec['earningsDate'] = _pd.to_datetime(\n rec['epochGradeDate'], unit='s')\n rec.set_index('earningsDate', inplace=True)\n rec.index.name = 'Date'\n rec.columns = utils.camel2title(rec.columns)\n self._recommendations = rec[[\n 'Firm', 'To Grade', 'From Grade', 'Action']].sort_index()\n except Exception:\n pass\n\n # get fundamentals\n data = utils.get_json(url+'/financials', proxy)\n\n # generic patterns\n for key in (\n (self._cashflow, 'cashflowStatement', 'cashflowStatements'),\n (self._balancesheet, 'balanceSheet', 'balanceSheetStatements'),\n (self._financials, 'incomeStatement', 'incomeStatementHistory')\n ):\n\n item = key[1] + 'History'\n if isinstance(data.get(item), dict):\n key[0]['yearly'] = cleanup(data[item][key[2]])\n\n item = key[1]+'HistoryQuarterly'\n if isinstance(data.get(item), dict):\n key[0]['quarterly'] = cleanup(data[item][key[2]])\n\n # earnings\n if isinstance(data.get('earnings'), dict):\n earnings = data['earnings']['financialsChart']\n df = _pd.DataFrame(earnings['yearly']).set_index('date')\n df.columns = utils.camel2title(df.columns)\n df.index.name = 'Year'\n self._earnings['yearly'] = df\n\n df = _pd.DataFrame(earnings['quarterly']).set_index('date')\n df.columns = utils.camel2title(df.columns)\n df.index.name = 'Quarter'\n self._earnings['quarterly'] = df\n\n self._fundamentals = True\n\n def get_recommendations(self, proxy=None, as_dict=False, *args, **kwargs):\n self._get_fundamentals(proxy)\n data = self._recommendations\n if as_dict:\n return data.to_dict()\n return data\n\n def get_calendar(self, proxy=None, as_dict=False, *args, **kwargs):\n self._get_fundamentals(proxy)\n data = self._calendar\n if as_dict:\n return data.to_dict()\n return data\n\n def get_major_holders(self, proxy=None, as_dict=False, *args, **kwargs):\n self._get_fundamentals(proxy)\n data = self._major_holders\n if as_dict:\n return data.to_dict()\n return data\n\n def get_institutional_holders(self, proxy=None, as_dict=False, *args, **kwargs):\n self._get_fundamentals(proxy)\n data = self._institutional_holders\n if as_dict:\n return data.to_dict()\n return data\n\n def get_info(self, proxy=None, as_dict=False, *args, **kwargs):\n self._get_fundamentals(proxy)\n data = self._info\n if as_dict:\n return data.to_dict()\n return data\n\n def get_sustainability(self, proxy=None, as_dict=False, *args, **kwargs):\n self._get_fundamentals(proxy)\n data = self._sustainability\n if as_dict:\n return data.to_dict()\n return data\n\n def get_earnings(self, proxy=None, as_dict=False, freq=\"yearly\"):\n self._get_fundamentals(proxy)\n data = self._earnings[freq]\n if as_dict:\n return data.to_dict()\n return data\n\n def get_financials(self, proxy=None, as_dict=False, freq=\"yearly\"):\n self._get_fundamentals(proxy)\n data = self._financials[freq]\n if as_dict:\n return data.to_dict()\n return data\n\n def get_balancesheet(self, proxy=None, as_dict=False, freq=\"yearly\"):\n self._get_fundamentals(proxy)\n data = self._balancesheet[freq]\n if as_dict:\n return data.to_dict()\n return data\n\n def get_balance_sheet(self, proxy=None, as_dict=False, freq=\"yearly\"):\n return self.get_balancesheet(proxy, as_dict, freq)\n\n def get_cashflow(self, proxy=None, as_dict=False, freq=\"yearly\"):\n self._get_fundamentals(proxy)\n data = self._cashflow[freq]\n if as_dict:\n return data.to_dict()\n return data\n\n def get_dividends(self, proxy=None):\n if self._history is None:\n self.history(period=\"max\", proxy=proxy)\n dividends = self._history[\"Dividends\"]\n return dividends[dividends != 0]\n\n def get_splits(self, proxy=None):\n if self._history is None:\n self.history(period=\"max\", proxy=proxy)\n splits = self._history[\"Stock Splits\"]\n return splits[splits != 0]\n\n def get_actions(self, proxy=None):\n if self._history is None:\n self.history(period=\"max\", proxy=proxy)\n actions = self._history[[\"Dividends\", \"Stock Splits\"]]\n return actions[actions != 0].dropna(how='all').fillna(0)\n\n def get_isin(self, proxy=None):\n # *** experimental ***\n if self._isin is not None:\n return self._isin\n\n ticker = self.ticker.upper()\n\n if \"-\" in ticker or \"^\" in ticker:\n self._isin = '-'\n return self._isin\n\n # setup proxy in requests format\n if proxy is not None:\n if isinstance(proxy, dict) and \"https\" in proxy:\n proxy = proxy[\"https\"]\n proxy = {\"https\": proxy}\n\n q = ticker\n self.get_info(proxy=proxy)\n if \"shortName\" in self._info:\n q = self._info['shortName']\n\n url = 'https://markets.businessinsider.com/ajax/' \\\n 'SearchController_Suggest?max_results=25&query=%s' \\\n % urlencode(q)\n data = _requests.get(url=url, proxies=proxy).text\n\n search_str = '\"{}|'.format(ticker)\n if search_str not in data:\n if q.lower() in data.lower():\n search_str = '\"|'\n if search_str not in data:\n self._isin = '-'\n return self._isin\n else:\n self._isin = '-'\n return self._isin\n\n self._isin = data.split(search_str)[1].split('\"')[0].split('|')[0]\n return self._isin\n"
] | [
[
"pandas.concat",
"pandas.to_datetime",
"pandas.read_html",
"pandas.DataFrame",
"numpy.round"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
SecTraversl/python_pandas_Tools | [
"4b818c993e1587c150d8f94e0c8c6437516deee4"
] | [
"pandasread_csv_addheader.py"
] | [
"# %%\n#######################################\ndef pandasread_csv_addheader(csv_file: str, addheader: list):\n \"\"\"Returns a pandas dataframe from the given .csv file. Assumes there is no header in the .csv and requires a header to be given as an argument to the 'addheader'.\n\n Example:\n >>> myheader = ['NAME','AGE','JOB','DEPARTMENT','PAY']\\n\n >>> pandasread_csv_addheader('test.csv', addheader=myheader)\\n\n NAME AGE JOB DEPARTMENT PAY\\n\n 0 bob 21 janitor sanitization team 2\\n\n 1 alice 22 secretary admin team 3\\n\n 2 chuck 23 plumber construction team 4\\n\n\n Reference:\n https://stackoverflow.com/questions/36828348/pandas-read-csv-reading-a-csv-file-with-a-missing-header-element\n\n Args:\n csv_file (str): Reference an existing .csv file.\n addheader (list): Reference the header you want to use for the columns.\n\n Returns:\n pandas.core.frame.DataFrame: Returns a pandas dataframe.\n \"\"\"\n import pandas\n df = pandas.read_csv(csv_file, header=None, names=addheader)\n return df\n\n"
] | [
[
"pandas.read_csv"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
MorganCThomas/MolScore | [
"b12b7b5539bb3211982fc7a1b5938c0f383a05c0"
] | [
"generative_models/lstm_hc/distribution_learner.py"
] | [
"\"\"\"\nAdapted from guacamol_baselines https://github.com/BenevolentAI/guacamol_baselines\n\"\"\"\n\nimport logging\nfrom typing import List\n\nimport torch\n#from guacamol.distribution_matching_generator import DistributionMatchingGenerator\n\nfrom model import SmilesRnn\nfrom trainer import SmilesRnnTrainer\nfrom utils import get_tensor_dataset, load_smiles_from_list, set_random_seed\nfrom smiles_char_dict import SmilesCharDictionary\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(logging.NullHandler())\n\n\nclass SmilesRnnDistributionLearner:\n def __init__(self, output_dir: str, n_epochs=10, hidden_size=512, n_layers=3,\n max_len=100, batch_size=64, rnn_dropout=0.2, lr=1e-3, valid_every=100) -> None:\n self.n_epochs = n_epochs\n self.output_dir = output_dir\n self.hidden_size = hidden_size\n self.n_layers = n_layers\n self.max_len = max_len\n self.batch_size = batch_size\n self.rnn_dropout = rnn_dropout\n self.lr = lr\n self.valid_every = valid_every\n self.print_every = 10\n self.seed = 42\n\n def train(self, training_set: List[str], validation_set: List[str]):# -> DistributionMatchingGenerator:\n # GPU if available\n cuda_available = torch.cuda.is_available()\n device_str = 'cuda' if cuda_available else 'cpu'\n device = torch.device(device_str)\n logger.info(f'CUDA enabled:\\t{cuda_available}')\n\n set_random_seed(self.seed, device)\n\n # load data\n train_seqs, _ = load_smiles_from_list(training_set, self.max_len)\n valid_seqs, _ = load_smiles_from_list(validation_set, self.max_len)\n\n train_set = get_tensor_dataset(train_seqs)\n test_set = get_tensor_dataset(valid_seqs)\n\n sd = SmilesCharDictionary()\n n_characters = sd.get_char_num()\n\n # build network\n smiles_model = SmilesRnn(input_size=n_characters,\n hidden_size=self.hidden_size,\n output_size=n_characters,\n n_layers=self.n_layers,\n rnn_dropout=self.rnn_dropout)\n\n # wire network for training\n optimizer = torch.optim.Adam(smiles_model.parameters(), lr=self.lr)\n criterion = torch.nn.CrossEntropyLoss(ignore_index=sd.pad_idx)\n\n trainer = SmilesRnnTrainer(model=smiles_model,\n criteria=[criterion],\n optimizer=optimizer,\n device=device,\n log_dir=self.output_dir)\n\n trainer.fit(train_set, test_set,\n batch_size=self.batch_size,\n print_every=self.print_every,\n valid_every=self.valid_every,\n n_epochs=self.n_epochs)\n"
] | [
[
"torch.device",
"torch.nn.CrossEntropyLoss",
"torch.cuda.is_available"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
JBorrow/pageplot | [
"8abad574fda476d26a59fc8b7d36da2838f2c11e"
] | [
"pageplot/plotmodel.py"
] | [
"\"\"\"\nThe base top-level plot model class.\n\nFrom this all data and plotting flow.\n\"\"\"\n\nfrom pageplot.exceptions import PagePlotParserError\nfrom pathlib import Path\nfrom typing import Any, Optional, Dict, List, Union\n\nfrom pageplot.extensionmodel import PlotExtension\nfrom pageplot.extensions import built_in_extensions\nfrom pageplot.io.spec import IOSpecification\nfrom pageplot.config import GlobalConfig\nfrom pageplot.mask import get_mask\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport unyt\nimport attr\n\n\[email protected](auto_attribs=True)\nclass PlotModel:\n \"\"\"\n Model describing an individual plot. De-serializes the input\n json describing an individual figure's extension values.\n\n To use this, you'll need to initialise it with the configuration\n (for all the extensions!), and then associate the data with\n the appropraite method. The plots can then be created using the\n methods in the following order:\n\n ``setup_figures`` - creates Figure and Axes objects\n ``run_extensions`` - runs all of the extensions' ``preprocess`` steps\n ``perform_blitting`` - runs the extensions' ``blit`` functions\n ``save`` - writes out the figures to disk\n ``finalize`` - closes the Figure object\n\n You can also serialize the contents of the whole figure to a dictionary\n with the ``serialize`` object.\n\n Parameters\n ----------\n\n name: str\n Plot name. This is the filename of the plot (without file extension).\n\n config: GlobalConfig\n Global configuration object.\n\n plot_spec: Dict[str, Any]\n Data controlling the behaviour of each extension. The keys should\n be the same as the used extensions. Mis-matches will raise a\n ``PagePlotParserError``.\n\n x, y, z: str, optional\n Strings to be passed to the data to load appropriate x, y, and z\n data. Here only x is required.\n\n x_units, y_units, z_units: Union[str, None, unyt.unyt_quantity]\n Expected output units for the plot, to be parsed.\n\n mask: str, optional\n Mask text (see :func:`get_mask`).\n\n\n \"\"\"\n\n name: str\n config: GlobalConfig\n plot_spec: Dict[str, Any]\n\n x: str\n y: Optional[str] = None\n z: Optional[str] = None\n\n # Output units for the plot.\n x_units: Union[str, None, unyt.unyt_quantity] = None\n y_units: Union[str, None, unyt.unyt_quantity] = None\n z_units: Union[str, None, unyt.unyt_quantity] = None\n\n mask: Optional[str] = None\n\n data: IOSpecification = attr.ib(init=False)\n fig: plt.Figure = attr.ib(init=False)\n axes: plt.Axes = attr.ib(init=False)\n extensions: Dict[str, PlotExtension] = attr.ib(init=False)\n\n def associate_data(self, data: IOSpecification):\n \"\"\"\n Associates the data file (which conforms to the\n ``IOSpecification``) with the plot.\n\n data: IOSpecification\n Any data file that conforms to the specification.\n \"\"\"\n\n self.data = data\n\n def setup_figures(self):\n \"\"\"\n Sets up the internal figure and axes.\n \"\"\"\n\n self.fig, self.axes = plt.subplots()\n\n return\n\n def run_extensions(\n self, additional_extensions: Optional[Dict[str, PlotExtension]] = None\n ):\n \"\"\"\n Run the figure extensions (these provide all data for the figures,\n excluding the plotting). Internal extensions are performed\n first, then any additional extensions are executed.\n\n additional_extensions: Dict[str, PlotExtension]\n Any additional extensions conforming to the specification.\n \"\"\"\n\n # First, sort out units and masking\n units = {\n \"x_units\": self.x_units,\n \"y_units\": self.y_units,\n \"z_units\": self.z_units,\n }\n\n for name, value in units.items():\n if value is None:\n if (associated_data := getattr(self, name[0])) is None:\n units[name] = unyt.unyt_quantity(1.0, None)\n else:\n units[name] = unyt.unyt_quantity(\n 1.0, associated_data.split(\" \", 1)[1]\n )\n else:\n units[name] = unyt.unyt_quantity(1.0, value)\n\n mask = get_mask(data=self.data, mask_text=self.mask)\n\n self.extensions = {}\n\n if additional_extensions is None:\n additional_extensions = {}\n\n combined_extensions = {**built_in_extensions, **additional_extensions}\n\n for name in self.plot_spec.keys():\n try:\n Extension = combined_extensions[name]\n except KeyError:\n raise PagePlotParserError(\n name, \"Unable to find matching extension for configuration value.\"\n )\n\n extension = Extension(\n name=name,\n config=self.config,\n metadata=self.data.metadata,\n x=self.data.data_from_string(self.x, mask=mask),\n y=self.data.data_from_string(self.y, mask=mask),\n z=self.data.data_from_string(self.z, mask=mask),\n **units,\n **self.plot_spec.get(name, {}),\n )\n\n extension.preprocess()\n\n self.extensions[name] = extension\n\n return\n\n def perform_blitting(self):\n \"\"\"\n Performs the blitting (creating the figure).\n\n Without this, the extensions are just 'created' and pre-processed\n without affecting or creating the figure.\n \"\"\"\n\n for extension in self.extensions.values():\n extension.blit(fig=self.fig, axes=self.axes)\n\n def save(self, filename: Path):\n \"\"\"\n Saves the figure to file.\n\n filename: Path\n Filename that you would like to save the figure to. Can have\n any matplotlib-compatible file extension.\n\n Notes\n -----\n\n It's suggested that you run finalzie() after this function, otherwise\n there will be lots of figures open at one time causing potential slowdowns.\n \"\"\"\n\n self.fig.savefig(filename)\n\n return\n\n def serialize(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the contents of the extensions to a dictionary.\n\n Note that you do not have to have 'created' the figure to run this,\n if you just want the data you should be able to just request\n the serialized data.\n \"\"\"\n\n serialized = {name: ext.serialize() for name, ext in self.extensions.items()}\n\n return serialized\n\n def finalize(self):\n \"\"\"\n Closes figures and cleans up.\n \"\"\"\n\n plt.close(self.fig)\n\n class Config:\n arbitrary_types_allowed = True\n"
] | [
[
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.close"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
fdcck/unrestricted-adversarial-examples | [
"125a21d2073308df05ad2dfaf4f9c58ec749b3e4"
] | [
"unrestricted-advex/unrestricted_advex/attacks.py"
] | [
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport multiprocessing\nimport random\nfrom itertools import product, repeat\n\nimport numpy as np\nimport tensorflow as tf\nfrom cleverhans.attacks import SPSA\nfrom cleverhans.model import Model\nfrom foolbox.attacks import BoundaryAttack as FoolboxBoundaryAttack\nfrom imagenet_c import corrupt\nfrom six.moves import xrange\nfrom unrestricted_advex.cleverhans_fast_spatial_attack import SpatialTransformationMethod\n\n\nclass Attack(object):\n name = None\n\n # TODO: Refactor this out of this object\n _stop_after_n_datapoints = None # An attack can optionally run on only a subset of the dataset\n\n def __call__(self, *args, **kwargs):\n raise NotImplementedError()\n\n\nclass CleanData(Attack):\n \"\"\"Also known as the \"null attack\". Just returns the unaltered clean image\"\"\"\n name = 'clean'\n\n def __call__(self, model_fn, images_batch_nhwc, y_np):\n del y_np, model_fn # unused\n return images_batch_nhwc\n\n\nclass SpsaAttack(Attack):\n name = 'spsa'\n\n def __init__(self, model, image_shape_hwc, epsilon=(16. / 255),\n num_steps=200, batch_size=32, is_debug=False):\n self.graph = tf.Graph()\n\n with self.graph.as_default():\n self.sess = tf.Session(graph=self.graph)\n\n self.x_input = tf.placeholder(tf.float32, shape=(1,) + image_shape_hwc)\n self.y_label = tf.placeholder(tf.int32, shape=(1,))\n\n self.model = model\n attack = SPSA(CleverhansPyfuncModelWrapper(self.model), sess=self.sess)\n self.x_adv = attack.generate(\n self.x_input,\n y=self.y_label,\n epsilon=epsilon,\n num_steps=num_steps,\n early_stop_loss_threshold=-1.,\n batch_size=batch_size,\n is_debug=is_debug)\n\n self.graph.finalize()\n\n def __call__(self, model, x_np, y_np): # (4. / 255)):\n if model != self.model:\n raise ValueError('Cannot call spsa attack on different models')\n del model # unused except to check that we already wired it up right\n\n with self.graph.as_default():\n all_x_adv_np = []\n for i in xrange(len(x_np)):\n x_adv_np = self.sess.run(self.x_adv, feed_dict={\n self.x_input: np.expand_dims(x_np[i], axis=0),\n self.y_label: np.expand_dims(y_np[i], axis=0),\n })\n all_x_adv_np.append(x_adv_np)\n return np.concatenate(all_x_adv_np)\n\n\ndef corrupt_float32_image(x, corruption_name, severity):\n \"\"\"Convert to uint8 and back to conform to corruption API\"\"\"\n x = np.copy(x) # We make a copy to avoid changing things in-place\n x = (x * 255).astype(np.uint8)\n\n corrupt_x = corrupt(\n x,\n corruption_name=corruption_name,\n severity=severity)\n return corrupt_x.astype(np.float32) / 255.\n\n\ndef _corrupt_float32_image_star(args):\n return corrupt_float32_image(*args)\n\n\nclass CommonCorruptionsAttack(Attack):\n name = \"common_corruptions\"\n\n def __init__(self, severity=1):\n self.corruption_names = [\n 'gaussian_noise',\n 'shot_noise',\n 'impulse_noise',\n 'defocus_blur',\n 'glass_blur',\n 'motion_blur',\n 'zoom_blur',\n # 'snow', # Snow does not work in python 2.7\n # 'frost', # Frost is not working correctly\n 'fog',\n 'brightness',\n 'contrast',\n 'elastic_transform',\n 'pixelate',\n 'jpeg_compression',\n 'speckle_noise',\n 'gaussian_blur',\n 'spatter',\n 'saturate']\n self.severity = severity\n self.pool = multiprocessing.Pool(len(self.corruption_names))\n\n def __call__(self, model_fn, images_batch_nhwc, y_np):\n assert images_batch_nhwc.shape[1:] == (224, 224, 3), \\\n \"Image shape must equal (N, 224, 224, 3)\"\n batch_size = len(images_batch_nhwc)\n\n # Keep track of the worst corruption for each image\n worst_corruption = np.copy(images_batch_nhwc)\n worst_loss = [np.NINF] * batch_size\n\n # Iterate through each image in the batch\n for batch_idx, x in enumerate(images_batch_nhwc):\n corrupt_args = [(x, corruption_name, self.severity)\n for corruption_name in self.corruption_names]\n corrupt_x_batch = self.pool.map(_corrupt_float32_image_star, corrupt_args)\n logits_batch = model_fn(np.array(corrupt_x_batch))\n label = y_np[batch_idx]\n\n # This is left un-vectorized for readability\n for (logits, corrupt_x) in zip(logits_batch, corrupt_x_batch):\n correct_logit, wrong_logit = logits[label], logits[1 - label]\n\n # We can choose different loss functions to optimize in the\n # attack. For now, optimize the magnitude of the wrong logit\n # because we use this as our confidence threshold\n loss = wrong_logit\n # loss = wrong_logit - correct_logit\n\n if loss > worst_loss[batch_idx]:\n worst_corruption[batch_idx] = corrupt_x\n worst_loss[batch_idx] = loss\n\n return worst_corruption\n\n\nclass BoundaryAttack(Attack):\n name = \"boundary\"\n\n def __init__(self, model, image_shape_hwc, max_l2_distortion=4, label_to_examples=None):\n if label_to_examples is None:\n label_to_examples = {}\n\n self.max_l2_distortion = max_l2_distortion\n\n class Model:\n def bounds(self):\n return [0, 1]\n\n def predictions(self, img):\n return model(img[np.newaxis, :, :, :])[0]\n\n def batch_predictions(self, img):\n return model(img)\n\n self.label_to_examples = label_to_examples\n\n h, w, c = image_shape_hwc\n mse_threshold = max_l2_distortion ** 2 / (h * w * c)\n try:\n # Foolbox 1.5 allows us to use a threshold the attack will abort after\n # reaching. Because we only care about a distortion of less than 4, as soon\n # as we reach it, we can just abort and move on to the next image.\n self.attack = FoolboxBoundaryAttack(model=Model(), threshold=mse_threshold)\n except:\n # Fall back to the original implementation.\n print(\"WARNING: Using foolbox version < 1.5 will cuase the \"\n \"boundary attack to perform more work than is required. \"\n \"Please upgrade to version 1.5\")\n self.attack = FoolboxBoundaryAttack(model=Model())\n\n def __call__(self, model, x_np, y_np):\n r = []\n for i in range(len(x_np)):\n other = 1 - y_np[i]\n initial_adv = random.choice(self.label_to_examples[other])\n try:\n adv = self.attack(x_np[i], y_np[i],\n log_every_n_steps=100, # Reduce verbosity of the attack\n starting_point=initial_adv\n )\n distortion = np.sum((x_np[i] - adv) ** 2) ** .5\n if distortion > self.max_l2_distortion:\n # project to the surface of the L2 ball\n adv = x_np[i] + (adv - x_np[i]) / distortion * self.max_l2_distortion\n\n except AssertionError as error:\n if str(error).startswith(\"Invalid starting point provided.\"):\n print(\"WARNING: The model misclassified the starting point (the target) \"\n \"from BoundaryAttack. This means that the attack will fail on this \"\n \"specific point (but is likely to succeed on other points.\")\n adv = x_np[i] # Just return the non-adversarial point\n else:\n raise error\n\n r.append(adv)\n return np.array(r)\n\n\nclass FastSpatialGridAttack(Attack):\n \"\"\"Fast attack from \"A Rotation and a Translation Suffice: Fooling CNNs with\n Simple Transformations\", Engstrom et al. 2018\n\n https://arxiv.org/pdf/1712.02779.pdf\n \"\"\"\n name = 'spatial_grid'\n\n def __init__(self, model,\n image_shape_hwc,\n spatial_limits,\n grid_granularity,\n black_border_size,\n ):\n self.graph = tf.Graph()\n\n with self.graph.as_default():\n self.sess = tf.Session(graph=self.graph)\n\n self.x_input = tf.placeholder(\n tf.float32, shape=[None] + list(image_shape_hwc))\n self.y_input = tf.placeholder(tf.float32, shape=(None, 2))\n\n self.model = model\n attack = SpatialTransformationMethod(\n CleverhansPyfuncModelWrapper(self.model), sess=self.sess)\n\n self.x_adv = attack.generate(\n self.x_input,\n y=self.y_input,\n n_samples=None,\n dx_min=-float(spatial_limits[0]) / image_shape_hwc[0],\n dx_max=float(spatial_limits[0]) / image_shape_hwc[0],\n n_dxs=grid_granularity[0],\n dy_min=-float(spatial_limits[1]) / image_shape_hwc[1],\n dy_max=float(spatial_limits[1]) / image_shape_hwc[1],\n n_dys=grid_granularity[1],\n angle_min=-spatial_limits[2],\n angle_max=spatial_limits[2],\n n_angles=grid_granularity[2],\n black_border_size=black_border_size,\n )\n\n self.graph.finalize()\n\n def __call__(self, model_fn, x_np, y_np):\n if model_fn != self.model:\n raise ValueError('Cannot call spatial attack on different models')\n del model_fn # unused except to check that we already wired it up right\n\n y_np_one_hot = np.zeros([len(y_np), 2], np.float32)\n y_np_one_hot[np.arange(len(y_np)), y_np] = 1.0\n\n # Reduce the batch size to 1 to avoid OOM errors\n with self.graph.as_default():\n all_x_adv_np = []\n for i in xrange(len(x_np)):\n x_adv_np = self.sess.run(self.x_adv, feed_dict={\n self.x_input: np.expand_dims(x_np[i], axis=0),\n self.y_input: np.expand_dims(y_np_one_hot[i], axis=0),\n })\n all_x_adv_np.append(x_adv_np)\n return np.concatenate(all_x_adv_np)\n\n\nclass SpatialGridAttack(Attack):\n \"\"\"Attack from \"A Rotation and a Translation Suffice: Fooling CNNs with\n Simple Transformations\", Engstrom et al. 2018\n\n https://arxiv.org/pdf/1712.02779.pdf\n \"\"\"\n name = 'spatial_grid'\n\n def __init__(self, image_shape_hwc,\n spatial_limits,\n grid_granularity,\n black_border_size,\n valid_check=None,\n ):\n \"\"\"\n :param model_fn: a callable: batch-input -> batch-probability in [0, 1]\n :param spatial_limits:\n :param grid_granularity:\n \"\"\"\n self.limits = spatial_limits\n self.granularity = grid_granularity\n self.valid_check = valid_check\n\n # Construct graph for spatial attack\n self.graph = tf.Graph()\n with self.graph.as_default():\n self._x_for_trans = tf.placeholder(tf.float32, shape=[None] + list(image_shape_hwc))\n self._t_for_trans = tf.placeholder(tf.float32, shape=[None, 3])\n\n x = apply_black_border(\n self._x_for_trans,\n image_height=image_shape_hwc[0],\n image_width=image_shape_hwc[1],\n border_size=black_border_size\n )\n\n self._tranformed_x_op = apply_transformation(\n x,\n transform=self._t_for_trans,\n image_height=image_shape_hwc[0],\n image_width=image_shape_hwc[1],\n )\n self.session = tf.Session()\n\n self.grid_store = []\n\n def __call__(self, model_fn, x_np, y_np):\n n = len(x_np)\n grid = product(*list(np.linspace(-l, l, num=g)\n for l, g in zip(self.limits, self.granularity)))\n\n worst_x = np.copy(x_np)\n max_xent = np.zeros(n)\n all_correct = np.ones(n).astype(bool)\n\n trans_np = np.stack(\n repeat([0, 0, 0], n))\n with self.graph.as_default():\n x_downsize_np = self.session.run(self._tranformed_x_op, feed_dict={\n self._x_for_trans: x_np,\n self._t_for_trans: trans_np,\n\n })\n\n for horizontal_trans, vertical_trans, rotation in grid:\n trans_np = np.stack(\n repeat([horizontal_trans, vertical_trans, rotation], n))\n\n # Apply the spatial attack\n with self.graph.as_default():\n x_np_trans = self.session.run(self._tranformed_x_op, feed_dict={\n self._x_for_trans: x_np,\n self._t_for_trans: trans_np,\n })\n # See how the model_fn performs on the perturbed input\n logits = model_fn(x_np_trans)\n preds = np.argmax(logits, axis=1)\n\n cur_xent = _sparse_softmax_cross_entropy_with_logits_from_numpy(\n logits, y_np, self.graph, self.session)\n\n cur_xent = np.asarray(cur_xent)\n cur_correct = np.equal(y_np, preds)\n\n if self.valid_check:\n is_valid = self.valid_check(x_downsize_np, x_np_trans)\n cur_correct |= ~is_valid\n cur_xent -= is_valid * 1e9\n\n # Select indices to update: we choose the misclassified transformation\n # of maximum xent (or just highest xent if everything else if correct).\n idx = (cur_xent > max_xent) & (cur_correct == all_correct)\n idx = idx | (cur_correct < all_correct)\n max_xent = np.maximum(cur_xent, max_xent)\n all_correct = cur_correct & all_correct\n\n idx = np.expand_dims(idx, axis=-1) # shape (bsize, 1)\n\n idx = np.expand_dims(idx, axis=-1)\n idx = np.expand_dims(idx, axis=-1) # shape (bsize, 1, 1, 1)\n worst_x = np.where(idx, x_np_trans, worst_x, ) # shape (bsize, 32, 32, 3)\n\n return worst_x\n\n\ndef _sparse_softmax_cross_entropy_with_logits_from_numpy(logits_np, labels_np, graph, sess):\n \"\"\"Helper that calls the TF sparse_softmax_cross_entropy_with_logits function\"\"\"\n with graph.as_default():\n labels_tf = tf.placeholder(tf.int32, [None])\n logits_tf = tf.placeholder(tf.float32, [None, None])\n xent_tf = tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=labels_tf, logits=logits_tf)\n return sess.run(xent_tf, feed_dict={\n labels_tf: labels_np, logits_tf: logits_np})\n\n\ndef apply_black_border(x, image_height, image_width, border_size):\n x = tf.image.resize_images(x, (image_width - border_size,\n image_height - border_size))\n x = tf.pad(x, [[0, 0],\n [border_size, border_size],\n [border_size, border_size],\n [0, 0]], 'CONSTANT')\n return x\n\n\ndef apply_transformation(x, transform, image_height, image_width):\n # Map a transformation onto the input\n trans_x, trans_y, rot = tf.unstack(transform, axis=1)\n rot *= np.pi / 180 # convert degrees to radians\n\n # Pad the image to prevent two-step rotation / translation\n # resulting in a cropped image\n x = tf.pad(x, [[0, 0], [50, 50], [50, 50], [0, 0]], 'CONSTANT')\n\n # rotate and translate image\n ones = tf.ones(shape=tf.shape(trans_x))\n zeros = tf.zeros(shape=tf.shape(trans_x))\n trans = tf.stack([ones, zeros, -trans_x,\n zeros, ones, -trans_y,\n zeros, zeros], axis=1)\n x = tf.contrib.image.rotate(x, rot, interpolation='BILINEAR')\n x = tf.contrib.image.transform(x, trans, interpolation='BILINEAR')\n return tf.image.resize_image_with_crop_or_pad(\n x, image_height, image_width)\n\n\nclass CleverhansPyfuncModelWrapper(Model):\n nb_classes = 2\n num_classes = 2\n\n def __init__(self, model_fn):\n \"\"\"\n Wrap a callable function that takes a numpy array of shape (N, C, H, W),\n and outputs a numpy vector of length N, with each element in range [0, 1].\n \"\"\"\n self.model_fn = model_fn\n\n def fprop(self, x, **kwargs):\n logits_op = tf.py_func(self.model_fn, [x], tf.float32)\n return {'logits': logits_op}\n\n\nclass RandomSpatialAttack(Attack):\n \"\"\"Apply a single random rotation and translation\n as in \"A Rotation and a Translation Suffice: Fooling CNNs with\n Simple Transformations\", Engstrom et al. 2018\n\n https://arxiv.org/pdf/1712.02779.pdf\n \"\"\"\n name = 'random_spatial'\n\n def __init__(self, image_shape_hwc, spatial_limits, black_border_size, valid_check=None):\n self.limits = spatial_limits\n self.valid_check = valid_check\n\n # Construct graph for spatial attack\n self.graph = tf.Graph()\n with self.graph.as_default():\n self._x_for_trans = tf.placeholder(tf.float32, shape=[None] + list(image_shape_hwc))\n self._t_for_trans = tf.placeholder(tf.float32, shape=[None, 3])\n\n x = apply_black_border(\n self._x_for_trans,\n image_height=image_shape_hwc[0],\n image_width=image_shape_hwc[1],\n border_size=black_border_size\n )\n\n self._tranformed_x_op = apply_transformation(\n x,\n transform=self._t_for_trans,\n image_height=image_shape_hwc[0],\n image_width=image_shape_hwc[1],\n )\n self.session = tf.Session()\n\n def __call__(self, model_fn, x_np, y_np):\n # randomize each example separately\n\n with self.graph.as_default():\n result = np.zeros(x_np.shape, dtype=x_np.dtype)\n did = np.zeros(x_np.shape[0], dtype=np.bool)\n\n trans_np = np.stack(\n repeat([0, 0, 0], x_np.shape[0]))\n x_downsize_np = self.session.run(self._tranformed_x_op, feed_dict={\n self._x_for_trans: x_np,\n self._t_for_trans: trans_np,\n })\n\n while True:\n random_transforms = (np.random.uniform(-lim, lim, len(x_np)) for lim in self.limits)\n trans_np = np.stack(random_transforms, axis=1)\n out = self.session.run(self._tranformed_x_op, feed_dict={\n self._x_for_trans: x_np,\n self._t_for_trans: trans_np,\n })\n\n if self.valid_check is None:\n return out\n else:\n ok = self.valid_check(x_downsize_np, out)\n result[ok] = out[ok]\n did[ok] = True\n if np.all(did):\n return result\n\n\nclass SpsaWithRandomSpatialAttack(Attack):\n \"\"\"Apply a single random rotation and translation and then apply SPSA\n to the resulting image\n \"\"\"\n name = \"spsa_with_random_spatial\"\n\n def __init__(self, model, image_shape_hwc, spatial_limits, black_border_size,\n epsilon=(16. / 255), num_steps=32, is_debug=False,\n valid_check=None):\n self.random_spatial_attack = RandomSpatialAttack(\n image_shape_hwc,\n valid_check=valid_check,\n spatial_limits=spatial_limits,\n black_border_size=black_border_size)\n\n self.spsa_attack = SpsaAttack(\n model,\n image_shape_hwc,\n epsilon=epsilon,\n num_steps=num_steps,\n batch_size=64, # this is number of samples in the new cleverhans\n is_debug=is_debug)\n\n def __call__(self, model, x_np, y_np):\n x_after_spatial_np = self.random_spatial_attack(model, x_np, y_np)\n x_adv = self.spsa_attack(model, x_after_spatial_np, y_np)\n return x_adv\n\n\nclass BoundaryWithRandomSpatialAttack(Attack):\n \"\"\"Apply a single random rotation and translation and then apply SPSA\n to the resulting image\n \"\"\"\n name = \"boundary_with_random_spatial\"\n\n def __init__(self, model, image_shape_hwc, spatial_limits, black_border_size,\n max_l2_distortion=4, label_to_examples=None, valid_check=None):\n self.random_spatial_attack = RandomSpatialAttack(\n image_shape_hwc,\n valid_check=valid_check,\n spatial_limits=spatial_limits,\n black_border_size=black_border_size)\n\n self.boundary_attack = BoundaryAttack(\n model,\n max_l2_distortion=max_l2_distortion,\n image_shape_hwc=image_shape_hwc,\n label_to_examples=label_to_examples)\n\n def __call__(self, model, x_np, y_np):\n x_after_spatial_np = self.random_spatial_attack(model, x_np, y_np)\n x_adv = self.boundary_attack(model, x_after_spatial_np, y_np)\n return x_adv\n"
] | [
[
"numpy.expand_dims",
"numpy.linspace",
"numpy.asarray",
"tensorflow.stack",
"numpy.concatenate",
"numpy.all",
"tensorflow.pad",
"numpy.where",
"tensorflow.py_func",
"tensorflow.Graph",
"numpy.stack",
"numpy.copy",
"numpy.argmax",
"tensorflow.contrib.image.transform",
"tensorflow.Session",
"numpy.zeros",
"tensorflow.unstack",
"tensorflow.shape",
"tensorflow.image.resize_images",
"tensorflow.placeholder",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits",
"numpy.equal",
"numpy.array",
"numpy.sum",
"tensorflow.image.resize_image_with_crop_or_pad",
"numpy.maximum",
"tensorflow.contrib.image.rotate",
"numpy.ones"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
}
] |
michaelneuder/parkes_lab_fa19 | [
"18d9f564e0df9c17ac5d54619ed869d778d4f6a4",
"18d9f564e0df9c17ac5d54619ed869d778d4f6a4",
"18d9f564e0df9c17ac5d54619ed869d778d4f6a4"
] | [
"proof_of_work/multiagent/turn_based/v4/selfishagentv4.py",
"proof_of_work/multiagent/turn_based/v5/environmentv5.py",
"costmdps/v9/costmdpcustomv9.py"
] | [
"import numpy as np\n\nclass SelfishAgent(object):\n def __init__(self, T):\n self.T = T\n self.policy = np.asarray([\n [0, 0, 0, 0, 0, 0, 0, 0, 0], \n [2, 2, 2, 0, 0, 0, 0, 0, 0], \n [2, 1, 2, 2, 2, 0, 0, 0, 0], \n [2, 2, 1, 2, 2, 2, 0, 0, 0], \n [2, 2, 2, 1, 2, 2, 2, 0, 0], \n [2, 2, 2, 2, 1, 2, 2, 2, 0], \n [2, 2, 2, 2, 2, 1, 2, 2, 0], \n [2, 2, 2, 2, 2, 2, 1, 2, 0], \n [1, 1, 1, 1, 1, 1, 1, 1, 1]\n ])\n\n def act(self, state):\n a, h = state\n if h == self.T:\n return 'adopt'\n if a == self.T:\n return 'override'\n if h > a:\n return 'adopt'\n # if (h == a) and (h == 1):\n # return 'match'\n if (h == a-1) and (h >= 1):\n return 'override'\n return 'wait'\n \n def act2(self, state):\n action = self.policy[state]\n if action == 0:\n return 'adopt'\n if action == 1:\n return 'override'\n return 'wait'\n\n ",
"import numpy as np\nnp.random.seed(0)\n\nADOPT = 0\nOVERRIDE = 1\nWAIT = 2\n\nclass Environment(object):\n def __init__(self, mining_powers, gammas, T):\n # relative mining strengths.\n self.mining_powers = mining_powers\n self.gammas = gammas\n self.num_miners = len(mining_powers)\n \n # termination parameters\n self.T = T\n\n # chain variables\n self.chain = ''\n self.starting_points = np.zeros(self.num_miners, dtype=np.int64)\n self.hidden_lengths = np.zeros(self.num_miners, dtype=np.int64)\n \n def reset(self):\n self.chain = ''\n self.starting_points = np.zeros(self.num_miners, dtype=np.int64)\n self.hidden_lengths = np.zeros(self.num_miners, dtype=np.int64)\n\n def getNextBlockWinner(self):\n winner = np.random.choice(np.arange(len(self.mining_powers)), p=self.mining_powers)\n self.hidden_lengths[winner] += 1\n return winner\n \n def adopt(self, player_index):\n _a, h = self.getState(player_index)\n self.starting_points[player_index] = len(self.chain)\n self.hidden_lengths[player_index] = 0\n return self.getState(player_index), (0, h)\n \n def wait(self, player_index):\n a, h = self.getState(player_index)\n if (a == self.T) or (h == self.T):\n return self.adopt(player_index)\n return self.getState(player_index), (0, 0)\n \n def override(self, player_index):\n a, h = self.getState(player_index)\n if a <= h:\n self.starting_points[player_index] = len(self.chain)\n self.hidden_lengths[player_index] = 0\n return self.getState(player_index), (0, 10)\n \n # chop chain to proper length\n self.chain = self.chain[:self.starting_points[player_index]]\n new_blocks = str(player_index) * a\n self.chain += new_blocks\n self.starting_points[player_index] = len(self.chain)\n self.hidden_lengths[player_index] = 0\n return self.getState(player_index), (a, 0)\n\n def getState(self, player_index):\n return (self.hidden_lengths[player_index], len(self.chain)-self.starting_points[player_index])\n \n def takeActionPlayer(self, player_index, action):\n if action == ADOPT:\n return self.adopt(player_index)\n elif action == OVERRIDE:\n return self.override(player_index)\n elif action == WAIT:\n return self.wait(player_index)\n else:\n raise KeyError('{} is not an action'.format(action))\n\nif __name__ == \"__main__\":\n powers = [0.55, 0.45]\n gammas = [0.5, 0.5]\n env = Environment(powers, gammas, T=9)\n chain = ''\n for _ in range(1000):\n chain += str(env.getNextBlockWinner())\n print('p0', chain.count('0'), chain.count('0')/len(chain))\n print('p1', chain.count('1'), chain.count('1')/len(chain))\n print('p2', chain.count('2'), chain.count('2')/len(chain))\n ",
"import matplotlib.pyplot as plt\nimport numpy as np\nimport progressbar as pb\nimport scipy.sparse as ss\nimport seaborn as sns\nfrom valueiterationv9 import value_iteration\nimport warnings\nwarnings.filterwarnings('ignore', category=ss.SparseEfficiencyWarning)\n\nADOPT = 0\nOVERRIDE = 1\nMINE = 2\nMATCH = 3\n\nIRRELEVANT = 0\nRELEVANT = 1\nACTIVE = 2\n\nclass CostMDP(object):\n def __init__(self, alpha, gamma, T, mining_cost, epsilon=10e-6):\n # params\n self.alpha = alpha\n self.gamma = gamma\n self.T = T\n self.mining_cost = mining_cost\n self.epsilon = epsilon\n\n # game\n self.action_count = 4\n self.fork_count = 3\n self.state_count = (T + 1) * (T + 1) * self.fork_count\n\n # mdp helpers\n self.state_mapping = {}\n self.states = []\n\n # matrices\n self.transitions = []\n self.rewards = []\n\n def initMDPHelpers(self):\n count = 0\n for a in range(self.T+1):\n for h in range(self.T+1):\n for fork in range(self.fork_count):\n self.state_mapping[(a, h, fork)] = count\n self.states.append((a, h, fork))\n count += 1\n \n def initMatrices(self):\n for _ in range(self.action_count):\n self.transitions.append(ss.csr_matrix(np.zeros(shape=(self.state_count, self.state_count))))\n self.rewards.append(ss.csr_matrix(np.zeros(shape=(self.state_count, self.state_count))))\n \n def populateMatrices(self):\n for state_index in range(self.state_count):\n a, h, fork = self.states[state_index]\n\n # adopt\n self.transitions[ADOPT][state_index, self.state_mapping[0, 0, IRRELEVANT]] = 1\n\n # override\n if a > h:\n self.transitions[OVERRIDE][state_index, self.state_mapping[a-h-1, 0, IRRELEVANT]] = 1\n self.rewards[OVERRIDE][state_index, self.state_mapping[a-h-1, 0, IRRELEVANT]] = h + 1\n else:\n self.transitions[OVERRIDE][state_index, 0] = 1\n self.rewards[OVERRIDE][state_index, 0] = -10000\n\n # mine \n if (fork != ACTIVE) and (a < self.T) and (h < self.T):\n self.transitions[MINE][state_index, self.state_mapping[a+1, h, IRRELEVANT]] = self.alpha\n self.transitions[MINE][state_index, self.state_mapping[a, h+1, RELEVANT]] = (1 - self.alpha) \n self.rewards[MINE][state_index, self.state_mapping[a+1, h, IRRELEVANT]] = -1 * self.alpha * self.mining_cost\n self.rewards[MINE][state_index, self.state_mapping[a, h+1, RELEVANT]] = -1 * self.alpha * self.mining_cost \n elif (fork == ACTIVE) and (a > h) and (h > 0) and (a < self.T) and (h < self.T):\n self.transitions[MINE][state_index, self.state_mapping[a+1, h, ACTIVE]] = self.alpha\n self.transitions[MINE][state_index, self.state_mapping[a-h, 1, RELEVANT]] = (1 - self.alpha) * self.gamma\n self.transitions[MINE][state_index, self.state_mapping[a, h+1, RELEVANT]] = (1 - self.alpha) * (1 - self.gamma)\n self.rewards[MINE][state_index, self.state_mapping[a+1, h, ACTIVE]] = -1 * self.alpha * self.mining_cost\n self.rewards[MINE][state_index, self.state_mapping[a-h, 1, RELEVANT]] = h - self.alpha * self.mining_cost\n self.rewards[MINE][state_index, self.state_mapping[a, h+1, RELEVANT]] = -1 * self.alpha * self.mining_cost\n else:\n self.transitions[MINE][state_index, 0] = 1\n self.rewards[MINE][state_index, 0] = -10000\n \n # match \n if (fork == RELEVANT) and (a >= h) and (h > 0) and (a < self.T) and (h < self.T):\n self.transitions[MATCH][state_index, self.state_mapping[a+1, h, ACTIVE]] = self.alpha\n self.transitions[MATCH][state_index, self.state_mapping[a-h, 1, RELEVANT]] = (1 - self.alpha) * self.gamma\n self.transitions[MATCH][state_index, self.state_mapping[a, h+1, RELEVANT]] = (1 - self.alpha) * (1 - self.gamma)\n self.rewards[MATCH][state_index, self.state_mapping[a+1, h, ACTIVE]] = -1 * self.alpha * self.mining_cost\n self.rewards[MATCH][state_index, self.state_mapping[a-h, 1, RELEVANT]] = h - self.alpha * self.mining_cost\n self.rewards[MATCH][state_index, self.state_mapping[a, h+1, RELEVANT]] = -1 * self.alpha * self.mining_cost\n else:\n self.transitions[MATCH][state_index, 0] = 1\n self.rewards[MATCH][state_index, 0] = -10000\n \n def getOptPolicy(self):\n policy, _ = value_iteration(\n self.action_count, len(self.states), self.transitions, self.rewards)\n return policy\n\n def printPolicy(self, policy): \n results = ''\n for a in range(9):\n for h in range(9):\n for fork in range(3):\n state_index = self.state_mapping[(a, h, fork)]\n action = policy[state_index]\n if action == 0:\n results += 'a'\n elif action == 1:\n results += 'o'\n elif action == 2:\n results += 'w'\n elif action == 3:\n results += 'm'\n else:\n raise RuntimeError('invalid action')\n results += ' & '\n results += '\\\\\\\\ \\n'\n print(results)\n \n def getAction(self, policy, state):\n state_index = self.state_mapping[state]\n return policy[state_index]\n\n def solveWithPolicy(self):\n self.initMDPHelpers()\n self.initMatrices()\n self.populateMatrices()\n return self.getOptPolicy()\n \nif __name__ == \"__main__\":\n alpha = 0.4\n gamma = 0.5\n T = 8\n mining_cost = 0.5\n cost_mdp = CostMDP(alpha = alpha, gamma = gamma, T = T, mining_cost = mining_cost)\n cost_mdp.initMDPHelpers()\n cost_mdp.initMatrices()\n cost_mdp.populateMatrices()\n policy = cost_mdp.getOptPolicy()\n cost_mdp.printPolicy(policy)\n"
] | [
[
"numpy.asarray"
],
[
"numpy.zeros",
"numpy.random.seed"
],
[
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
qinvador/qiskit-terra | [
"4e104de3c113c01688a0ed06b2f2cb1a958fce44",
"4e104de3c113c01688a0ed06b2f2cb1a958fce44"
] | [
"qiskit/extensions/standard/u2.py",
"qiskit/extensions/standard/t.py"
] | [
"# -*- coding: utf-8 -*-\n\n# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"\nOne-pulse single-qubit gate.\n\"\"\"\nimport numpy\nfrom qiskit.circuit import Gate\nfrom qiskit.circuit import QuantumCircuit\nfrom qiskit.circuit import QuantumRegister\nfrom qiskit.qasm import pi\nfrom qiskit.util import deprecate_arguments\n\n\nclass U2Gate(Gate):\n \"\"\"One-pulse single-qubit gate.\"\"\"\n\n def __init__(self, phi, lam, label=None):\n \"\"\"Create new one-pulse single-qubit gate.\"\"\"\n super().__init__('u2', 1, [phi, lam], label=label)\n\n def _define(self):\n from qiskit.extensions.standard.u3 import U3Gate\n definition = []\n q = QuantumRegister(1, 'q')\n rule = [(U3Gate(pi / 2, self.params[0], self.params[1]), [q[0]], [])]\n for inst in rule:\n definition.append(inst)\n self.definition = definition\n\n def inverse(self):\n \"\"\"Invert this gate.\n\n u2(phi,lamb)^dagger = u2(-lamb-pi,-phi+pi)\n \"\"\"\n return U2Gate(-self.params[1] - pi, -self.params[0] + pi)\n\n def to_matrix(self):\n \"\"\"Return a Numpy.array for the U2 gate.\"\"\"\n isqrt2 = 1 / numpy.sqrt(2)\n phi, lam = self.params\n phi, lam = float(phi), float(lam)\n return numpy.array([\n [\n isqrt2,\n -numpy.exp(1j * lam) * isqrt2\n ],\n [\n numpy.exp(1j * phi) * isqrt2,\n numpy.exp(1j * (phi + lam)) * isqrt2\n ]\n ], dtype=complex)\n\n\n@deprecate_arguments({'q': 'qubit'})\ndef u2(self, phi, lam, qubit, *, q=None): # pylint: disable=invalid-name,unused-argument\n \"\"\"Apply U2 gate with angle phi and lam to a specified qubit (qubit).\n u2(φ,λ) := U(π/2,φ,λ) = Rz(φ + π/2)Rx(π/2)Rz(λ − π/2)\n\n Examples:\n\n Circuit Representation:\n\n .. jupyter-execute::\n\n from qiskit.circuit import QuantumCircuit, Parameter\n\n phi = Parameter('φ')\n lam = Parameter('λ')\n circuit = QuantumCircuit(1)\n circuit.u2(phi,lam,0)\n circuit.draw()\n\n Matrix Representation:\n\n .. jupyter-execute::\n\n import numpy\n from qiskit.extensions.standard.u2 import U2Gate\n U2Gate(numpy.pi/2,numpy.pi/2).to_matrix()\n \"\"\"\n return self.append(U2Gate(phi, lam), [qubit], [])\n\n\nQuantumCircuit.u2 = u2\n",
"# -*- coding: utf-8 -*-\n\n# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2017.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\n\"\"\"\nT=sqrt(S) phase gate or its inverse.\n\"\"\"\nimport numpy\nfrom qiskit.circuit import Gate\nfrom qiskit.circuit import QuantumCircuit\nfrom qiskit.circuit import QuantumRegister\nfrom qiskit.qasm import pi\nfrom qiskit.util import deprecate_arguments\n\n\nclass TGate(Gate):\n \"\"\"T Gate: pi/4 rotation around Z axis.\"\"\"\n\n def __init__(self, label=None):\n \"\"\"Create new T gate.\"\"\"\n super().__init__('t', 1, [], label=label)\n\n def _define(self):\n \"\"\"\n gate t a { u1(pi/4) a; }\n \"\"\"\n from qiskit.extensions.standard.u1 import U1Gate\n definition = []\n q = QuantumRegister(1, 'q')\n rule = [\n (U1Gate(pi / 4), [q[0]], [])\n ]\n for inst in rule:\n definition.append(inst)\n self.definition = definition\n\n def inverse(self):\n \"\"\"Invert this gate.\"\"\"\n return TdgGate()\n\n def to_matrix(self):\n \"\"\"Return a numpy.array for the T gate.\"\"\"\n return numpy.array([[1, 0],\n [0, (1 + 1j) / numpy.sqrt(2)]], dtype=complex)\n\n\nclass TdgGate(Gate):\n \"\"\"Tdg Gate: -pi/4 rotation around Z axis.\"\"\"\n\n def __init__(self, label=None):\n \"\"\"Create a new Tdg gate.\"\"\"\n super().__init__('tdg', 1, [], label=label)\n\n def _define(self):\n \"\"\"\n gate tdg a { u1(pi/4) a; }\n \"\"\"\n from qiskit.extensions.standard.u1 import U1Gate\n definition = []\n q = QuantumRegister(1, 'q')\n rule = [\n (U1Gate(-pi / 4), [q[0]], [])\n ]\n for inst in rule:\n definition.append(inst)\n self.definition = definition\n\n def inverse(self):\n \"\"\"Invert this gate.\"\"\"\n return TGate()\n\n def to_matrix(self):\n \"\"\"Return a numpy.array for the inverse T gate.\"\"\"\n return numpy.array([[1, 0],\n [0, (1 - 1j) / numpy.sqrt(2)]], dtype=complex)\n\n\n@deprecate_arguments({'q': 'qubit'})\ndef t(self, qubit, *, q=None): # pylint: disable=invalid-name,unused-argument\n \"\"\"Apply T gate to a specified qubit (qubit).\n A T gate implements a pi/4 rotation of a qubit state vector about the\n z axis of the Bloch sphere.\n\n Examples:\n\n Circuit Representation:\n\n .. jupyter-execute::\n\n from qiskit import QuantumCircuit\n\n circuit = QuantumCircuit(1)\n circuit.t(0)\n circuit.draw()\n\n Matrix Representation:\n\n .. jupyter-execute::\n\n from qiskit.extensions.standard.t import TGate\n TGate().to_matrix()\n \"\"\"\n return self.append(TGate(), [qubit], [])\n\n\n@deprecate_arguments({'q': 'qubit'})\ndef tdg(self, qubit, *, q=None): # pylint: disable=unused-argument\n \"\"\"Apply Tdg gate to a specified qubit (qubit).\n A Tdg gate implements a -pi/4 rotation of a qubit state vector about the\n z axis of the Bloch sphere. It is the inverse of T-gate.\n\n Examples:\n\n Circuit Representation:\n\n .. jupyter-execute::\n\n from qiskit import QuantumCircuit\n\n circuit = QuantumCircuit(1)\n circuit.tdg(0)\n circuit.draw()\n\n Matrix Representation:\n\n .. jupyter-execute::\n\n from qiskit.extensions.standard.t import TdgGate\n TdgGate().to_matrix()\n \"\"\"\n return self.append(TdgGate(), [qubit], [])\n\n\nQuantumCircuit.t = t\nQuantumCircuit.tdg = tdg\n"
] | [
[
"numpy.exp",
"numpy.sqrt"
],
[
"numpy.sqrt"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
a1600012888/mmdetection3d | [
"2e01549c56dabf1965abc975a7301a8d746973ad",
"2e01549c56dabf1965abc975a7301a8d746973ad",
"2e01549c56dabf1965abc975a7301a8d746973ad",
"2e01549c56dabf1965abc975a7301a8d746973ad"
] | [
"plugin/radar/depth_net.py",
"plugin/depth_v3/model.py",
"tests/test_data/test_datasets/test_nuscenes_mono_dataset.py",
"tools/surrdet/get_scene_flow.py"
] | [
"# Copyright 2020 Toyota Research Institute. All rights reserved.\n\nimport torch\nimport torch.nn as nn\nfrom .layers01 import \\\n PackLayerConv3d, UnpackLayerConv3d, Conv2D, ResidualBlock, InvDepth\n\nfrom .utils import DepthPredictHead2Up, get_depth_metrics\nfrom mmdet.models import DETECTORS\nimport torch.nn.functional as F\n\[email protected]_module()\nclass PackNetSlim01(nn.Module):\n \"\"\"\n PackNet network with 3d convolutions (version 01, from the CVPR paper).\n Slimmer version, with fewer feature channels\n\n https://arxiv.org/abs/1905.02693\n\n Parameters\n ----------\n dropout : float\n Dropout value to use\n version : str\n Has a XY format, where:\n X controls upsampling variations (not used at the moment).\n Y controls feature stacking (A for concatenation and B for addition)\n kwargs : dict\n Extra parameters\n \"\"\"\n def __init__(self, dropout=None, version=None, min_depth=0.5, **kwargs):\n super().__init__()\n self.version = version[1:]\n # Input/output channels\n in_channels = 3\n out_channels = 1\n # Hyper-parameters\n ni, no = 32, out_channels\n n1, n2, n3, n4, n5 = 16, 32, 64, 128, 256\n #n1, n2, n3, n4, n5 = 32, 64, 128, 256, 512\n num_blocks = [2, 2, 3, 3]\n pack_kernel = [5, 3, 3, 3, 3]\n unpack_kernel = [3, 3, 3, 3, 3]\n iconv_kernel = [3, 3, 3, 3, 3]\n num_3d_feat = 4\n # Initial convolutional layer\n #self.down_sample_conv = Conv2D(in_channels, 16, 5, 2)\n self.pre_calc = Conv2D(in_channels, ni, 5, 1)\n # Support for different versions\n if self.version == 'A': # Channel concatenation\n n1o, n1i = n1, n1 + ni + no\n n2o, n2i = n2, n2 + n1 + no\n n3o, n3i = n3, n3 + n2 + no\n n4o, n4i = n4, n4 + n3\n n5o, n5i = n5, n5 + n4\n elif self.version == 'B': # Channel addition\n n1o, n1i = n1, n1 + no\n n2o, n2i = n2, n2 + no\n n3o, n3i = n3//2, n3//2 + no\n n4o, n4i = n4//2, n4//2\n n5o, n5i = n5//2, n5//2\n else:\n raise ValueError('Unknown PackNet version {}'.format(version))\n\n # Encoder\n\n self.pack1 = PackLayerConv3d(n1, pack_kernel[0], d=num_3d_feat)\n self.pack2 = PackLayerConv3d(n2, pack_kernel[1], d=num_3d_feat)\n self.pack3 = PackLayerConv3d(n3, pack_kernel[2], d=num_3d_feat)\n self.pack4 = PackLayerConv3d(n4, pack_kernel[3], d=num_3d_feat)\n self.pack5 = PackLayerConv3d(n5, pack_kernel[4], d=num_3d_feat)\n\n self.conv1 = Conv2D(ni, n1, 7, 1)\n self.conv2 = ResidualBlock(n1, n2, num_blocks[0], 1, dropout=dropout)\n self.conv3 = ResidualBlock(n2, n3, num_blocks[1], 1, dropout=dropout)\n self.conv4 = ResidualBlock(n3, n4, num_blocks[2], 1, dropout=dropout)\n self.conv5 = ResidualBlock(n4, n5, num_blocks[3], 1, dropout=dropout)\n\n # Decoder\n\n self.unpack5 = UnpackLayerConv3d(n5, n5o, unpack_kernel[0], d=num_3d_feat)\n self.unpack4 = UnpackLayerConv3d(n5, n4o, unpack_kernel[1], d=num_3d_feat)\n self.unpack3 = UnpackLayerConv3d(n4, n3o, unpack_kernel[2], d=num_3d_feat)\n self.unpack2 = UnpackLayerConv3d(n3, n2o, unpack_kernel[3], d=num_3d_feat)\n self.unpack1 = UnpackLayerConv3d(n2, n1o, unpack_kernel[4], d=num_3d_feat)\n\n self.iconv5 = Conv2D(n5i, n5, iconv_kernel[0], 1)\n self.iconv4 = Conv2D(n4i, n4, iconv_kernel[1], 1)\n self.iconv3 = Conv2D(n3i, n3, iconv_kernel[2], 1)\n self.iconv2 = Conv2D(n2i, n2, iconv_kernel[3], 1)\n self.iconv1 = Conv2D(n1i, n1, iconv_kernel[4], 1)\n\n # Depth Layers\n\n self.unpack_disps = nn.PixelShuffle(2)\n self.unpack_disp4 = nn.Upsample(scale_factor=2, mode='nearest', align_corners=None)\n self.unpack_disp3 = nn.Upsample(scale_factor=2, mode='nearest', align_corners=None)\n self.unpack_disp2 = nn.Upsample(scale_factor=2, mode='nearest', align_corners=None)\n\n self.disp4_layer = InvDepth(n4, out_channels=out_channels, min_depth=min_depth)\n self.disp3_layer = InvDepth(n3, out_channels=out_channels, min_depth=min_depth)\n self.disp2_layer = InvDepth(n2, out_channels=out_channels, min_depth=min_depth)\n self.disp1_layer = InvDepth(n1, out_channels=out_channels, min_depth=min_depth)\n\n self.init_weights()\n\n def init_weights(self):\n \"\"\"Initializes network weights.\"\"\"\n for m in self.modules():\n if isinstance(m, (nn.Conv2d, nn.Conv3d)):\n nn.init.xavier_uniform_(m.weight)\n if m.bias is not None:\n m.bias.data.zero_()\n\n def get_pred(self, data, **kwargs):\n \"\"\"\n Runs the network and returns inverse depth maps\n (4 scales if training and 1 if not).\n \"\"\"\n # x = data['img']\n x = data\n #x = self.down_sample_conv(x)\n x = self.pre_calc(x)\n\n # Encoder\n\n x1 = self.conv1(x)\n x1p = self.pack1(x1)\n x2 = self.conv2(x1p)\n x2p = self.pack2(x2)\n x3 = self.conv3(x2p)\n x3p = self.pack3(x3)\n x4 = self.conv4(x3p)\n x4p = self.pack4(x4)\n x5 = self.conv5(x4p)\n x5p = self.pack5(x5)\n\n # Skips\n\n skip1 = x\n skip2 = x1p\n skip3 = x2p\n skip4 = x3p\n skip5 = x4p\n\n # Decoder\n\n unpack5 = self.unpack5(x5p)\n if self.version == 'A':\n concat5 = torch.cat((unpack5, skip5), 1)\n else:\n concat5 = unpack5 + skip5\n iconv5 = self.iconv5(concat5)\n\n unpack4 = self.unpack4(iconv5)\n if self.version == 'A':\n concat4 = torch.cat((unpack4, skip4), 1)\n else:\n concat4 = unpack4 + skip4\n iconv4 = self.iconv4(concat4)\n inv_depth4 = self.disp4_layer(iconv4)\n up_inv_depth4 = self.unpack_disp4(inv_depth4)\n\n unpack3 = self.unpack3(iconv4)\n if self.version == 'A':\n concat3 = torch.cat((unpack3, skip3, up_inv_depth4), 1)\n else:\n concat3 = torch.cat((unpack3 + skip3, up_inv_depth4), 1)\n iconv3 = self.iconv3(concat3)\n inv_depth3 = self.disp3_layer(iconv3)\n up_inv_depth3 = self.unpack_disp3(inv_depth3)\n\n unpack2 = self.unpack2(iconv3)\n if self.version == 'A':\n concat2 = torch.cat((unpack2, skip2, up_inv_depth3), 1)\n else:\n concat2 = torch.cat((unpack2 + skip2, up_inv_depth3), 1)\n iconv2 = self.iconv2(concat2)\n inv_depth2 = self.disp2_layer(iconv2)\n up_inv_depth2 = self.unpack_disp2(inv_depth2)\n\n unpack1 = self.unpack1(iconv2)\n if self.version == 'A':\n concat1 = torch.cat((unpack1, skip1, up_inv_depth2), 1)\n else:\n concat1 = torch.cat((unpack1 + skip1, up_inv_depth2), 1)\n iconv1 = self.iconv1(concat1)\n inv_depth1 = self.disp1_layer(iconv1)\n\n if self.training:\n inv_depths = [inv_depth1, inv_depth2, inv_depth3, inv_depth4]\n #inv_depths = [inv_depth1]\n else:\n inv_depths = [inv_depth1]\n\n #inv_depths = [F.interpolate(t_inv_depth, scale_factor=2, mode=\"bilinear\", align_corners=False) for t_inv_depth in inv_depths]\n # ret depth pred\n return inv_depths\n\n def forward(self, return_loss=True, rescale=False, **kwargs):\n\n if not return_loss:\n # in evalhook!\n\n x = kwargs['img']\n label = kwargs['depth_map']\n\n data = {'img':x, 'depth_map':label}\n depth_pred = self.get_pred(data)[0]\n label = data['depth_map'].unsqueeze(dim=1)\n mask = (label > 0)\n\n #print(depth_pred.shape, label.shape, mask.shape, 'data shape')\n loss = torch.abs((label - depth_pred)) * mask\n loss = torch.sum(loss) / torch.sum(mask)\n\n with torch.no_grad():\n metrics = get_depth_metrics(depth_pred, label, mask)\n # abs_diff, abs_rel, sq_rel, rmse, rmse_log\n metrics = [m.item() for m in metrics]\n\n # hack the hook\n # outputs[0]=None. see https://github.com/open-mmlab/mmdetection/blob/master/mmdet/apis/test.py#L99\n #outputs = {'loss': loss, 'log_vars':log_vars, 'num_samples':depth_pred.size(0), 0:None}\n #print('val', loss)\n metrics.append(loss.item())\n return [metrics]\n raise NotImplementedError\n\n def train_step(self, data, optimzier):\n depth_pred = self.get_pred(data)[0]\n label = data['depth_map'].unsqueeze(dim=1)\n mask = (label > 0)\n\n #print(depth_pred.shape, label.shape, mask.shape, 'data shape')\n #from IPython import embed\n #embed()\n loss = torch.abs((label - depth_pred)) * mask\n\n loss = torch.sum(loss) / torch.sum(mask)\n\n log_var = {}\n with torch.no_grad():\n metrics = get_depth_metrics(depth_pred, label, mask)\n # abs_diff, abs_rel, sq_rel, rmse, rmse_log\n metrics = [m.item() for m in metrics]\n abs_diff, abs_rel, sq_rel, rmse, rmse_log = metrics\n sparsity = torch.sum(mask) * 1.0 / torch.numel(mask)\n\n\n std = torch.tensor([58.395, 57.12, 57.375]).cuda().view(1, -1, 1, 1)\n mean = torch.tensor([123.675, 116.28, 103.53]).cuda().view(1, -1, 1, 1)\n img = data['img'] * std + mean\n img = img / 255.0\n depth_at_gt = depth_pred * mask\n log_vars = {'loss': loss.item(), 'sparsity': sparsity.item(),\n 'abs_diff': abs_diff, 'abs_rel': abs_rel,\n 'sq_rel': sq_rel, 'rmse': rmse,\n 'rmse_log': rmse_log\n }\n # 'pred', 'data', 'label', 'depth_at_gt' is used for visualization only!\n outputs = {'pred': torch.clamp(1.0 / (depth_pred+1e-4), 0, 1), 'data': img,\n 'label': torch.clamp(1.0 / (label+1e-4), 0, 1),\n 'depth_at_gt': torch.clamp(1.0 / (depth_at_gt+1e-4), 0., 1),\n 'loss':loss, 'log_vars':log_vars, 'num_samples':depth_pred.size(0)}\n\n return outputs\n\n def val_step(self, data, optimizer):\n\n return self.train_step(self, data, optimizer)\n",
"from mmdet.models import DETECTORS\nimport torch\nimport torch.nn as nn\nfrom mmcv.runner import auto_fp16\nfrom mmdet.models.backbones import ResNetV1d\nfrom .utils import DepthPredictHead2Up, get_depth_metrics\n\[email protected]_module()\nclass ResDepthModel(nn.Module):\n\n def __init__(self, depth=50,\n strides=(1, 2, 2, 2),\n dilations=(1, 1, 1, 2),\n out_indices=(0, 1, 2, 3),\n base_channels=64,\n **kwargs):\n super(ResDepthModel, self).__init__()\n self.backbone = ResNetV1d(depth=depth,\n strides=strides,\n dilations=dilations,\n out_indices=out_indices,\n base_channels=base_channels)\n # output channel =\n\n feat_dim = self.backbone.feat_dim\n self.head = DepthPredictHead2Up(feat_dim)\n\n\n def get_pred(self, data):\n x = data['img']\n\n features = self.backbone(x)\n\n last_feat = features[-1]\n\n pred = self.head(last_feat)\n\n return pred\n\n def forward(self, return_loss=True, rescale=False, **kwargs):\n\n if not return_loss:\n # in evalhook!\n\n x = kwargs['img']\n label = kwargs['depth_map']\n\n data = {'img':x, 'depth_map':label}\n depth_pred = self.get_pred(data)\n label = data['depth_map'].unsqueeze(dim=1)\n mask = (label > 0)\n\n #print(depth_pred.shape, label.shape, mask.shape, 'data shape')\n loss = torch.abs((label - depth_pred)) * mask\n loss = torch.sum(loss) / torch.sum(mask)\n\n with torch.no_grad():\n metrics = get_depth_metrics(depth_pred, label, mask)\n # abs_diff, abs_rel, sq_rel, rmse, rmse_log\n metrics = [m.item() for m in metrics]\n\n # hack the hook\n # outputs[0]=None. see https://github.com/open-mmlab/mmdetection/blob/master/mmdet/apis/test.py#L99\n #outputs = {'loss': loss, 'log_vars':log_vars, 'num_samples':depth_pred.size(0), 0:None}\n #print('val', loss)\n metrics.append(loss.item())\n return [metrics]\n raise NotImplementedError\n\n def train_step(self, data, optimzier):\n depth_pred = self.get_pred(data)\n label = data['depth_map'].unsqueeze(dim=1)\n mask = (label > 0)\n\n #print(depth_pred.shape, label.shape, mask.shape, 'data shape')\n #from IPython import embed\n #embed()\n loss = torch.abs((label - depth_pred)) * mask\n\n loss = torch.sum(loss) / torch.sum(mask)\n\n log_var = {}\n with torch.no_grad():\n metrics = get_depth_metrics(depth_pred, label, mask)\n # abs_diff, abs_rel, sq_rel, rmse, rmse_log\n metrics = [m.item() for m in metrics]\n abs_diff, abs_rel, sq_rel, rmse, rmse_log = metrics\n sparsity = torch.sum(mask) * 1.0 / torch.numel(mask)\n\n\n std = torch.tensor([58.395, 57.12, 57.375]).cuda().view(1, -1, 1, 1)\n mean = torch.tensor([123.675, 116.28, 103.53]).cuda().view(1, -1, 1, 1)\n img = data['img'] * std + mean\n img = img / 255.0\n depth_at_gt = depth_pred * mask\n log_vars = {'loss': loss.item(), 'sparsity': sparsity.item(),\n 'abs_diff': abs_diff, 'abs_rel': abs_rel,\n 'sq_rel': sq_rel, 'rmse': rmse,\n 'rmse_log': rmse_log\n }\n # 'pred', 'data', 'label', 'depth_at_gt' is used for visualization only!\n outputs = {'pred': torch.clamp(1.0 / (depth_pred+1e-4), 0, 1), 'data': img,\n 'label': torch.clamp(1.0 / (label+1e-4), 0, 1),\n 'depth_at_gt': torch.clamp(1.0 / (depth_at_gt+1e-4), 0., 1),\n 'loss':loss, 'log_vars':log_vars, 'num_samples':depth_pred.size(0)}\n\n return outputs\n\n def val_step(self, data, optimizer):\n\n return self.train_step(self, data, optimizer)\n",
"import mmcv\nimport numpy as np\nimport pytest\nimport torch\n\nfrom mmdet3d.datasets import NuScenesMonoDataset\n\n\ndef test_getitem():\n np.random.seed(0)\n class_names = [\n 'car', 'truck', 'trailer', 'bus', 'construction_vehicle', 'bicycle',\n 'motorcycle', 'pedestrian', 'traffic_cone', 'barrier'\n ]\n img_norm_cfg = dict(\n mean=[102.9801, 115.9465, 122.7717], std=[1.0, 1.0, 1.0], to_rgb=False)\n pipeline = [\n dict(type='LoadImageFromFileMono3D'),\n dict(\n type='LoadAnnotations3D',\n with_bbox=True,\n with_label=True,\n with_attr_label=True,\n with_bbox_3d=True,\n with_label_3d=True,\n with_bbox_depth=True),\n dict(type='Resize', img_scale=(1600, 900), keep_ratio=True),\n dict(type='RandomFlip3D', flip_ratio_bev_horizontal=1.0),\n dict(type='Normalize', **img_norm_cfg),\n dict(type='Pad', size_divisor=32),\n dict(type='DefaultFormatBundle3D', class_names=class_names),\n dict(\n type='Collect3D',\n keys=[\n 'img', 'gt_bboxes', 'gt_labels', 'attr_labels', 'gt_bboxes_3d',\n 'gt_labels_3d', 'centers2d', 'depths'\n ]),\n ]\n\n nus_dataset = NuScenesMonoDataset(\n ann_file='tests/data/nuscenes/nus_infos_mono3d.coco.json',\n pipeline=pipeline,\n data_root='tests/data/nuscenes/',\n img_prefix='tests/data/nuscenes/',\n test_mode=False)\n\n data = nus_dataset[0]\n img_metas = data['img_metas']._data\n filename = img_metas['filename']\n img_shape = img_metas['img_shape']\n pad_shape = img_metas['pad_shape']\n flip = img_metas['flip']\n bboxes = data['gt_bboxes']._data\n attrs = data['attr_labels']._data\n labels3d = data['gt_labels_3d']._data\n labels = data['gt_labels']._data\n centers2d = data['centers2d']._data\n depths = data['depths']._data\n\n expected_filename = 'tests/data/nuscenes/samples/CAM_BACK_LEFT/' + \\\n 'n015-2018-07-18-11-07-57+0800__CAM_BACK_LEFT__1531883530447423.jpg'\n expected_img_shape = (900, 1600, 3)\n expected_pad_shape = (928, 1600, 3)\n expected_flip = True\n expected_bboxes = torch.tensor([[485.4207, 513.7568, 515.4637, 576.1393],\n [748.9482, 512.0452, 776.4941, 571.6310],\n [432.1318, 427.8805, 508.4290, 578.1468],\n [367.3779, 427.7682, 439.4244, 578.8904],\n [592.8713, 515.0040, 623.4984, 575.0945]])\n expected_attr_labels = torch.tensor([8, 8, 4, 4, 8])\n expected_labels = torch.tensor([8, 8, 7, 7, 8])\n expected_centers2d = torch.tensor([[500.6090, 544.6358],\n [762.8789, 541.5280],\n [471.1633, 502.2295],\n [404.1957, 502.5908],\n [608.3627, 544.7317]])\n expected_depths = torch.tensor(\n [15.3193, 15.6073, 14.7567, 14.8803, 15.4923])\n\n assert filename == expected_filename\n assert img_shape == expected_img_shape\n assert pad_shape == expected_pad_shape\n assert flip == expected_flip\n assert torch.allclose(bboxes, expected_bboxes, 1e-5)\n assert torch.all(attrs == expected_attr_labels)\n assert torch.all(labels == expected_labels)\n assert torch.all(labels3d == expected_labels)\n assert torch.allclose(centers2d, expected_centers2d, 1e-5)\n assert torch.allclose(depths, expected_depths, 1e-5)\n\n\ndef test_format_results():\n if not torch.cuda.is_available():\n pytest.skip('test requires GPU and torch+cuda')\n root_path = 'tests/data/nuscenes/'\n ann_file = 'tests/data/nuscenes/nus_infos_mono3d.coco.json'\n class_names = [\n 'car', 'truck', 'trailer', 'bus', 'construction_vehicle', 'bicycle',\n 'motorcycle', 'pedestrian', 'traffic_cone', 'barrier'\n ]\n pipeline = [\n dict(type='LoadImageFromFileMono3D'),\n dict(\n type='LoadAnnotations3D',\n with_bbox=True,\n with_label=True,\n with_attr_label=True,\n with_bbox_3d=True,\n with_label_3d=True,\n with_bbox_depth=True),\n dict(type='Resize', img_scale=(1600, 900), keep_ratio=True),\n dict(type='Pad', size_divisor=32),\n dict(type='DefaultFormatBundle3D', class_names=class_names),\n dict(\n type='Collect3D',\n keys=[\n 'img', 'gt_bboxes', 'gt_labels', 'attr_labels', 'gt_bboxes_3d',\n 'gt_labels_3d', 'centers2d', 'depths'\n ]),\n ]\n nus_dataset = NuScenesMonoDataset(\n ann_file=ann_file,\n pipeline=pipeline,\n data_root=root_path,\n test_mode=True)\n results = mmcv.load('tests/data/nuscenes/mono3d_sample_results.pkl')\n result_files, tmp_dir = nus_dataset.format_results(results)\n result_data = mmcv.load(result_files['img_bbox'])\n assert len(result_data['results'].keys()) == 1\n assert len(result_data['results']['e93e98b63d3b40209056d129dc53ceee']) == 8\n det = result_data['results']['e93e98b63d3b40209056d129dc53ceee'][0]\n\n expected_token = 'e93e98b63d3b40209056d129dc53ceee'\n expected_trans = torch.tensor(\n [1018.753821915645, 605.190386124652, 0.7266818822266328])\n expected_size = torch.tensor([1.6380000114440918, 4.25, 1.440000057220459])\n expected_rotation = torch.tensor([\n -0.9924980733795628, -0.013604682549109839, 0.01027292674776989,\n -0.12106590736714223\n ])\n expected_detname = 'car'\n expected_attr = 'vehicle.moving'\n\n assert det['sample_token'] == expected_token\n assert torch.allclose(\n torch.tensor(det['translation']), expected_trans, 1e-5)\n assert torch.allclose(torch.tensor(det['size']), expected_size, 1e-5)\n assert torch.allclose(\n torch.tensor(det['rotation']), expected_rotation, 1e-5)\n assert det['detection_name'] == expected_detname\n assert det['attribute_name'] == expected_attr\n",
"from nuscenes.nuscenes import NuScenes, NuScenesExplorer\nimport numpy as np\nimport os\nimport os.path as osp\nimport json\nfrom pyquaternion import Quaternion\nfrom nuscenes.utils.data_classes import LidarPointCloud, RadarPointCloud, Box\nfrom nuscenes.utils.geometry_utils import view_points, box_in_image, BoxVisibility, transform_matrix\n\nfrom PIL import Image\nfrom IPython import embed\nfrom copy import deepcopy\nimport cv2\nimport json\n\nSPLITS = {'val': 'v1.0-trainval-val', 'train': 'v1.0-trainval', 'test': 'v1.0-test'}\nCamNames = ['CAM_FRONT', 'CAM_FRONT_RIGHT', \n 'CAM_BACK_RIGHT', 'CAM_BACK', 'CAM_BACK_LEFT',\n 'CAM_FRONT_LEFT']\n\ndef get_sf_ann(ann_token:str, timestamp, points, nusc):\n \"\"\"\n points: np.array of shape [3, N]\n \"\"\"\n points = deepcopy(points)\n ann_data = nusc.get('sample_annotation', ann_token)\n \n visibilities=['1', '2', '3', '4']\n if not (ann_data['visibility_token'] in visibilities):\n return None, None, None\n # 'sample_token', 'instance_token', 'translation', 'size', 'rotation', 'prev': '', 'next', 'num_lidar_pts'\n #box = Box(ann_data['translation'], ann_data['size'], Quaternion(ann_data['rotation']),\n # name=ann_data['category_name'], token=ann_data['token'])\n box = nusc.get_box(ann_token)\n # collect points\n next_ann_token = ann_data['next']\n prev_ann_token = ann_data['prev']\n\n has_next = next_ann_token != ''\n has_prev = prev_ann_token != ''\n\n if (not has_next) and (not has_prev):\n return None, None, box\n\n num_ref = int(has_next) + int(has_prev)\n\n is_valid_points = is_points_in_box(box, deepcopy(points))\n valid_points = points[:, is_valid_points]\n print('number valid points: {} - gt:{}'.format(valid_points.shape[1], ann_data['num_lidar_pts']))\n #assert valid_points.shape[1] == ann_data['num_lidar_pts'], 'num of lidar pts not right! {} {}'.format(valid_points.shape[1], ann_data['num_lidar_pts'])\n\n box_center = box.center\n valid_points = np.concatenate([valid_points, box_center[:, np.newaxis]], axis=-1)\n # get speed twice\n\n # avg speed: pts_x, pts_y, pts_dep, pts_sf\n valid_points_to_box = points_to_box(box, deepcopy(valid_points))\n\n sf = 0\n if next_ann_token is not '':\n next_points, next_time = points_to_ann_cord(next_ann_token, deepcopy(valid_points_to_box), nusc)\n sf_from_next = (next_points - valid_points) / (next_time*1e-6 - timestamp*1e-6)\n sf = sf + sf_from_next\n\n if prev_ann_token is not '':\n prev_points, prev_time = points_to_ann_cord(prev_ann_token, deepcopy(valid_points_to_box), nusc)\n sf_from_prev = (prev_points - valid_points) / (prev_time*1e-6 - timestamp*1e-6)\n sf = sf + sf_from_prev\n\n #embed() \n sf = sf / num_ref\n\n return valid_points, sf, box\n\n\ndef points_to_ann_cord(ann_token, points, nusc):\n ann_data = nusc.get('sample_annotation', ann_token)\n # 'sample_token', 'instance_token', 'translation', 'size', 'rotation', 'prev': '', 'next', 'num_lidar_pts'\n #box = Box(ann_data['translation'], ann_data['size'], Quaternion(ann_data['rotation']),\n # name=ann_data['category_name'], token=ann_data['token'])\n box = nusc.get_box(ann_token)\n next_sample = nusc.get('sample', ann_data['sample_token'])\n\n timestamp = next_sample['timestamp']\n return points_from_box(box, points), timestamp\n\n \n\ndef points_to_box(box, points):\n '''\n box.orientation.rotation_matrix, \n box.center \n points: np.array: [3, N]\n\n '''\n x, y, z = box.center\n points[0, :] = points[0, :] - x\n points[1, :] = points[1, :] - y\n points[2, :] = points[2, :] - z\n\n points = np.dot(box.orientation.inverse.rotation_matrix, points)\n\n return points\n\ndef points_from_box(box, points):\n \"\"\"\n box.orientation.rotation_matrix, \n box.center \n points: np.array: [3, N]\n \"\"\"\n points = np.dot(box.orientation.rotation_matrix, points)\n x, y, z = box.center\n\n points[0, :] = points[0, :] + x\n points[1, :] = points[1, :] + y\n points[2, :] = points[2, :] + z\n\n return points\n\n\ndef is_points_in_box(box, points):\n '''\n points: np.array of shape [3, N]\n '''\n \n points = points_to_box(box, points)\n points = np.abs(points)\n\n w, l, h = box.wlh\n \n # 这一步有点不确定了\n x_lim, y_lim, z_lim = l / 2, w / 2, h / 2\n\n in_box_x = points[0, :] < x_lim\n in_box_y = points[1, :] < y_lim\n in_box_z = points[2, :] < z_lim\n\n in_box = np.logical_and(np.logical_and(in_box_x, in_box_y), in_box_z)\n\n return in_box\n\n\ndef parse_sample(sample_token, nusc):\n sample_data = nusc.get('sample', sample_token)\n timestamp = sample_data['timestamp']\n\n # First Step: Get lidar points in global frame cord!\n lidar_token = sample_data['data']['LIDAR_TOP']\n lidar_data = nusc.get('sample_data', lidar_token)\n pcl_path = osp.join(nusc.dataroot, lidar_data['filename'])\n pc = LidarPointCloud.from_file(pcl_path)\n\n # lidar point in point sensor frame\n\n cs_record = nusc.get('calibrated_sensor', lidar_data['calibrated_sensor_token'])\n pc.rotate(Quaternion(cs_record['rotation']).rotation_matrix)\n pc.translate(np.array(cs_record['translation']))\n\n # Second step: transform from ego to the global frame.\n poserecord = nusc.get('ego_pose', lidar_data['ego_pose_token'])\n pc.rotate(Quaternion(poserecord['rotation']).rotation_matrix)\n pc.translate(np.array(poserecord['translation']))\n\n # First Step finished! pc in global frame\n\n ann_tokens = sample_data['anns']\n\n all_points = []\n all_sf = []\n for ann_token in ann_tokens:\n # ret are in global frame\n points, sf, box = get_sf_ann(ann_token, timestamp, pc.points[:3, ], nusc)\n if points is not None:\n all_points.append(points)\n all_sf.append(sf)\n \n points = np.concatenate(all_points, axis=-1)\n sf = np.concatenate(all_sf, axis=-1)\n\n # transform points to ego pose; change sf's orentiation\n points = points - np.array(poserecord['translation'])[:, np.newaxis]\n points = np.dot(Quaternion(poserecord['rotation']).rotation_matrix.T, points)\n\n sf = np.dot(Quaternion(poserecord['rotation']).rotation_matrix.T, sf)\n\n return points, sf\n\ndef visualize_sample(sample_token, nusc):\n points, sf = parse_sample(sample_token, nusc)\n sample_data = nusc.get('sample', sample_token)\n\n for cam_name in CamNames:\n cam_token = sample_data['data'][cam_name]\n cam_data = nusc.get('sample_data', cam_token)\n im = Image.open(osp.join(nusc.dataroot, cam_data['filename']))\n cam_cs = nusc.get('calibrated_sensor', cam_data['calibrated_sensor_token'])\n\n # transform points for ego pose to camera pose\n cam_points = deepcopy(points) - np.array(cam_cs['translation'])[:, np.newaxis]\n cam_points = np.dot(Quaternion(cam_cs['rotation']).rotation_matrix.T, cam_points)\n\n # use camera intrinsics to project points into image plane. \n cam_points = view_points(cam_points, np.array(cam_cs['camera_intrinsic']), normalize=True)\n\n # filter out points which do not show in this camera\n mask = np.ones(cam_points.shape[1], dtype=bool)\n \n mask = np.logical_and(mask, cam_points[0, :] > 1)\n mask = np.logical_and(mask, cam_points[0, :] < im.size[0] - 1)\n mask = np.logical_and(mask, cam_points[1, :] > 1)\n mask = np.logical_and(mask, cam_points[1, :] < im.size[1] - 1)\n #print('Mask num', cam_points.shape[1], mask.sum())\n cam_points = cam_points[:, mask]\n cam_sf = sf[:, mask]\n img = cv2.cvtColor(np.asarray(im),cv2.COLOR_RGB2BGR) \n prev_point = np.array([0,0])\n for i in range(cam_points.shape[1]):\n cur_cord = np.array([int(cam_points[0, i]), int(cam_points[1, i])])\n cv2.circle(img, (int(cam_points[0, i]), int(cam_points[1, i])), 4, [0,0,255], -1)\n font = cv2.FONT_HERSHEY_SIMPLEX\n sf_str = '{:.3f} - {:.3f} - {:.3f}'.format(sf[0, i],sf[1, i],sf[2, i])\n #print(sf_str)\n #print(cam_points[:, i])\n #if np.sum(np.abs(cur_cord - prev_point)) > 300:\n # cv2.putText(img, sf_str, (int(cam_points[0, i]), int(cam_points[1, i])), font, 2, (255, 0, 0))\n # prev_point = cur_cord\n \n _, boxes, _ = nusc.get_sample_data(cam_token, box_vis_level=BoxVisibility.ANY)\n for box in boxes:\n c = nusc.colormap[box.name]\n box.render_cv2(img, view=np.array(cam_cs['camera_intrinsic']), normalize=True, colors=(c, c, c))\n \n im = Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))\n im.save(os.path.join('/home/zhangty/tmp/visual_sf', cam_name+'.png'))\n\ndef generate_sf_for_one_sample(sample_token, nusc, save_dir, meta=None):\n points, sf = parse_sample(sample_token, nusc)\n sample_data = nusc.get('sample', sample_token)\n\n \n for cam_name in CamNames:\n cam_token = sample_data['data'][cam_name]\n cam_data = nusc.get('sample_data', cam_token)\n filename = cam_data['filename']\n cam_cs = nusc.get('calibrated_sensor', cam_data['calibrated_sensor_token'])\n\n # transform points for ego pose to camera pose\n cam_points = deepcopy(points) - np.array(cam_cs['translation'])[:, np.newaxis]\n cam_points = np.dot(Quaternion(cam_cs['rotation']).rotation_matrix.T, cam_points)\n\n # use camera intrinsics to project points into image plane. \n cam_points = view_points(cam_points, np.array(cam_cs['camera_intrinsic']), normalize=True)\n\n # filter out points which do not show in this camera\n mask = np.ones(cam_points.shape[1], dtype=bool)\n \n mask = np.logical_and(mask, cam_points[0, :] > 1)\n mask = np.logical_and(mask, cam_points[0, :] < 1599)\n mask = np.logical_and(mask, cam_points[1, :] > 1)\n mask = np.logical_and(mask, cam_points[1, :] < 899)\n cam_points = cam_points[:, mask]\n cam_sf = sf[:, mask]\n\n save_points = np.concatenate([cam_points, cam_sf], axis=0)\n\n img_name = osp.split(filename)[-1].split('.')[0]\n np.save(osp.join(save_dir, img_name), save_points) # will add .npy postfix automaticlly\n save_path = osp.join(img_name +'.npy')\n\n meta[cam_token] = save_path\n \n return meta\n\ndef _main():\n split='train'\n data_path='data/nuscenes/'\n nusc = NuScenes(\n version=SPLITS[split], dataroot=data_path, verbose=True)\n\n samples = nusc.sample\n\n save_dir = '/public/MARS/datasets/nuScenes-SF/trainval'\n meta = {}\n for sample in samples:\n sample_token = sample['token']\n generate_sf_for_one_sample(sample_token, nusc, save_dir, meta)\n\n meta_file_path = os.path.join(save_dir, 'meta.json')\n with open(meta_file_path, 'w') as f:\n json.dump(meta, f)\n\ndef _test_visual():\n split='train'\n data_path='data/nuscenes/'\n nusc = NuScenes(\n version=SPLITS[split], dataroot=data_path, verbose=True)\n\n samples = nusc.sample\n\n sample = samples[0]\n sample_token = sample['token']\n #tp_parse_sample(sample_token, nusc)\n visualize_sample(sample_token, nusc)\n embed()\n\nif __name__ == '__main__':\n _main()\n \n #_test_visual()\n"
] | [
[
"torch.abs",
"torch.cat",
"torch.sum",
"torch.nn.PixelShuffle",
"torch.tensor",
"torch.numel",
"torch.nn.Upsample",
"torch.no_grad",
"torch.nn.init.xavier_uniform_",
"torch.clamp"
],
[
"torch.abs",
"torch.sum",
"torch.tensor",
"torch.numel",
"torch.no_grad",
"torch.clamp"
],
[
"torch.all",
"numpy.random.seed",
"torch.tensor",
"torch.cuda.is_available",
"torch.allclose"
],
[
"numpy.dot",
"numpy.abs",
"numpy.logical_and",
"numpy.asarray",
"numpy.ones",
"numpy.concatenate",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
thomaskuestner/CNNArt | [
"c2fc639dd2ce035f6ca90113290682a0ccd26fb8",
"c2fc639dd2ce035f6ca90113290682a0ccd26fb8",
"c2fc639dd2ce035f6ca90113290682a0ccd26fb8",
"c2fc639dd2ce035f6ca90113290682a0ccd26fb8",
"c2fc639dd2ce035f6ca90113290682a0ccd26fb8"
] | [
"utils/RigidPatching.py",
"GUI/PyQt/networks/multiclass/SENets/multiclass_SE-ResNet-56.py",
"GUI/PyQt/utils/Prediction.py",
"GUI/PyQt/utils/CNN_main.py",
"GUI/PyQt/networks/multiclass/SENets/multiclass_SE-DenseNet-34.py"
] | [
"'''\r\nCopyright: 2016-2019 Thomas Kuestner ([email protected]) under Apache2 license\r\n@author: Thomas Kuestner\r\n'''\r\n\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport math\r\n\r\nfrom utils.Label import Label\r\n\r\n#########################################################################################################################################\r\n#Function: fRigidPatching #\r\n#The function fRigidPatching is responsible for splitting the dicom numpy array in patches depending on the patchSize and the #\r\n#patchOverlap. Besides the function creates an 1D array with the corresponding labels. #\r\n# #\r\n#Input: dicom_numpy_array ---> 3D dicom array (height, width, number of slices) #\r\n# patchSize ---> size of patches, example: [40, 40], patchSize[0] = height, patchSize[1] = weight, height and weight can differ #\r\n# patchOverlap ---> the ratio for overlapping, example: 0.25 #\r\n# mask_numpy_array ---> 3D mask array contains information about the areas of artefacts. movement-artefact = 1, shim-artefact = 2 #\r\n# noise-artefact = 3 #\r\n# ratio_labeling ---> set the ratio of the number of 'Pixel-Artefacts' to the whole number of pixels of one patch #\r\n#Output: dPatches ---> 3D-Numpy-Array, which contain all Patches. #\r\n# dLabels ---> 1D-Numpy-Array with all corresponding labels #\r\n#########################################################################################################################################\r\n\r\ndef fRigidPatching(dicom_numpy_array, patchSize, patchOverlap, mask_numpy_array, ratio_labeling):\r\n move_artefact = False\r\n shim_artefact = False\r\n noise_artefact = False\r\n #dLabels = []\r\n\r\n dOverlap = np.multiply(patchSize, patchOverlap)\r\n dNotOverlap = np.round(np.multiply(patchSize, (1 - patchOverlap)))\r\n size_zero_pad = np.array(([math.ceil((dicom_numpy_array.shape[0] - dOverlap[0]) / (dNotOverlap[0])) * dNotOverlap[0] + dOverlap[\r\n 0], math.ceil((dicom_numpy_array.shape[1] - dOverlap[1]) / (dNotOverlap[1])) * dNotOverlap[1] + dOverlap[1]]))\r\n zero_pad = np.array(([int(size_zero_pad[0]) - dicom_numpy_array.shape[0], int(size_zero_pad[1]) - dicom_numpy_array.shape[1]]))\r\n zero_pad_part = np.array(([int(math.ceil(zero_pad[0] / 2)), int(math.ceil(zero_pad[1] / 2))]))\r\n Img_zero_pad = np.lib.pad(dicom_numpy_array, (\r\n (zero_pad_part[0], zero_pad[0] - zero_pad_part[0]), (zero_pad_part[1], zero_pad[1] - zero_pad_part[1]), (0, 0)),\r\n mode='constant')\r\n Mask_zero_pad = np.lib.pad(mask_numpy_array, (\r\n (zero_pad_part[0], zero_pad[0] - zero_pad_part[0]), (zero_pad_part[1], zero_pad[1] - zero_pad_part[1]), (0, 0)),\r\n mode='constant')\r\n nbPatches = int(((size_zero_pad[0]-patchSize[0])/((1-patchOverlap)*patchSize[0])+1)*((size_zero_pad[1]-patchSize[1])/((1-patchOverlap)*patchSize[1])+1)*dicom_numpy_array.shape[2])\r\n dPatches = np.zeros((patchSize[0], patchSize[1], nbPatches), dtype=float) #dtype=np.float32\r\n dLabels = np.zeros((nbPatches), dtype = float) #dtype = float\r\n idxPatch = 0\r\n for iZ in range(0, dicom_numpy_array.shape[2], 1):\r\n for iY in range(0, int(size_zero_pad[0] - dOverlap[0]), int(dNotOverlap[0])):\r\n for iX in range(0, int(size_zero_pad[1] - dOverlap[1]), int(dNotOverlap[1])):\r\n dPatch = Img_zero_pad[iY:iY + patchSize[0], iX:iX + patchSize[1], iZ]\r\n dPatches[:,:,idxPatch] = dPatch\r\n\r\n dPatch_mask = Mask_zero_pad[iY:iY + patchSize[0], iX:iX + patchSize[1], iZ]\r\n patch_number_value = patchSize[0] * patchSize[1]\r\n\r\n if np.count_nonzero((dPatch_mask==1).astype(np.int)) > int(ratio_labeling*patch_number_value):\r\n move_artefact = True\r\n if np.count_nonzero((dPatch_mask==2).astype(np.int)) > int(ratio_labeling*patch_number_value):\r\n shim_artefact = True\r\n if np.count_nonzero((dPatch_mask==3).astype(np.int)) > int(ratio_labeling*patch_number_value):\r\n noise_artefact = True\r\n\r\n label = 0\r\n\r\n if move_artefact == True and shim_artefact != True and noise_artefact != True:\r\n label = 1\r\n elif move_artefact != True and shim_artefact == True and noise_artefact != True:\r\n label = 2\r\n elif move_artefact != True and shim_artefact != True and noise_artefact == True:\r\n label = 3\r\n elif move_artefact == True and shim_artefact == True and noise_artefact != True:\r\n label = 4\r\n elif move_artefact == True and shim_artefact != True and noise_artefact == True:\r\n label = 5\r\n elif move_artefact != True and shim_artefact == True and noise_artefact == True:\r\n label = 6\r\n elif move_artefact == True and shim_artefact == True and noise_artefact == True:\r\n label = 7\r\n\r\n print(label)\r\n dLabels[idxPatch] = label\r\n idxPatch += 1\r\n\r\n move_artefact = False\r\n shim_artefact = False\r\n noise_artefact = False\r\n\r\n print(\"Rigid done!\")\r\n print(dLabels)\r\n return dPatches, dLabels, nbPatches\r\n\r\n\r\n#########################################################################################################################################\r\n#Function: fRigidPatching3D #\r\n#The function fRigidPatching3D is responsible for splitting the dicom numpy array in patches depending on the patchSize and the #\r\n#patchOverlap. Besides the function creates an 1D array with the corresponding labels. #\r\n# #\r\n#Input: dicom_numpy_array ---> 3D dicom array (height, width, number of slices) #\r\n# patchSize ---> size of patches, example: [40, 40], patchSize[0] = height, patchSize[1] = weight, height and weight can differ #\r\n# patchOverlap ---> the ratio for overlapping, example: 0.25 #\r\n# mask_numpy_array ---> 3D mask array contains information about the areas of artefacts. movement-artefact = 1, shim-artefact = 2 #\r\n# noise-artefact = 3 #\r\n# ratio_labeling ---> set the ratio of the number of 'Pixel-Artefacts' to the whole number of pixels of one patch #\r\n#Output: dPatches ---> 3D-Numpy-Array, which contain all Patches. #\r\n# dLabels ---> 1D-Numpy-Array with all corresponding labels #\r\n#########################################################################################################################################\r\n\r\ndef fRigidPatching3D(dicom_numpy_array, patchSize, patchOverlap, mask_numpy_array, ratio_labeling):\r\n move_artefact = False\r\n shim_artefact = False\r\n noise_artefact = False\r\n #dLabels = []\r\n print(patchSize)\r\n dOverlap = np.round(np.multiply(patchSize, patchOverlap))\r\n dNotOverlap = np.round(np.multiply(patchSize, (1 - patchOverlap)))\r\n print(dOverlap, dNotOverlap)\r\n size_zero_pad = np.array(([math.ceil((dicom_numpy_array.shape[0] - dOverlap[0]) / (dNotOverlap[0])) * dNotOverlap[0] + dOverlap[\r\n 0], math.ceil((dicom_numpy_array.shape[1] - dOverlap[1]) / (dNotOverlap[1])) * dNotOverlap[1] + dOverlap[1], math.ceil((dicom_numpy_array.shape[2] - dOverlap[2]) / (dNotOverlap[2])) * dNotOverlap[2] + dOverlap[2]]))\r\n print(size_zero_pad.shape)\r\n zero_pad = np.array(([int(size_zero_pad[0]) - dicom_numpy_array.shape[0], int(size_zero_pad[1]) - dicom_numpy_array.shape[1], int(size_zero_pad[2]) - dicom_numpy_array.shape[2]]))\r\n print(zero_pad.shape)\r\n zero_pad_part = np.array(([int(math.ceil(zero_pad[0] / 2)), int(math.ceil(zero_pad[1] / 2)), int(math.ceil(zero_pad[2] / 2))]))\r\n print(zero_pad_part.shape)\r\n Img_zero_pad = np.lib.pad(dicom_numpy_array, (\r\n (zero_pad_part[0], zero_pad[0] - zero_pad_part[0]), (zero_pad_part[1], zero_pad[1] - zero_pad_part[1]), (zero_pad_part[2], zero_pad[2] - zero_pad_part[2])),\r\n mode='constant')\r\n print(Img_zero_pad.shape)\r\n Mask_zero_pad = np.lib.pad(mask_numpy_array, (\r\n (zero_pad_part[0], zero_pad[0] - zero_pad_part[0]), (zero_pad_part[1], zero_pad[1] - zero_pad_part[1]), (zero_pad_part[2], zero_pad[2] - zero_pad_part[2])),\r\n mode='constant')\r\n print(Mask_zero_pad.shape)\r\n print(size_zero_pad[2])\r\n print(np.round((1-patchOverlap)*patchSize[2]))\r\n print(((size_zero_pad[2]-patchSize[2])/(np.round((1-patchOverlap)*patchSize[2]))+1))\r\n nbPatches = ((size_zero_pad[0]-patchSize[0])/((1-patchOverlap)*patchSize[0])+1)*((size_zero_pad[1]-patchSize[1])/((1-patchOverlap)*patchSize[1])+1)*((size_zero_pad[2]-patchSize[2])/(np.round((1-patchOverlap)*patchSize[2]))+1)\r\n print(nbPatches)\r\n dPatches = np.zeros((patchSize[0], patchSize[1], patchSize[2], int(nbPatches)), dtype=float)\r\n dLabels = np.zeros((int(nbPatches)), dtype = int) #float\r\n idxPatch = 0\r\n for iZ in range(0, int(size_zero_pad[2] - dOverlap[2]), int(dNotOverlap[2])):\r\n for iY in range(0, int(size_zero_pad[0] - dOverlap[0]), int(dNotOverlap[0])):\r\n for iX in range(0, int(size_zero_pad[1] - dOverlap[1]), int(dNotOverlap[1])):\r\n dPatch = Img_zero_pad[iY:iY + patchSize[0], iX:iX + patchSize[1], iZ:iZ + patchSize[2]]\r\n print(dPatch.shape)\r\n print(dPatches[:,:,:,idxPatch].shape)\r\n dPatches[:,:,:,idxPatch] = dPatch\r\n\r\n dPatch_mask = Mask_zero_pad[iY:iY + patchSize[0], iX:iX + patchSize[1], iZ:iZ + patchSize[2]]\r\n patch_number_value = patchSize[0] * patchSize[1]*patchSize[2]\r\n\r\n if np.count_nonzero((dPatch_mask==1).astype(np.int)) > int(ratio_labeling*patch_number_value):\r\n move_artefact = True\r\n if np.count_nonzero((dPatch_mask==2).astype(np.int)) > int(ratio_labeling*patch_number_value):\r\n shim_artefact = True\r\n if np.count_nonzero((dPatch_mask==3).astype(np.int)) > int(ratio_labeling*patch_number_value):\r\n noise_artefact = True\r\n\r\n label = 0\r\n\r\n if move_artefact == True and shim_artefact != True and noise_artefact != True:\r\n label = 1\r\n elif move_artefact != True and shim_artefact == True and noise_artefact != True:\r\n label = 2\r\n elif move_artefact != True and shim_artefact != True and noise_artefact == True:\r\n label = 3\r\n elif move_artefact == True and shim_artefact == True and noise_artefact != True:\r\n label = 4\r\n elif move_artefact == True and shim_artefact != True and noise_artefact == True:\r\n label = 5\r\n elif move_artefact != True and shim_artefact == True and noise_artefact == True:\r\n label = 6\r\n elif move_artefact == True and shim_artefact == True and noise_artefact == True:\r\n label = 7\r\n\r\n print(label)\r\n dLabels[idxPatch] = label\r\n idxPatch += 1\r\n\r\n move_artefact = False\r\n shim_artefact = False\r\n noise_artefact = False\r\n\r\n print(\"Rigid done!\")\r\n print(dLabels.dtype)\r\n return dPatches, dLabels, nbPatches\r\n\r\n\r\ndef fRigidPatching3DN(dicom_numpy_array, patchSize, patchOverlap, mask_numpy_array, ratio_labeling):\r\n move_artefact = False\r\n shim_artefact = False\r\n noise_artefact = False\r\n #dLabels = []\r\n\r\n dOverlap = np.multiply(patchSize, patchOverlap)\r\n dNotOverlap = np.round(np.multiply(patchSize, (1 - patchOverlap)))\r\n print(dOverlap,dNotOverlap)\r\n size_zero_pad = np.array(([math.ceil((dicom_numpy_array.shape[0] - dOverlap[0]) / (dNotOverlap[0])) * dNotOverlap[0] + dOverlap[\r\n 0], math.ceil((dicom_numpy_array.shape[1] - dOverlap[1]) / (dNotOverlap[1])) * dNotOverlap[1] + dOverlap[1], math.ceil((dicom_numpy_array.shape[2] - dOverlap[2]) / (dNotOverlap[2])) * dNotOverlap[2] + dOverlap[2]]))\r\n zero_pad = np.array(([int(size_zero_pad[0]) - dicom_numpy_array.shape[0], int(size_zero_pad[1]) - dicom_numpy_array.shape[1], int(size_zero_pad[2]) - dicom_numpy_array.shape[2]]))\r\n zero_pad_part = np.array(([int(math.ceil(zero_pad[0] / 2)), int(math.ceil(zero_pad[1] / 2)), int(math.ceil(zero_pad[2] / 2))]))\r\n Img_zero_pad = np.lib.pad(dicom_numpy_array, (\r\n (zero_pad_part[0], zero_pad[0] - zero_pad_part[0]), (zero_pad_part[1], zero_pad[1] - zero_pad_part[1]), (zero_pad_part[2], zero_pad[2] - zero_pad_part[2])),\r\n mode='constant')\r\n print(Img_zero_pad.shape)\r\n Mask_zero_pad = np.lib.pad(mask_numpy_array, (\r\n (zero_pad_part[0], zero_pad[0] - zero_pad_part[0]), (zero_pad_part[1], zero_pad[1] - zero_pad_part[1]), (zero_pad_part[2], zero_pad[2] - zero_pad_part[2])),\r\n mode='constant')\r\n nbPatches = ((size_zero_pad[0]-patchSize[0])/((1-patchOverlap)*patchSize[0])+1)*((size_zero_pad[1]-patchSize[1])/((1-patchOverlap)*patchSize[1])+1)*((size_zero_pad[2]-patchSize[2])/((1-patchOverlap)*patchSize[2])+1)\r\n print(((size_zero_pad[0]-patchSize[0])/((1-patchOverlap)*patchSize[0])+1))\r\n print(((size_zero_pad[1]-patchSize[1])/((1-patchOverlap)*patchSize[1])+1))\r\n print(((size_zero_pad[2]-patchSize[2])/((1-patchOverlap)*patchSize[2])+1))\r\n print(int(patchSize[0]), int(patchSize[1]), int(patchSize[2]), int(nbPatches))\r\n dPatches = np.zeros((int(patchSize[0]), int(patchSize[1]), int(patchSize[2]), int(nbPatches)), dtype=float)\r\n dLabels = np.zeros((int(nbPatches)), dtype = float)\r\n idxPatch = 0\r\n for iZ in range(0, dicom_numpy_array.shape[2], int(dNotOverlap[2])):\r\n for iY in range(0, int(size_zero_pad[0] - dOverlap[0]), int(dNotOverlap[0])):\r\n for iX in range(0, int(size_zero_pad[1] - dOverlap[1]), int(dNotOverlap[1])):\r\n print(iX, iY, iZ)\r\n dPatch = Img_zero_pad[iY:iY + patchSize[0], iX:iX + patchSize[1], iZ:iZ + patchSize[2]]\r\n print(idxPatch)\r\n print(dPatch.shape)\r\n dPatches[:,:,:,idxPatch] = dPatch\r\n\r\n dPatch_mask = Mask_zero_pad[iY:iY + patchSize[0], iX:iX + patchSize[1], iZ:iZ + patchSize[2]]\r\n patch_number_value = patchSize[0] * patchSize[1]*patchSize[2]\r\n\r\n if np.count_nonzero((dPatch_mask==1).astype(np.int)) > int(ratio_labeling*patch_number_value):\r\n move_artefact = True\r\n if np.count_nonzero((dPatch_mask==2).astype(np.int)) > int(ratio_labeling*patch_number_value):\r\n shim_artefact = True\r\n if np.count_nonzero((dPatch_mask==3).astype(np.int)) > int(ratio_labeling*patch_number_value):\r\n noise_artefact = True\r\n\r\n label = 0\r\n\r\n if move_artefact == True and shim_artefact != True and noise_artefact != True:\r\n label = 1\r\n elif move_artefact != True and shim_artefact == True and noise_artefact != True:\r\n label = 2\r\n elif move_artefact != True and shim_artefact != True and noise_artefact == True:\r\n label = 3\r\n elif move_artefact == True and shim_artefact == True and noise_artefact != True:\r\n label = 4\r\n elif move_artefact == True and shim_artefact != True and noise_artefact == True:\r\n label = 5\r\n elif move_artefact != True and shim_artefact == True and noise_artefact == True:\r\n label = 6\r\n elif move_artefact == True and shim_artefact == True and noise_artefact == True:\r\n label = 7\r\n\r\n dLabels[idxPatch] = label\r\n idxPatch += 1\r\n\r\n move_artefact = False\r\n shim_artefact = False\r\n noise_artefact = False\r\n\r\n print(\"Rigid patching done!\")\r\n #print(\"Rigid done!\")\r\n #print(dLabels)\r\n return dPatches, dLabels, nbPatches\r\n\r\n\r\ndef fRigidPatching_maskLabeling(dicom_numpy_array, patchSize, patchOverlap, mask_numpy_array, ratio_labeling, dataset):\r\n dPatches = None\r\n move_artefact = False\r\n shim_artefact = False\r\n noise_artefact = False\r\n\r\n #body region\r\n bodyRegion, bodyRegionLabel = dataset.getBodyRegion()\r\n\r\n # MRT weighting label (T1, T2)\r\n weighting, weightingLabel = dataset.getMRTWeighting()\r\n\r\n #dOverlap = np.multiply(patchSize, patchOverlap)\r\n dOverlap = np.round(np.multiply(patchSize, patchOverlap))\r\n #dNotOverlap = np.round(np.multiply(patchSize, (1 - patchOverlap)))\r\n dNotOverlap = [patchSize[0]-dOverlap[0], patchSize[1]-dOverlap[1]]\r\n\r\n size_zero_pad = np.array(\r\n ([math.ceil((dicom_numpy_array.shape[0] - dOverlap[0]) / (dNotOverlap[0])) * dNotOverlap[0] + dOverlap[0],\r\n math.ceil((dicom_numpy_array.shape[1] - dOverlap[1]) / (dNotOverlap[1])) * dNotOverlap[1] + dOverlap[1]]))\r\n\r\n zero_pad = np.array(\r\n ([int(size_zero_pad[0]) - dicom_numpy_array.shape[0], int(size_zero_pad[1]) - dicom_numpy_array.shape[1]]))\r\n\r\n zero_pad_part = np.array(([int(math.ceil(zero_pad[0] / 2)), int(math.ceil(zero_pad[1] / 2))]))\r\n\r\n Img_zero_pad = np.lib.pad(dicom_numpy_array, (\r\n (zero_pad_part[0], zero_pad[0] - zero_pad_part[0]),\r\n (zero_pad_part[1], zero_pad[1] - zero_pad_part[1]), (0, 0)), mode='constant')\r\n\r\n Mask_zero_pad = np.lib.pad(mask_numpy_array,\r\n ((zero_pad_part[0], zero_pad[0] - zero_pad_part[0]),\r\n (zero_pad_part[1], zero_pad[1] - zero_pad_part[1]), (0, 0)),\r\n mode='constant')\r\n\r\n nbPatches = int(((size_zero_pad[0]-patchSize[0])/((1-patchOverlap)*patchSize[0])+1)*((size_zero_pad[1]-patchSize[1])/((1-patchOverlap)*patchSize[1])+1)*dicom_numpy_array.shape[2])\r\n nbPatches_in_Y = int((size_zero_pad[0]-dOverlap[0])/dNotOverlap[0])\r\n nbPatches_in_X = int((size_zero_pad[1]-dOverlap[1])/dNotOverlap[1])\r\n nbPatches_in_Z = dicom_numpy_array.shape[2]\r\n nbPatches = nbPatches_in_X*nbPatches_in_Y*nbPatches_in_Z\r\n\r\n dPatches = np.zeros((patchSize[0], patchSize[1], nbPatches), dtype=float) # dtype=np.float32\r\n #dLabels = np.zeros((nbPatches), dtype=float) # dtype = float\r\n dLabels = np.zeros((nbPatches), dtype=np.dtype('i4'))\r\n idxPatch = 0\r\n\r\n for iZ in range(0, dicom_numpy_array.shape[2], 1):\r\n for iY in range(0, int(size_zero_pad[0] - dOverlap[0]), int(dNotOverlap[0])):\r\n for iX in range(0, int(size_zero_pad[1] - dOverlap[1]), int(dNotOverlap[1])):\r\n dPatch = Img_zero_pad[iY:iY + patchSize[0], iX:iX + patchSize[1], iZ]\r\n dPatches[:, :, idxPatch] = dPatch\r\n\r\n #if idxPatch == 7678:\r\n # print()\r\n\r\n dPatch_mask = Mask_zero_pad[iY:iY + patchSize[0], iX:iX + patchSize[1], iZ]\r\n patch_number_value = patchSize[0] * patchSize[1]\r\n\r\n if np.count_nonzero((dPatch_mask == 1).astype(np.int)) > int(ratio_labeling * patch_number_value):\r\n move_artefact = True\r\n if np.count_nonzero((dPatch_mask == 2).astype(np.int)) > int(ratio_labeling * patch_number_value):\r\n shim_artefact = True\r\n if np.count_nonzero((dPatch_mask == 3).astype(np.int)) > int(ratio_labeling * patch_number_value):\r\n noise_artefact = True\r\n\r\n label = Label.REFERENCE\r\n\r\n if move_artefact == True and shim_artefact != True and noise_artefact != True:\r\n label = Label.MOTION\r\n elif move_artefact != True and shim_artefact == True and noise_artefact != True:\r\n label = Label.SHIM\r\n elif move_artefact != True and shim_artefact != True and noise_artefact == True:\r\n label = Label.NOISE\r\n elif move_artefact == True and shim_artefact == True and noise_artefact != True:\r\n label = Label.MOTION_AND_SHIM\r\n elif move_artefact == True and shim_artefact != True and noise_artefact == True:\r\n label = Label.MOTION_AND_NOISE\r\n elif move_artefact != True and shim_artefact == True and noise_artefact == True:\r\n label = Label.SHIM_AND_NOISE\r\n elif move_artefact == True and shim_artefact == True and noise_artefact == True:\r\n label = Label.MOTION_AND_SHIM_AND_NOISE\r\n\r\n\r\n # calculate final label\r\n label = label + bodyRegionLabel + weightingLabel\r\n\r\n #print(label)\r\n dLabels[idxPatch] = label\r\n idxPatch += 1\r\n\r\n move_artefact = False\r\n shim_artefact = False\r\n noise_artefact = False\r\n\r\n print(\"Rigid patching done for %s!\" % dataset.getPathdata())\r\n #print(dLabels)\r\n #return dPatches, dLabels, nbPatches\r\n return dPatches, dLabels\r\n\r\n\r\ndef fRigidPatching_patchLabeling(dicom_numpy_array, patchSize, patchOverlap, ratio_labeling):\r\n dPatches = None\r\n move_artefact = False\r\n shim_artefact = False\r\n noise_artefact = False\r\n dLabels = []\r\n\r\n dOverlap = np.multiply(patchSize, patchOverlap)\r\n dNotOverlap = np.round(np.multiply(patchSize, (1 - patchOverlap)))\r\n size_zero_pad = np.array(\r\n ([math.ceil((dicom_numpy_array.shape[0] - dOverlap[0]) / (dNotOverlap[0])) * dNotOverlap[0] + dOverlap[\r\n 0],\r\n math.ceil((dicom_numpy_array.shape[1] - dOverlap[1]) / (dNotOverlap[1])) * dNotOverlap[1] + dOverlap[1]]))\r\n zero_pad = np.array(\r\n ([int(size_zero_pad[0]) - dicom_numpy_array.shape[0], int(size_zero_pad[1]) - dicom_numpy_array.shape[1]]))\r\n zero_pad_part = np.array(([int(math.ceil(zero_pad[0] / 2)), int(math.ceil(zero_pad[1] / 2))]))\r\n Img_zero_pad = np.lib.pad(dicom_numpy_array, (\r\n (zero_pad_part[0], zero_pad[0] - zero_pad_part[0]), (zero_pad_part[1], zero_pad[1] - zero_pad_part[1]), (0, 0)),\r\n mode='constant')\r\n\r\n for iZ in range(0, dicom_numpy_array.shape[2], 1):\r\n for iY in range(0, int(size_zero_pad[0] - dOverlap[0]), int(dNotOverlap[0])):\r\n for iX in range(0, int(size_zero_pad[1] - dOverlap[1]), int(dNotOverlap[1])):\r\n dPatch = Img_zero_pad[iY:iY + patchSize[0], iX:iX + patchSize[1], iZ]\r\n dPatch = dPatch[:, :, np.newaxis]\r\n\r\n if dPatches is None:\r\n dPatches = dPatch\r\n else:\r\n dPatches = np.concatenate((dPatches, dPatch), axis=2)\r\n dLabels = np.ones((dPatches.shape[2]), dtype=np.dtype('i4'))\r\n\r\n return dPatches, dLabels\r\n\r\n\r\n#########################################################################################################################################\r\n#Function: fRigidPatching3D #\r\n#The function fRigidPatching3D is responsible for splitting the dicom numpy array in patches depending on the patchSize and the #\r\n#patchOverlap. Besides the function creates an 1D array with the corresponding labels. #\r\n# #\r\n#Input: dicom_numpy_array ---> 3D dicom array (height, width, number of slices) #\r\n# patchSize ---> size of patches, example: [40, 40], patchSize[0] = height, patchSize[1] = weight, height and weight can differ #\r\n# patchOverlap ---> the ratio for overlapping, example: 0.25 #\r\n# mask_numpy_array ---> 3D mask array contains information about the areas of artefacts. movement-artefact = 1, shim-artefact = 2 #\r\n# noise-artefact = 3 #\r\n# ratio_labeling ---> set the ratio of the number of 'Pixel-Artefacts' to the whole number of pixels of one patch #\r\n#Output: dPatches ---> 3D-Numpy-Array, which contain all Patches. #\r\n# dLabels ---> 1D-Numpy-Array with all corresponding labels #\r\n#########################################################################################################################################\r\n\r\ndef fRigidPatching3D_maskLabeling(dicom_numpy_array, patchSize, patchOverlap, mask_numpy_array, ratio_labeling, dataset=None, dopatching=True):\r\n #ToDo odd patch size not supported!\r\n\r\n move_artefact = False\r\n shim_artefact = False\r\n noise_artefact = False\r\n\r\n if isinstance(dataset, int): # already pre-processed label bodyRegionLabel + weightingLabel\r\n bodyRegionweightingLabel = dataset\r\n else:\r\n # body region\r\n bodyRegion, bodyRegionLabel = dataset.getBodyRegion()\r\n\r\n # MRT weighting label (T1, T2)\r\n weighting, weightingLabel = dataset.getMRTWeighting()\r\n\r\n dOverlap = np.round(np.multiply(patchSize, patchOverlap))\r\n dNotOverlap = np.round(np.multiply(patchSize, (1 - patchOverlap)))\r\n\r\n size_zero_pad = np.array(([math.ceil((dicom_numpy_array.shape[0] - dOverlap[0]) / (dNotOverlap[0])) * dNotOverlap[0] + dOverlap[0],\r\n math.ceil((dicom_numpy_array.shape[1] - dOverlap[1]) / (dNotOverlap[1])) * dNotOverlap[1] + dOverlap[1],\r\n math.ceil((dicom_numpy_array.shape[2] - dOverlap[2]) / (dNotOverlap[2])) * dNotOverlap[2] + dOverlap[2]]))\r\n zero_pad = np.array(([int(size_zero_pad[0]) - dicom_numpy_array.shape[0],\r\n int(size_zero_pad[1]) - dicom_numpy_array.shape[1],\r\n int(size_zero_pad[2]) - dicom_numpy_array.shape[2]]))\r\n zero_pad_part = np.array(([int(math.ceil(zero_pad[0] / 2)),\r\n int(math.ceil(zero_pad[1] / 2)),\r\n int(math.ceil(zero_pad[2] / 2))]))\r\n\r\n Img_zero_pad = np.lib.pad(dicom_numpy_array,\r\n ((zero_pad_part[0], zero_pad[0] - zero_pad_part[0]),\r\n (zero_pad_part[1], zero_pad[1] - zero_pad_part[1]),\r\n (zero_pad_part[2], zero_pad[2] - zero_pad_part[2])),\r\n mode='constant')\r\n\r\n Mask_zero_pad = np.lib.pad(mask_numpy_array,\r\n ((zero_pad_part[0], zero_pad[0] - zero_pad_part[0]),\r\n (zero_pad_part[1], zero_pad[1] - zero_pad_part[1]),\r\n (zero_pad_part[2], zero_pad[2] - zero_pad_part[2])),\r\n mode='constant')\r\n\r\n nbPatches = ((size_zero_pad[0]-patchSize[0])/((1-patchOverlap)*patchSize[0])+1)*((size_zero_pad[1]-patchSize[1])/((1-patchOverlap)*patchSize[1])+1)*((size_zero_pad[2]-patchSize[2])/(np.round((1-patchOverlap)*patchSize[2]))+1)\r\n\r\n nbPatches_in_Y = int((size_zero_pad[0] - dOverlap[0]) / dNotOverlap[0])\r\n nbPatches_in_X = int((size_zero_pad[1] - dOverlap[1]) / dNotOverlap[1])\r\n nbPatches_in_Z = int((size_zero_pad[2] - dOverlap[2]) / dNotOverlap[2])\r\n nbPatches = nbPatches_in_X * nbPatches_in_Y * nbPatches_in_Z\r\n\r\n dPatches = np.zeros((patchSize[0], patchSize[1], patchSize[2], int(nbPatches)), dtype=float)\r\n dLabels = np.zeros((int(nbPatches)), dtype = int) #float\r\n idxPatch = 0\r\n\r\n for iZ in range(0, int(size_zero_pad[2] - dOverlap[2]), int(dNotOverlap[2])):\r\n for iY in range(0, int(size_zero_pad[0] - dOverlap[0]), int(dNotOverlap[0])):\r\n for iX in range(0, int(size_zero_pad[1] - dOverlap[1]), int(dNotOverlap[1])):\r\n dPatch = Img_zero_pad[iY:iY + patchSize[0], iX:iX + patchSize[1], iZ:iZ + patchSize[2]]\r\n dPatches[:,:,:,idxPatch] = dPatch\r\n\r\n dPatch_mask = Mask_zero_pad[iY:iY + patchSize[0], iX:iX + patchSize[1], iZ:iZ + patchSize[2]]\r\n patch_number_value = patchSize[0] * patchSize[1]*patchSize[2]\r\n\r\n if np.count_nonzero((dPatch_mask==1).astype(np.int)) > int(ratio_labeling*patch_number_value):\r\n move_artefact = True\r\n if np.count_nonzero((dPatch_mask==2).astype(np.int)) > int(ratio_labeling*patch_number_value):\r\n shim_artefact = True\r\n if np.count_nonzero((dPatch_mask==3).astype(np.int)) > int(ratio_labeling*patch_number_value):\r\n noise_artefact = True\r\n\r\n label = Label.REFERENCE\r\n\r\n if move_artefact == True and shim_artefact != True and noise_artefact != True:\r\n label = Label.MOTION\r\n elif move_artefact != True and shim_artefact == True and noise_artefact != True:\r\n label = Label.SHIM\r\n elif move_artefact != True and shim_artefact != True and noise_artefact == True:\r\n label = Label.NOISE\r\n elif move_artefact == True and shim_artefact == True and noise_artefact != True:\r\n label = Label.MOTION_AND_SHIM\r\n elif move_artefact == True and shim_artefact != True and noise_artefact == True:\r\n label = Label.MOTION_AND_NOISE\r\n elif move_artefact != True and shim_artefact == True and noise_artefact == True:\r\n label = Label.SHIM_AND_NOISE\r\n elif move_artefact == True and shim_artefact == True and noise_artefact == True:\r\n label = Label.MOTION_AND_SHIM_AND_NOISE\r\n\r\n if isinstance(dataset, int):\r\n label = bodyRegionweightingLabel + label\r\n else:\r\n label = weightingLabel + bodyRegionLabel + label\r\n\r\n dLabels[idxPatch] = label\r\n idxPatch += 1\r\n\r\n move_artefact = False\r\n shim_artefact = False\r\n noise_artefact = False\r\n\r\n if isinstance(dataset, int):\r\n return dPatches\r\n else:\r\n print(\"Rigid patching done for %s \" % dataset.getPathdata())\r\n #print(dLabels)\r\n return dPatches, dLabels#, nbPatches\r\n\r\ndef fRigidPatching3D_maskLabeling_tf(dicom_tensor, patchSize, patchOverlap, mask_numpy_array, ratio_labeling, dataset=None, dopatching=True):\r\n #ToDo odd patch size not supported!\r\n\r\n dOverlap = tf.math.round(tf.math.multiply(patchSize, patchOverlap))\r\n dNotOverlap = tf.math.round(tf.math.multiply(patchSize, (1 - patchOverlap)))\r\n\r\n imgShape = dicom_tensor.shape.as_list()\r\n\r\n size_zero_pad = np.array(([math.ceil((imgShape[0] - dOverlap[0]) / (dNotOverlap[0])) * dNotOverlap[0] + dOverlap[0],\r\n math.ceil((imgShape[1] - dOverlap[1]) / (dNotOverlap[1])) * dNotOverlap[1] + dOverlap[1],\r\n math.ceil((imgShape[2] - dOverlap[2]) / (dNotOverlap[2])) * dNotOverlap[2] + dOverlap[2]]))\r\n zero_pad = np.array(([int(size_zero_pad[0]) - imgShape[0],\r\n int(size_zero_pad[1]) - imgShape[1],\r\n int(size_zero_pad[2]) - imgShape[2]]))\r\n zero_pad_part = np.array(([int(math.ceil(zero_pad[0] / 2)),\r\n int(math.ceil(zero_pad[1] / 2)),\r\n int(math.ceil(zero_pad[2] / 2))]))\r\n\r\n Img_zero_pad = tf.pad(dicom_tensor,\r\n tf.Variable((zero_pad_part[0], zero_pad[0] - zero_pad_part[0]),\r\n (zero_pad_part[1], zero_pad[1] - zero_pad_part[1]),\r\n (zero_pad_part[2], zero_pad[2] - zero_pad_part[2])),\r\n mode='constant')\r\n\r\n #nbPatches = ((size_zero_pad[0]-patchSize[0])/((1-patchOverlap)*patchSize[0])+1)*((size_zero_pad[1]-patchSize[1])/((1-patchOverlap)*patchSize[1])+1)*((size_zero_pad[2]-patchSize[2])/(tf.math.round((1-patchOverlap)*patchSize[2]))+1)\r\n\r\n #nbPatches_in_Y = int((size_zero_pad[0] - dOverlap[0]) / dNotOverlap[0])\r\n #nbPatches_in_X = int((size_zero_pad[1] - dOverlap[1]) / dNotOverlap[1])\r\n #nbPatches_in_Z = int((size_zero_pad[2] - dOverlap[2]) / dNotOverlap[2])\r\n #nbPatches = nbPatches_in_X * nbPatches_in_Y * nbPatches_in_Z\r\n\r\n #dPatches = tf.zeros((patchSize[0], patchSize[1], patchSize[2], int(nbPatches)), dtype=float)\r\n\r\n patch = [None for _ in range(fcalculatepatches(imgShape, patchSize, patchOverlap))]\r\n idxPatch = 0\r\n for iZ in range(0, int(size_zero_pad[2] - dOverlap[2]), int(dNotOverlap[2])):\r\n for iY in range(0, int(size_zero_pad[0] - dOverlap[0]), int(dNotOverlap[0])):\r\n for iX in range(0, int(size_zero_pad[1] - dOverlap[1]), int(dNotOverlap[1])):\r\n patch[idxPatch] = tf.slice(Img_zero_pad, begin=[iY, iX, iZ], size=[patchSize[0], patchSize[1], patchSize[2]])\r\n idxPatch += 1\r\n\r\n dPatches = tf.stack(patch, axis=3)\r\n return dPatches\r\n\r\n\r\ndef fcalculatepatches(imageSize, patchSize, patchOverlap):\r\n\r\n dOverlap = np.round(np.multiply(patchSize, patchOverlap))\r\n dNotOverlap = np.round(np.multiply(patchSize, (1 - patchOverlap)))\r\n\r\n size_zero_pad = np.array(\r\n ([math.ceil((imageSize[0] - dOverlap[0]) / (dNotOverlap[0])) * dNotOverlap[0] + dOverlap[0],\r\n math.ceil((imageSize[1] - dOverlap[1]) / (dNotOverlap[1])) * dNotOverlap[1] + dOverlap[1],\r\n math.ceil((imageSize[2] - dOverlap[2]) / (dNotOverlap[2])) * dNotOverlap[2] + dOverlap[2]]))\r\n\r\n idxPatch = 0\r\n for iZ in range(0, int(size_zero_pad[2] - dOverlap[2]), int(dNotOverlap[2])):\r\n for iY in range(0, int(size_zero_pad[0] - dOverlap[0]), int(dNotOverlap[0])):\r\n for iX in range(0, int(size_zero_pad[1] - dOverlap[1]), int(dNotOverlap[1])):\r\n idxPatch += 1\r\n\r\n return idxPatch",
"import os\r\n#os.environ[\"CUDA_DEVICE_ORDER\"]=\"0000:02:00.0\"\r\n#os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\r\n\r\nfrom tensorflow.python.client import device_lib\r\nprint(device_lib.list_local_devices)\r\n\r\nimport tensorflow as tf\r\nfrom keras.backend.tensorflow_backend import set_session\r\nconfig = tf.ConfigProto()\r\nconfig.gpu_options.per_process_gpu_memory_fraction = 1.0\r\nset_session(tf.Session(config=config))\r\n\r\nimport os.path\r\nimport scipy.io as sio\r\nimport numpy as np\r\nimport math\r\nimport keras\r\nfrom keras.layers import Input\r\nimport keras.backend as K\r\nfrom keras.layers import Conv2D\r\nfrom keras.layers import BatchNormalization\r\nfrom keras.layers import GlobalAveragePooling2D\r\nfrom keras.layers.core import Dense, Activation, Flatten\r\nfrom keras.models import Model\r\nfrom keras.models import Sequential\r\nfrom keras.layers.convolutional import Convolution2D\r\nfrom keras.callbacks import EarlyStopping\r\nfrom keras.callbacks import LearningRateScheduler\r\nfrom keras.callbacks import ReduceLROnPlateau\r\nfrom keras.callbacks import ModelCheckpoint\r\nfrom keras.models import model_from_json\r\nfrom keras.regularizers import l2 # , activity_l2\r\n\r\nfrom DLart.Constants_DLart import *\r\nfrom utils.image_preprocessing import ImageDataGenerator\r\nfrom utils.LivePlotCallback import LivePlotCallback\r\nfrom matplotlib import pyplot as plt\r\n\r\nfrom networks.multiclass.SENets.deep_residual_learning_blocks import *\r\n\r\n\r\ndef createModel(patchSize, numClasses):\r\n # SE-ResNet-56 based on CIFAR-10, for 32x32 Images\r\n print(K.image_data_format())\r\n\r\n if K.image_data_format() == 'channels_last':\r\n bn_axis = -1\r\n else:\r\n bn_axis = 1\r\n\r\n input_tensor = Input(shape=(patchSize[0], patchSize[1], 1))\r\n\r\n # first conv layer\r\n x = Conv2D(16, (3,3), strides=(1,1), kernel_initializer='he_normal', name='conv1')(input_tensor)\r\n x = BatchNormalization(axis=bn_axis, name='bn_conv1')(x)\r\n x = Activation('relu')(x)\r\n\r\n # first stage of 2n=2*9=18 Convs (3x3, 16)\r\n x = identity_block(x, [16, 16], stage=1, block=1, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [16, 16], stage=1, block=2, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [16, 16], stage=1, block=3, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [16, 16], stage=1, block=4, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [16, 16], stage=1, block=5, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [16, 16], stage=1, block=6, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [16, 16], stage=1, block=7, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [16, 16], stage=1, block=8, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [16, 16], stage=1, block=9, se_enabled=True, se_ratio=4)\r\n\r\n # second stage of 2n=2*9=18 convs (3x3, 32)\r\n x = projection_block(x, [32, 32], stage=2, block=1, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [32, 32], stage=2, block=2, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [32, 32], stage=2, block=3, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [32, 32], stage=2, block=4, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [32, 32], stage=2, block=5, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [32, 32], stage=2, block=6, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [32, 32], stage=2, block=7, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [32, 32], stage=2, block=8, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [32, 32], stage=2, block=9, se_enabled=True, se_ratio=4)\r\n\r\n # third stage of 3n=3*9=18 convs (3x3, 64)\r\n x = projection_block(x, [64, 64], stage=3, block=1, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [64, 64], stage=3, block=2, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [64, 64], stage=3, block=3, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [64, 64], stage=3, block=4, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [64, 64], stage=3, block=5, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [64, 64], stage=3, block=6, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [64, 64], stage=3, block=7, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [64, 64], stage=3, block=8, se_enabled=True, se_ratio=4)\r\n x = identity_block(x, [64, 64], stage=3, block=9, se_enabled=True, se_ratio=4)\r\n\r\n # global average pooling\r\n x = GlobalAveragePooling2D(data_format='channels_last')(x)\r\n\r\n # fully-connected layer\r\n output = Dense(units=numClasses,\r\n activation='softmax',\r\n kernel_initializer='he_normal',\r\n name='fully-connected')(x)\r\n\r\n # create model\r\n sModelName = 'SE-ResNet-56'\r\n cnn = Model(input_tensor, output, name=sModelName)\r\n\r\n return cnn, sModelName\r\n\r\n\r\ndef fTrain(X_train=None, y_train=None, X_valid=None, y_valid=None, X_test=None, y_test=None, sOutPath=None, patchSize=0, batchSizes=None, learningRates=None, iEpochs=None, dlart_handle=None):\r\n # grid search on batch_sizes and learning rates\r\n # parse inputs\r\n batchSize = batchSizes[0]\r\n learningRate = learningRates[0]\r\n\r\n # change the shape of the dataset -> at color channel -> here one for grey scale\r\n X_train = np.expand_dims(X_train, axis=-1)\r\n X_test = np.expand_dims(X_test, axis=-1)\r\n\r\n if X_valid is not None and y_valid is not None:\r\n X_valid = np.expand_dims(X_valid, axis=-1)\r\n\r\n #y_train = np.asarray([y_train[:], np.abs(np.asarray(y_train[:], dtype=np.float32) - 1)]).T\r\n #y_test = np.asarray([y_test[:], np.abs(np.asarray(y_test[:], dtype=np.float32) - 1)]).T\r\n\r\n # number of classes\r\n numClasses = np.shape(y_train)[1]\r\n\r\n #create cnn model\r\n cnn, sModelName = createModel(patchSize=patchSize, numClasses=numClasses)\r\n\r\n fTrainInner(cnn,\r\n sModelName,\r\n X_train=X_train,\r\n y_train=y_train,\r\n X_valid=X_valid,\r\n y_valid=y_valid,\r\n X_test=X_test,\r\n y_test=y_test,\r\n sOutPath=sOutPath,\r\n patchSize=patchSize,\r\n batchSize=batchSize,\r\n learningRate=learningRate,\r\n iEpochs=iEpochs,\r\n dlart_handle=dlart_handle)\r\n\r\n K.clear_session()\r\n\r\n # for iBatch in batchSizes:\r\n # for iLearn in learningRates:\r\n # fTrainInner(cnn,\r\n # sModelName,\r\n # X_train=X_train,\r\n # y_train=y_train,\r\n # X_valid=X_valid,\r\n # y_valid=y_valid,\r\n # X_test=X_test,\r\n # y_test=y_test,\r\n # sOutPath=sOutPath,\r\n # patchSize=patchSize,\r\n # batchSize=iBatch,\r\n # learningRate=iLearn,\r\n # iEpochs=iEpochs,\r\n # dlart_handle=dlart_handle)\r\n\r\ndef fTrainInner(cnn, modelName, X_train=None, y_train=None, X_valid=None, y_valid=None, X_test=None, y_test=None, sOutPath=None, patchSize=0, batchSize=None, learningRate=None, iEpochs=None, dlart_handle=None):\r\n print('Training CNN')\r\n print('with lr = ' + str(learningRate) + ' , batchSize = ' + str(batchSize))\r\n\r\n # save names\r\n _, sPath = os.path.splitdrive(sOutPath)\r\n sPath, sFilename = os.path.split(sPath)\r\n sFilename, sExt = os.path.splitext(sFilename)\r\n\r\n model_name = sOutPath + os.sep + sFilename + '_lr_' + str(learningRate) + '_bs_' + str(batchSize)\r\n weight_name = model_name + '_weights.h5'\r\n model_json = model_name + '.json'\r\n model_all = model_name + '_model.h5'\r\n model_mat = model_name + '.mat'\r\n\r\n if (os.path.isfile(model_mat)): # no training if output file exists\r\n print('------- already trained -> go to next')\r\n return\r\n\r\n\r\n # create optimizer\r\n if dlart_handle != None:\r\n if dlart_handle.getOptimizer() == SGD_OPTIMIZER:\r\n opti = keras.optimizers.SGD(lr=learningRate,\r\n momentum=dlart_handle.getMomentum(),\r\n decay=dlart_handle.getWeightDecay(),\r\n nesterov=dlart_handle.getNesterovEnabled())\r\n elif dlart_handle.getOptimizer() == RMS_PROP_OPTIMIZER:\r\n opti = keras.optimizers.RMSprop(lr=learningRate, decay=dlart_handle.getWeightDecay())\r\n elif dlart_handle.getOptimizer() == ADAGRAD_OPTIMIZER:\r\n opti = keras.optimizers.Adagrad(lr=learningRate, epsilon=None, decay=dlart_handle.getWeightDecay())\r\n elif dlart_handle.getOptimizer() == ADADELTA_OPTIMIZER:\r\n opti = keras.optimizers.Adadelta(lr=learningRate, rho=0.95, epsilon=None,\r\n decay=dlart_handle.getWeightDecay())\r\n elif dlart_handle.getOptimizer() == ADAM_OPTIMIZER:\r\n opti = keras.optimizers.Adam(lr=learningRate, beta_1=0.9, beta_2=0.999, epsilon=None,\r\n decay=dlart_handle.getWeightDecay())\r\n else:\r\n raise ValueError(\"Unknown Optimizer!\")\r\n else:\r\n # opti = SGD(lr=learningRate, momentum=1e-8, decay=0.1, nesterov=True);#Adag(lr=0.01, epsilon=1e-06)\r\n opti = keras.optimizers.Adam(lr=learningRate, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\r\n\r\n cnn.summary()\r\n\r\n # compile model\r\n cnn.compile(loss='categorical_crossentropy', optimizer=opti, metrics=['accuracy'])\r\n\r\n # callbacks\r\n callback_earlyStopping = EarlyStopping(monitor='val_loss', patience=25, verbose=1)\r\n #callback_tensorBoard = keras.callbacks.TensorBoard(log_dir=dlart_handle.getLearningOutputPath() + '/logs',\r\n #histogram_freq=2,\r\n #batch_size=batchSize,\r\n #write_graph=True,\r\n # write_grads=True,\r\n # write_images=True,\r\n # embeddings_freq=0,\r\n # embeddings_layer_names=None,\r\n # embeddings_metadata=None)\r\n\r\n callbacks = [callback_earlyStopping]\r\n callbacks.append(ModelCheckpoint(sOutPath + os.sep + 'checkpoints/checker.hdf5', monitor='val_acc', verbose=0, period=5, save_best_only=True)) # overrides the last checkpoint, its just for security\r\n #callbacks.append(ReduceLROnPlateau(monitor='loss', factor=0.1, patience=5, min_lr=1e-4, verbose=1))\r\n callbacks.append(LearningRateScheduler(schedule=step_decay, verbose=1))\r\n callbacks.append(LivePlotCallback(dlart_handle))\r\n\r\n\r\n # data augmentation\r\n if dlart_handle.getDataAugmentationEnabled() == True:\r\n # Initialize Image Generator\r\n # all shifted and rotated images are filled with zero padded pixels\r\n datagen = ImageDataGenerator(\r\n featurewise_center=False,\r\n samplewise_center=False,\r\n featurewise_std_normalization=False,\r\n samplewise_std_normalization=False,\r\n zca_whitening=dlart_handle.getZCA_Whitening(),\r\n zca_epsilon=1e-6,\r\n rotation_range=dlart_handle.getRotation(),\r\n width_shift_range=dlart_handle.getWidthShift(),\r\n height_shift_range=dlart_handle.getHeightShift(),\r\n shear_range=0.,\r\n zoom_range=dlart_handle.getZoom(),\r\n channel_shift_range=0.,\r\n fill_mode='constant',\r\n cval=0.,\r\n horizontal_flip=dlart_handle.getHorizontalFlip(),\r\n vertical_flip=dlart_handle.getVerticalFlip(),\r\n rescale=None,\r\n histogram_equalization=dlart_handle.getHistogramEqualization(),\r\n contrast_stretching=dlart_handle.getContrastStretching(),\r\n adaptive_equalization=dlart_handle.getAdaptiveEqualization(),\r\n preprocessing_function=None,\r\n data_format=K.image_data_format()\r\n )\r\n\r\n datagen_val = ImageDataGenerator(featurewise_center=False,\r\n samplewise_center=False,\r\n featurewise_std_normalization=False,\r\n samplewise_std_normalization=False,\r\n zca_whitening=dlart_handle.getZCA_Whitening(),\r\n zca_epsilon=1e-6,\r\n rotation_range=0.,\r\n width_shift_range=0.,\r\n height_shift_range=0.,\r\n shear_range=0.,\r\n zoom_range=0.,\r\n channel_shift_range=0.,\r\n fill_mode='constant',\r\n cval=0.,\r\n horizontal_flip=False,\r\n vertical_flip=False,\r\n rescale=None,\r\n histogram_equalization=dlart_handle.getHistogramEqualization(),\r\n contrast_stretching=dlart_handle.getContrastStretching(),\r\n adaptive_equalization=dlart_handle.getAdaptiveEqualization(),\r\n preprocessing_function=None,\r\n data_format=K.image_data_format())\r\n\r\n datagen_test = ImageDataGenerator(featurewise_center=False,\r\n samplewise_center=False,\r\n featurewise_std_normalization=False,\r\n samplewise_std_normalization=False,\r\n zca_whitening=dlart_handle.getZCA_Whitening(),\r\n zca_epsilon=1e-6,\r\n rotation_range=0.,\r\n width_shift_range=0.,\r\n height_shift_range=0.,\r\n shear_range=0.,\r\n zoom_range=0.,\r\n channel_shift_range=0.,\r\n fill_mode='constant',\r\n cval=0.,\r\n horizontal_flip=False,\r\n vertical_flip=False,\r\n rescale=None,\r\n histogram_equalization=dlart_handle.getHistogramEqualization(),\r\n contrast_stretching=dlart_handle.getContrastStretching(),\r\n adaptive_equalization=dlart_handle.getAdaptiveEqualization(),\r\n preprocessing_function=None,\r\n data_format=K.image_data_format())\r\n\r\n # fit parameters from dataset\r\n datagen.fit(X_train)\r\n datagen_test.fit(X_test)\r\n\r\n # configure batch size and get one batch of images\r\n for x_batch, y_batch in datagen.flow(X_train, y_train, batch_size=9):\r\n # display first 9 images\r\n for i in range(0, 9):\r\n plt.subplot(330+1+i)\r\n plt.imshow(x_batch[i].reshape(x_batch.shape[1], x_batch.shape[2]), cmap='gray')\r\n plt.show()\r\n break\r\n\r\n if X_valid is not None and y_valid is not None:\r\n # fit model on data\r\n # use validation/test split\r\n datagen_val.fit(X_valid)\r\n result = cnn.fit_generator(datagen.flow(X_train, y_train, batch_size=batchSize),\r\n steps_per_epoch=X_train.shape[0]//batchSize,\r\n epochs=iEpochs,\r\n validation_data=datagen_val.flow(X_valid, y_valid, batch_size=batchSize),\r\n callbacks=callbacks,\r\n workers=1,\r\n use_multiprocessing=False)\r\n\r\n else:\r\n # fit model on data\r\n # use test data for validation and test\r\n\r\n result = cnn.fit_generator(datagen.flow(X_train, y_train, batch_size=batchSize),\r\n steps_per_epoch=X_train.shape[0] // batchSize,\r\n epochs=iEpochs,\r\n validation_data=datagen_test.flow(X_test, y_test, batch_size=batchSize),\r\n callbacks=callbacks,\r\n workers=1,\r\n use_multiprocessing=False)\r\n\r\n # return the loss value and metrics values for the model in test mode\r\n score_test, acc_test = cnn.evaluate_generator(datagen_test.flow(X_test, y_test, batch_size=batchSize),\r\n steps=None,\r\n max_queue_size=10,\r\n workers=1,\r\n use_multiprocessing=False)\r\n\r\n prob_test = cnn.predict_generator(datagen_test.flow(X_test, y_test, batch_size=batchSize),\r\n steps = None,\r\n max_queue_size = 10,\r\n workers = 1,\r\n use_multiprocessing = False,\r\n verbose = 1)\r\n\r\n else:\r\n if X_valid is not None and y_valid is not None:\r\n # use validation/test split\r\n result = cnn.fit(X_train,\r\n y_train,\r\n validation_data=(X_valid, y_valid),\r\n epochs=iEpochs,\r\n batch_size=batchSize,\r\n callbacks=callbacks,\r\n verbose=1)\r\n else:\r\n # use test set for validation and test\r\n result = cnn.fit(X_train,\r\n y_train,\r\n validation_data=(X_test, y_test),\r\n epochs=iEpochs,\r\n batch_size=batchSize,\r\n callbacks=callbacks,\r\n verbose=1)\r\n\r\n # return the loss value and metrics values for the model in test mode\r\n score_test, acc_test = cnn.evaluate(X_test, y_test, batch_size=batchSize, verbose=1)\r\n\r\n prob_test = cnn.predict(X_test, batchSize, 0)\r\n\r\n\r\n # save model\r\n json_string = cnn.to_json()\r\n with open(model_json, 'w') as jsonFile:\r\n jsonFile.write(json_string)\r\n\r\n # wei = cnn.get_weights()\r\n cnn.save_weights(weight_name, overwrite=True)\r\n cnn.save(model_all) # keras > v0.7\r\n model_png_dir = sOutPath + os.sep + \"model.png\"\r\n from keras.utils import plot_model\r\n plot_model(cnn, to_file=model_png_dir, show_shapes=True, show_layer_names=True)\r\n\r\n # matlab\r\n acc = result.history['acc']\r\n loss = result.history['loss']\r\n val_acc = result.history['val_acc']\r\n val_loss = result.history['val_loss']\r\n\r\n print('Saving results: ' + model_name)\r\n sio.savemat(model_name, {'model_settings': model_json,\r\n 'model': model_all,\r\n 'weights': weight_name,\r\n 'acc': acc,\r\n 'loss': loss,\r\n 'val_acc': val_acc,\r\n 'val_loss': val_loss,\r\n 'score_test': score_test,\r\n 'acc_test': acc_test,\r\n 'prob_test': prob_test})\r\n\r\n\r\ndef step_decay(epoch, lr):\r\n drop = 0.1\r\n epochs_drop = 10.0\r\n print(\"Current Learning Rate: \" + str(lr))\r\n if epoch == epochs_drop or epoch == 2*epochs_drop or epoch == 3*epochs_drop or epoch == 4*epochs_drop:\r\n lr = drop*lr\r\n print(\"Reduce Learningrate by 0.1 to \" + str(lr))\r\n\r\n return lr\r\n\r\n\r\ndef fPredict(X,y, sModelPath, sOutPath, batchSize=64):\r\n \"\"\"Takes an already trained model and computes the loss and Accuracy over the samples X with their Labels y\r\n Input:\r\n X: Samples to predict on. The shape of X should fit to the input shape of the model\r\n y: Labels for the Samples. Number of Samples should be equal to the number of samples in X\r\n sModelPath: (String) full path to a trained keras model. It should be *_json.txt file. there has to be a corresponding *_weights.h5 file in the same directory!\r\n sOutPath: (String) full path for the Output. It is a *.mat file with the computed loss and accuracy stored.\r\n The Output file has the Path 'sOutPath'+ the filename of sModelPath without the '_json.txt' added the suffix '_pred.mat'\r\n batchSize: Batchsize, number of samples that are processed at once\"\"\"\r\n sModelPath = sModelPath.replace(\"_json.txt\", \"\")\r\n weight_name = sModelPath + '_weights.h5'\r\n model_json = sModelPath + '_json.txt'\r\n model_all = sModelPath + '_model.h5'\r\n\r\n # load weights and model (new way)\r\n model_json = open(model_json, 'r')\r\n model_string = model_json.read()\r\n model_json.close()\r\n model = model_from_json(model_string)\r\n\r\n model.compile(loss='categorical_crossentropy', optimizer=keras.optimizers.Adam(), metrics=['accuracy'])\r\n model.load_weights(weight_name)\r\n\r\n score_test, acc_test = model.evaluate(X, y, batch_size=batchSize)\r\n print('loss' + str(score_test) + ' acc:' + str(acc_test))\r\n prob_pre = model.predict(X, batch_size=batchSize, verbose=1)\r\n print(prob_pre[0:14, :])\r\n _, sModelFileSave = os.path.split(sModelPath)\r\n\r\n modelSave = sOutPath + sModelFileSave + '_pred.mat'\r\n print('saving Model:{}'.format(modelSave))\r\n sio.savemat(modelSave, {'prob_pre': prob_pre, 'score_test': score_test, 'acc_test': acc_test})\r\n\r\n\r\n###############################################################################\r\n## OPTIMIZATIONS ##\r\n###############################################################################\r\ndef fHyperasTrain(X_train, Y_train, X_test, Y_test, patchSize):\r\n # explicitly stated here instead of cnn = createModel() to allow optimization\r\n cnn = Sequential()\r\n # cnn.add(Convolution2D(32,\r\n # 14,\r\n # 14,\r\n # init='normal',\r\n # # activation='sigmoid',\r\n # weights=None,\r\n # border_mode='valid',\r\n # subsample=(1, 1),\r\n # W_regularizer=l2(1e-6),\r\n # input_shape=(1, patchSize[0,0], patchSize[0,1])))\r\n # cnn.add(Activation('relu'))\r\n\r\n cnn.add(Convolution2D(32, # 64\r\n 7,\r\n 7,\r\n init='normal',\r\n # activation='sigmoid',\r\n weights=None,\r\n border_mode='valid',\r\n subsample=(1, 1),\r\n W_regularizer=l2(1e-6)))\r\n cnn.add(Activation('relu'))\r\n cnn.add(Convolution2D(64, # learning rate: 0.1 -> 76%\r\n 3,\r\n 3,\r\n init='normal',\r\n # activation='sigmoid',\r\n weights=None,\r\n border_mode='valid',\r\n subsample=(1, 1),\r\n W_regularizer=l2(1e-6)))\r\n cnn.add(Activation('relu'))\r\n\r\n cnn.add(Convolution2D(128, # learning rate: 0.1 -> 76%\r\n 3,\r\n 3,\r\n init='normal',\r\n # activation='sigmoid',\r\n weights=None,\r\n border_mode='valid',\r\n subsample=(1, 1),\r\n W_regularizer=l2(1e-6)))\r\n cnn.add(Activation('relu'))\r\n\r\n # cnn.add(pool2(pool_size=(2, 2), strides=None, border_mode='valid', dim_ordering='th'))\r\n\r\n cnn.add(Flatten())\r\n # cnn.add(Dense(input_dim= 100,\r\n # output_dim= 100,\r\n # init = 'normal',\r\n # #activation = 'sigmoid',\r\n # W_regularizer='l2'))\r\n # cnn.add(Activation('sigmoid'))\r\n cnn.add(Dense(input_dim=100,\r\n output_dim=2,\r\n init='normal',\r\n # activation = 'sigmoid',\r\n W_regularizer='l2'))\r\n cnn.add(Activation('softmax'))\r\n\r\n #opti = SGD(lr={{choice([0.1, 0.01, 0.05, 0.005, 0.001])}}, momentum=1e-8, decay=0.1, nesterov=True)\r\n #cnn.compile(loss='categorical_crossentropy', optimizer=opti)\r\n\r\n epochs = 300\r\n\r\n result = cnn.fit(X_train, Y_train,\r\n batch_size=128, # {{choice([64, 128])}}\r\n nb_epoch=epochs,\r\n show_accuracy=True,\r\n verbose=2,\r\n validation_data=(X_test, Y_test))\r\n score_test, acc_test = cnn.evaluate(X_test, Y_test, verbose=0)\r\n\r\n #return {'loss': -acc_test, 'status': STATUS_OK, 'model': cnn, 'trainresult': result, 'score_test': score_test}\r\n\r\n\r\n## helper functions\r\ndef drange(start, stop, step):\r\n r = start\r\n while r < stop:\r\n yield r\r\n r += step",
"import os\r\nimport os.path\r\nimport keras\r\nimport keras.backend as K\r\nfrom keras.models import model_from_json\r\nimport tensorflow as tf\r\n\r\nfrom utils.label import *\r\n\r\nfrom sklearn.metrics import classification_report, confusion_matrix\r\nfrom DLart.Constants_DLart import *\r\n\r\n\r\ndef predict_model(X_test, Y_test, sModelPath, batch_size=32, dlart_handle=None):\r\n X_test = np.expand_dims(X_test, axis=-1)\r\n\r\n # pathes\r\n _, sPath = os.path.splitdrive(sModelPath)\r\n sPath, sFilename = os.path.split(sPath)\r\n sFilename, sExt = os.path.splitext(sFilename)\r\n\r\n # load weights and model\r\n with open(sModelPath + os.sep + sFilename + '.json', 'r') as fp:\r\n model_string = fp.read()\r\n\r\n model = model_from_json(model_string)\r\n\r\n # create optimizer\r\n\r\n if dlart_handle is not None:\r\n if dlart_handle.getOptimizer() == SGD_OPTIMIZER:\r\n opti = keras.optimizers.SGD(momentum=dlart_handle.getMomentum(),\r\n decay=dlart_handle.getWeightDecay(),\r\n nesterov=dlart_handle.getNesterovEnabled())\r\n\r\n elif dlart_handle.getOptimizer() == RMS_PROP_OPTIMIZER:\r\n opti = keras.optimizers.RMSprop(decay=dlart_handle.getWeightDecay())\r\n\r\n elif dlart_handle.getOptimizer() == ADAGRAD_OPTIMIZER:\r\n opti = keras.optimizers.Adagrad(epsilon=None, decay=dlart_handle.getWeightDecay())\r\n\r\n elif dlart_handle.getOptimizer() == ADADELTA_OPTIMIZER:\r\n opti = keras.optimizers.Adadelta(rho=0.95, epsilon=None,\r\n decay=dlart_handle.getWeightDecay())\r\n\r\n elif dlart_handle.getOptimizer() == ADAM_OPTIMIZER:\r\n opti = keras.optimizers.Adam(beta_1=0.9, beta_2=0.999, epsilon=None,\r\n decay=dlart_handle.getWeightDecay())\r\n else:\r\n raise ValueError(\"Unknown Optimizer!\")\r\n else:\r\n opti = keras.optimizers.Adam(beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\r\n model.summary()\r\n\r\n model.compile(loss='categorical_crossentropy', optimizer=opti, metrics=['accuracy'])\r\n model.load_weights(sModelPath + os.sep + sFilename + '_weights.h5')\r\n\r\n # evaluate model on test data\r\n score_test, acc_test = model.evaluate(X_test, Y_test, batch_size=batch_size)\r\n print('loss' + str(score_test) + ' acc:' + str(acc_test))\r\n\r\n # predict test dataset\r\n probability_predictions = model.predict(X_test, batch_size=batch_size, verbose=1, steps=None)\r\n\r\n # classification report\r\n # target_names = []\r\n # if len(classMappings[list(classMappings.keys())[0]]) == 3:\r\n # for i in sorted(classMappings):\r\n # i = i % 100\r\n # i = i % 10\r\n # if Label.LABEL_STRINGS[i] not in target_names:\r\n # target_names.append(Label.LABEL_STRINGS[i])\r\n # elif len(classMappings[list(classMappings.keys())[0]]) == 8:\r\n # for i in sorted(classMappings):\r\n # i = i % 100\r\n # if Label.LABEL_STRINGS[i] not in target_names:\r\n # target_names.append(Label.LABEL_STRINGS[i])\r\n # else:\r\n # for i in sorted(classMappings):\r\n # target_names.append(Label.LABEL_STRINGS[i])\r\n\r\n classification_summary = classification_report(np.argmax(Y_test, axis=1),\r\n np.argmax(probability_predictions, axis=1),\r\n target_names=None, digits=4)\r\n\r\n # confusion matrix\r\n confusionMatrix = confusion_matrix(y_true=np.argmax(Y_test, axis=1),\r\n y_pred=np.argmax(probability_predictions, axis=1),\r\n labels=range(int(probability_predictions.shape[1])))\r\n\r\n prediction = {\r\n 'predictions': probability_predictions,\r\n 'score_test': score_test,\r\n 'acc_test': acc_test,\r\n 'classification_report': classification_summary,\r\n 'confusion_matrix': confusionMatrix\r\n }\r\n\r\n return prediction\r\n\r\n\r\ndef predict_segmentation_model(X_test, y_test=None, Y_segMasks_test=None, sModelPath=None, sOutPath=None, batch_size=64,\r\n usingClassification=False, dlart_handle=None):\r\n \"\"\"Takes an already trained model and computes the loss and Accuracy over the samples X with their Labels y\r\n Input:\r\n X: Samples to predict on. The shape of X should fit to the input shape of the model\r\n y: Labels for the Samples. Number of Samples should be equal to the number of samples in X\r\n sModelPath: (String) full path to a trained keras model. It should be *_json.txt file. there has to be a corresponding *_weights.h5 file in the same directory!\r\n sOutPath: (String) full path for the Output. It is a *.mat file with the computed loss and accuracy stored.\r\n The Output file has the Path 'sOutPath'+ the filename of sModelPath without the '_json.txt' added the suffix '_pred.mat'\r\n batchSize: Batchsize, number of samples that are processed at once\"\"\"\r\n\r\n X_test = np.expand_dims(X_test, axis=-1)\r\n Y_segMasks_test_foreground = np.expand_dims(Y_segMasks_test, axis=-1)\r\n Y_segMasks_test_background = np.ones(Y_segMasks_test_foreground.shape) - Y_segMasks_test_foreground\r\n Y_segMasks_test = np.concatenate((Y_segMasks_test_background, Y_segMasks_test_foreground), axis=-1)\r\n\r\n # if usingClassification:\r\n # y_test = np.expand_dims(y_test, axis=-1)\r\n\r\n _, sPath = os.path.splitdrive(sModelPath)\r\n sPath, sFilename = os.path.split(sPath)\r\n sFilename, sExt = os.path.splitext(sFilename)\r\n\r\n listdir = os.listdir(sModelPath)\r\n\r\n # sModelPath = sModelPath.replace(\"_json.txt\", \"\")\r\n # weight_name = sModelPath + '_weights.h5'\r\n # model_json = sModelPath + '_json.txt'\r\n # model_all = sModelPath + '_model.h5'\r\n\r\n # load weights and model (new way)\r\n with open(sModelPath + os.sep + sFilename + '.json', 'r') as fp:\r\n model_string = fp.read()\r\n\r\n model = model_from_json(model_string)\r\n\r\n model.summary()\r\n\r\n if dlart_handle is not None:\r\n if dlart_handle.getOptimizer() == SGD_OPTIMIZER:\r\n opti = keras.optimizers.SGD(momentum=dlart_handle.getMomentum(),\r\n decay=dlart_handle.getWeightDecay(),\r\n nesterov=dlart_handle.getNesterovEnabled())\r\n\r\n elif dlart_handle.getOptimizer() == RMS_PROP_OPTIMIZER:\r\n opti = keras.optimizers.RMSprop(decay=dlart_handle.getWeightDecay())\r\n\r\n elif dlart_handle.getOptimizer() == ADAGRAD_OPTIMIZER:\r\n opti = keras.optimizers.Adagrad(epsilon=None, decay=dlart_handle.getWeightDecay())\r\n\r\n elif dlart_handle.getOptimizer() == ADADELTA_OPTIMIZER:\r\n opti = keras.optimizers.Adadelta(rho=0.95, epsilon=None,\r\n decay=dlart_handle.getWeightDecay())\r\n\r\n elif dlart_handle.getOptimizer() == ADAM_OPTIMIZER:\r\n opti = keras.optimizers.Adam(beta_1=0.9, beta_2=0.999, epsilon=None,\r\n decay=dlart_handle.getWeightDecay())\r\n else:\r\n raise ValueError(\"Unknown Optimizer!\")\r\n else:\r\n opti = keras.optimizers.Adam(beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\r\n\r\n if usingClassification:\r\n model.compile(loss={'segmentation_output': dice_coef_loss, 'classification_output': 'categorical_crossentropy'},\r\n optimizer=opti,\r\n metrics={'segmentation_output': dice_coef, 'classification_output': 'accuracy'})\r\n\r\n model.load_weights(sModelPath + os.sep + sFilename + '_weights.h5')\r\n\r\n loss_test, segmentation_output_loss_test, classification_output_loss_test, segmentation_output_dice_coef_test, classification_output_acc_test \\\r\n = model.evaluate(X_test,\r\n {'segmentation_output': Y_segMasks_test, 'classification_output': y_test},\r\n batch_size=batch_size, verbose=1)\r\n\r\n print('loss' + str(loss_test) + ' segmentation loss:' + str(\r\n segmentation_output_loss_test) + ' classification loss: ' + str(classification_output_loss_test) + \\\r\n ' segmentation dice coef: ' + str(\r\n segmentation_output_dice_coef_test) + ' classification accuracy: ' + str(classification_output_acc_test))\r\n\r\n prob_pre = model.predict(X_test, batch_size=batch_size, verbose=1)\r\n\r\n predictions = {'prob_pre': prob_pre,\r\n 'loss_test': loss_test,\r\n 'segmentation_output_loss_test': segmentation_output_loss_test,\r\n 'classification_output_loss_test': classification_output_loss_test,\r\n 'segmentation_output_dice_coef_test': segmentation_output_dice_coef_test,\r\n 'classification_output_acc_test': classification_output_acc_test}\r\n else:\r\n model.compile(loss=dice_coef_loss, optimizer=opti, metrics=[dice_coef])\r\n model.load_weights(sModelPath + os.sep + sFilename + '_weights.h5')\r\n\r\n score_test, acc_test = model.evaluate(X_test, Y_segMasks_test, batch_size=batch_size)\r\n print('loss: ' + str(score_test) + ' dice coef:' + str(acc_test))\r\n\r\n prob_pre = model.predict(X_test, batch_size=batch_size, verbose=1)\r\n\r\n predictions = {'prob_pre': prob_pre, 'score_test': score_test, 'acc_test': acc_test}\r\n\r\n return predictions\r\n\r\n\r\ndef dice_coef(y_true, y_pred, epsilon=1e-5):\r\n dice_numerator = 2.0 * K.sum(y_true * y_pred, axis=[1, 2, 3, 4])\r\n dice_denominator = K.sum(K.square(y_true), axis=[1, 2, 3, 4]) + K.sum(K.square(y_pred), axis=[1, 2, 3, 4])\r\n\r\n dice_score = dice_numerator / (dice_denominator + epsilon)\r\n return K.mean(dice_score, axis=0)\r\n\r\n\r\ndef dice_coef_loss(y_true, y_pred):\r\n return 1 - dice_coef(y_true, y_pred)\r\n\r\n\r\ndef dice_coef_2(ground_truth, prediction, weight_map=None):\r\n \"\"\"\r\n Function to calculate the dice loss with the definition given in\r\n\r\n Milletari, F., Navab, N., & Ahmadi, S. A. (2016)\r\n V-net: Fully convolutional neural\r\n networks for volumetric medical image segmentation. 3DV 2016\r\n\r\n using a square in the denominator\r\n\r\n :param prediction: the logits\r\n :param ground_truth: the segmentation ground_truth\r\n :param weight_map:\r\n :return: the loss\r\n \"\"\"\r\n ground_truth = tf.to_int64(ground_truth)\r\n prediction = tf.cast(prediction, tf.float32)\r\n ids = tf.range(tf.to_int64(tf.shape(ground_truth)[0]), dtype=tf.int64)\r\n ids = tf.stack([ids, ground_truth], axis=1)\r\n one_hot = tf.SparseTensor(\r\n indices=ids,\r\n values=tf.ones_like(ground_truth, dtype=tf.float32),\r\n dense_shape=tf.to_int64(tf.shape(prediction)))\r\n if weight_map is not None:\r\n n_classes = prediction.shape[1].value\r\n weight_map_nclasses = tf.reshape(\r\n tf.tile(weight_map, [n_classes]), prediction.get_shape())\r\n dice_numerator = 2.0 * tf.sparse_reduce_sum(\r\n weight_map_nclasses * one_hot * prediction, reduction_axes=[0])\r\n dice_denominator = \\\r\n tf.reduce_sum(weight_map_nclasses * tf.square(prediction),\r\n reduction_indices=[0]) + \\\r\n tf.sparse_reduce_sum(one_hot * weight_map_nclasses,\r\n reduction_axes=[0])\r\n else:\r\n dice_numerator = 2.0 * tf.sparse_reduce_sum(\r\n one_hot * prediction, reduction_axes=[0])\r\n dice_denominator = \\\r\n tf.reduce_sum(tf.square(prediction), reduction_indices=[0]) + \\\r\n tf.sparse_reduce_sum(one_hot, reduction_axes=[0])\r\n epsilon_denominator = 0.00001\r\n\r\n dice_score = dice_numerator / (dice_denominator + epsilon_denominator)\r\n # dice_score.set_shape([n_classes])\r\n # minimising (1 - dice_coefficients)\r\n\r\n # return 1.0 - tf.reduce_mean(dice_score)\r\n return tf.reduce_mean(dice_score)\r\n",
"# -*- coding: utf-8 -*-\n\"\"\"\n----------------------------------\nMain function for calling the CNNs\n----------------------------------\nCreated on Wed Jan 27 16:57:10 2016\nCopyright: 2016, 2017 Thomas Kuestner ([email protected]) under Apache2 license\n@author: Thomas Kuestner\n\"\"\"\nfrom tensorflow.python.keras.models import load_model\n\nfrom config.PATH import CNN_PATH\n\n\"\"\"Import\"\"\"\n\nimport sys\nimport numpy as np # for algebraic operations, matrices\nimport h5py\nimport scipy.io as sio # I/O\nimport os.path # operating system\nimport argparse\nimport keras.backend as K\n\n# networks\nfrom networks.motion.CNN2D import *\nfrom networks.motion.CNN3D import *\nfrom networks.motion.MNetArt import *\nfrom networks.motion.VNetArt import *\nfrom networks.multiclass.DenseResNet import *\nfrom networks.multiclass.InceptionNet import *\nfrom networks.multiclass.SENets import *\n\nfrom hyperopt import Trials, STATUS_OK, tpe\nfrom hyperas import optim\nimport tensorflow as tf\nfrom keras.backend.tensorflow_backend import set_session\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nset_session(tf.Session(config=config))\n\n\"\"\"functions\"\"\"\n\nRUN_CNN_TRAIN_TEST_VALIDATION = 0\nRUN_CNN_TRAIN_TEST = 1\nRUN_CNN_PREDICT = 2\n\n\ndef fLoadData(conten):\n # prepared in matlab\n print('Loading data')\n for sVarname in ['X_train', 'X_test', 'y_train', 'y_test']:\n if sVarname in conten:\n exec(sVarname + '=conten[sVarname]')\n else:\n exec(sVarname + '= None')\n\n pIdx = np.random.permutation(np.arange(len(X_train)))\n X_train = X_train[pIdx]\n y_train = y_train[pIdx]\n y_train = np.asarray([y_train[:, 0], np.abs(np.asarray(y_train[:, 0], dtype=np.float32) - 1)]).T\n y_test = np.asarray([y_test[:, 0], np.abs(np.asarray(y_test[:, 0], dtype=np.float32) - 1)]).T\n return X_train, y_train, X_test, y_test\n\n\ndef fRemove_entries(entries, the_dict):\n for key in entries:\n if key in the_dict:\n del the_dict[key]\n\n\ndef fLoadMat(sInPath):\n \"\"\"Data\"\"\"\n if os.path.isfile(sInPath):\n try:\n conten = sio.loadmat(sInPath)\n except:\n f = h5py.File(sInPath, 'r')\n conten = {}\n conten['X_train'] = np.transpose(np.array(f['X_train']), (3, 2, 0, 1))\n conten['X_test'] = np.transpose(np.array(f['X_test']), (3, 2, 0, 1))\n conten['y_train'] = np.transpose(np.array(f['y_train']))\n conten['y_test'] = np.transpose(np.array(f['y_test']))\n conten['patchSize'] = np.transpose(np.array(f['patchSize']))\n else:\n sys.exit('Input file is not existing')\n X_train, y_train, X_test, y_test = fLoadData(conten) # output order needed for hyperas\n\n fRemove_entries(('X_train', 'X_test', 'y_train', 'y_test'), conten)\n dData = {'X_train': X_train, 'X_test': X_test, 'y_train': y_train, 'y_test': y_test}\n dOut = dData.copy()\n dOut.update(conten)\n return dOut # output dictionary (similar to conten, but with reshaped X_train, ...)\n\n\ndef fLoadDataForOptim(sInPath):\n if os.path.isfile(sInPath):\n conten = sio.loadmat(sInPath)\n X_train, y_train, X_test, y_test = fLoadData(conten) # output order needed for hyperas\n return X_train, y_train, X_test, y_test, conten[\"patchSize\"]\n\n\n# def fLoadAddData(sInPath): # deprecated\n# if os.path.isfile(sInPath):\n# conten = sio.loadmat(sInPath)\n# else:\n# sys.exit('Input file is not existing')\n# for sVarname in conten:\n# if not any(x in sVarname for x in ['X_train', 'X_test', 'y_train', 'y_test'] ):\n# conten[sVarname]\n\ndef fRunCNN(dData, sModelIn, lTrain, sParaOptim, sOutPath, iBatchSize, iLearningRate, iEpochs, dlart_handle=None,\n usingSegmentationMasks=False):\n \"\"\"CNN Models\"\"\"\n # check model\n sModel = sModelIn\n\n # dynamic loading of corresponding model\n cnnModel = __import__(sModel, globals(), locals(), ['createModel', 'fTrain', 'fPredict', 'load_best_model'],\n 0) # dynamic module loading with specified functions and with absolute importing (level=0) -> work in both Python2 and Python3\n\n # train (w/ or w/o optimization) and predicting\n if lTrain == RUN_CNN_TRAIN_TEST: # training\n if sParaOptim == 'hyperas': # hyperas parameter optimization\n best_run, best_model = optim.minimize(model=cnnModel.fHyperasTrain,\n data=fLoadDataForOptim(args.inPath[0]),\n algo=tpe.suggest,\n max_evals=5,\n trials=Trials())\n X_train, y_train, X_test, y_test, patchSize = fLoadDataForOptim(args.inPath[0])\n score_test, acc_test = best_model.evaluate(X_test, y_test)\n prob_test = best_model.predict(X_test, best_run['batch_size'], 0)\n\n _, sPath = os.path.splitdrive(sOutPath)\n sPath, sFilename = os.path.split(sPath)\n sFilename, sExt = os.path.splitext(sFilename)\n model_name = sPath + '/' + sFilename + str(patchSize[0, 0]) + str(patchSize[0, 1]) + '_best'\n weight_name = model_name + '_weights.h5'\n model_json = model_name + '.json'\n model_all = model_name + '_model.h5'\n json_string = best_model.to_json()\n open(model_json, 'w').write(json_string)\n # wei = best_model.get_weights()\n best_model.save_weights(weight_name)\n best_model.save(model_all)\n\n result = best_run['result']\n # acc = result.history['acc']y,\n loss = result.history['loss']\n val_acc = result.history['val_acc']\n val_loss = result.history['val_loss']\n sio.savemat(model_name, {'model_settings': model_json,\n 'model': model_all,\n 'weights': weight_name,\n 'acc': -best_run['loss'],\n 'loss': loss,\n 'val_acc': val_acc,\n 'val_loss': val_loss,\n 'score_test': score_test,\n 'acc_test': acc_test,\n 'prob_test': prob_test})\n\n elif sParaOptim == 'grid': # grid search << backward compatibility\n cnnModel.fTrain(X_traind=dData['X_train'],\n y_traind=dData['y_train'],\n X_test=dData['X_test'],\n y_test=dData['y_test'],\n sOutPath=sOutPath,\n patchSize=dData['patchSize'],\n batchSizes=iBatchSize,\n learningRates=iLearningRate,\n iEpochs=iEpochs,\n dlart_handle=dlart_handle)\n\n\n else: # no optimization or grid search (if batchSize|learningRate are arrays)\n if not usingSegmentationMasks:\n cnnModel.fTrain(X_train=dData['X_train'],\n y_train=dData['y_train'],\n X_test=dData['X_test'],\n y_test=dData['y_test'],\n sOutPath=sOutPath,\n patchSize=dData['patchSize'],\n batchSizes=iBatchSize,\n learningRates=iLearningRate,\n iEpochs=iEpochs,\n dlart_handle=dlart_handle)\n else:\n cnnModel.fTrain(X_train=dData['X_train'],\n y_train=dData['y_train'],\n Y_segMasks_train=dData['Y_segMasks_train'],\n X_test=dData['X_test'],\n y_test=dData['y_test'],\n Y_segMasks_test=dData['Y_segMasks_test'],\n sOutPath=sOutPath,\n patchSize=dData['patchSize'],\n batchSizes=iBatchSize,\n learningRates=iLearningRate,\n iEpochs=iEpochs,\n dlart_handle=dlart_handle)\n\n\n elif lTrain == RUN_CNN_TRAIN_TEST_VALIDATION:\n if sParaOptim == 'hyperas': # hyperas parameter optimization\n best_run, best_model = optim.minimize(model=cnnModel.fHyperasTrain,\n data=fLoadDataForOptim(args.inPath[0]),\n algo=tpe.suggest,\n max_evals=5,\n trials=Trials())\n X_train, y_train, X_test, y_test, patchSize = fLoadDataForOptim(args.inPath[0])\n score_test, acc_test = best_model.evaluate(X_test, y_test)\n prob_test = best_model.predict(X_test, best_run['batch_size'], 0)\n\n _, sPath = os.path.splitdrive(sOutPath)\n sPath, sFilename = os.path.split(sPath)\n sFilename, sExt = os.path.splitext(sFilename)\n model_name = sPath + '/' + sFilename + str(patchSize[0, 0]) + str(patchSize[0, 1]) + '_best'\n weight_name = model_name + '_weights.h5'\n model_json = model_name + '.json'\n model_all = model_name + '_model.h5'\n json_string = best_model.to_json()\n open(model_json, 'w').write(json_string)\n # wei = best_model.get_weights()\n best_model.save_weights(weight_name)\n best_model.save(model_all)\n\n result = best_run['result']\n # acc = result.history['acc']\n loss = result.history['loss']\n val_acc = result.history['val_acc']\n val_loss = result.history['val_loss']\n sio.savemat(model_name, {'model_settings': model_json,\n 'model': model_all,\n 'weights': weight_name,\n 'acc': -best_run['loss'],\n 'loss': loss,\n 'val_acc': val_acc,\n 'val_loss': val_loss,\n 'score_test': score_test,\n 'acc_test': acc_test,\n 'prob_test': prob_test})\n\n elif sParaOptim == 'grid': # grid search << backward compatibility\n cnnModel.fTrain(X_traind=dData['X_train'],\n y_traind=dData['y_train'],\n X_valid=dData['X_valid'],\n y_valid=dData['y_valid'],\n X_test=dData['X_test'],\n y_test=dData['y_test'],\n sOutPath=sOutPath,\n patchSize=dData['patchSize'],\n batchSizes=iBatchSize,\n learningRates=iLearningRate,\n iEpochs=iEpochs,\n dlart_handle=dlart_handle)\n\n else: # no optimization or grid search (if batchSize|learningRate are arrays)\n if not usingSegmentationMasks:\n cnnModel.fTrain(X_train=dData['X_train'],\n y_train=dData['y_train'],\n X_valid=dData['X_valid'],\n y_valid=dData['y_valid'],\n X_test=dData['X_test'],\n y_test=dData['y_test'],\n sOutPath=sOutPath,\n patchSize=dData['patchSize'],\n batchSizes=iBatchSize,\n learningRates=iLearningRate,\n iEpochs=iEpochs,\n dlart_handle=dlart_handle)\n else:\n cnnModel.fTrain(X_train=dData['X_train'],\n y_train=dData['y_train'],\n Y_segMasks_train=dData['Y_segMasks_train'],\n X_valid=dData['X_valid'],\n y_valid=dData['y_valid'],\n Y_segMasks_valid=dData['Y_segMasks_validation'],\n X_test=dData['X_test'],\n y_test=dData['y_test'],\n Y_segMasks_test=dData['Y_segMasks_test'],\n sOutPath=sOutPath,\n patchSize=dData['patchSize'],\n batchSizes=iBatchSize,\n learningRates=iLearningRate,\n iEpochs=iEpochs,\n dlart_handle=dlart_handle)\n\n elif lTrain == RUN_CNN_PREDICT: # predicting\n cnnModel.fPredict(dData['X_test'], dData['y_test'], dData['model_name'], sOutPath, dData['patchSize'],\n iBatchSize[0])\n\n _, sPath = os.path.splitdrive(sOutPath)\n sPath, sFilename = os.path.split(sPath)\n sFilename, sExt = os.path.splitext(sFilename)\n\n model_name = sOutPath + os.sep + sFilename\n model_all = model_name + '_model.h5'\n try:\n model = load_model(model_all)\n except:\n try:\n def dice_coef(y_true, y_pred, epsilon=1e-5):\n dice_numerator = 2.0 * K.sum(y_true * y_pred, axis=[1, 2, 3, 4])\n dice_denominator = K.sum(K.square(y_true), axis=[1, 2, 3, 4]) + K.sum(K.square(y_pred),\n axis=[1, 2, 3, 4])\n\n dice_score = dice_numerator / (dice_denominator + epsilon)\n return K.mean(dice_score, axis=0)\n\n def dice_coef_loss(y_true, y_pred):\n return 1 - dice_coef(y_true, y_pred)\n\n model = load_model(model_all,\n custom_objects={'dice_coef_loss': dice_coef_loss, 'dice_coef': dice_coef})\n except:\n model = {}\n return model, model_all\n\n\n# Main Code\nif __name__ == \"__main__\": # for command line call\n # input parsing\n # ADD new options here!\n parser = argparse.ArgumentParser(description='''CNN artifact detection''',\n epilog='''(c) Thomas Kuestner, [email protected]''')\n parser.add_argument('-i', '--inPath', nargs=1, type=str, help='input path to *.mat of stored patches',\n default=CNN_PATH + os.sep + 'Datatmp/in.mat')\n parser.add_argument('-o', '--outPath', nargs=1, type=str,\n help='output path to the file used for storage (subfiles _model, _weights, ... are automatically generated)',\n default=CNN_PATH + os.sep + 'Datatmp/out')\n parser.add_argument('-m', '--model', nargs=1, type=str,\n choices=['motion_head_CNN2D', 'motion_abd_CNN2D', 'motion_all_CNN2D', 'motion_CNN3D',\n 'motion_MNetArt', 'motion_VNetArt', 'multi_DenseResNet', 'multi_InceptionNet'],\n help='select CNN model', default='motion_2DCNN_head')\n parser.add_argument('-t', '--train', dest='train', action='store_true',\n help='if set -> training | if not set -> prediction')\n parser.add_argument('-p', '--paraOptim', dest='paraOptim', type=str, choices=['grid', 'hyperas', 'none'],\n help='parameter optimization via grid search, hyper optimization or no optimization',\n default='none')\n parser.add_argument('-b', '--batchSize', nargs='*', dest='batchSize', type=int, help='batchSize', default=64)\n parser.add_argument('-l', '--learningRates', nargs='*', dest='learningRate', type=int, help='learningRate',\n default=0.0001)\n parser.add_argument('-e', '--epochs', nargs=1, dest='epochs', type=int, help='epochs', default=300)\n\n args = parser.parse_args()\n\n if os.path.isfile(args.outPath[0]):\n print('Warning! Output file is already existing and will be overwritten')\n\n # load input data\n dData = fLoadMat(args.inPath[0])\n # save path for keras model\n if 'outPath' in dData:\n sOutPath = dData['outPath']\n else:\n sOutPath = args.outPath[0]\n\n fRunCNN(dData, args.model[0], args.train, args.paraOptim, sOutPath, args.batchSize, args.learningRate,\n args.epochs[0])\n",
"import os\r\n# os.environ[\"CUDA_DEVICE_ORDER\"]=\"0000:02:00.0\"\r\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\r\n\r\nfrom tensorflow.python.client import device_lib\r\n\r\nprint(device_lib.list_local_devices)\r\n\r\nimport os.path\r\nimport scipy.io as sio\r\nimport numpy as np\r\nimport math\r\nimport keras\r\nfrom keras.layers import Input\r\nimport keras.backend as K\r\nfrom keras.layers import Conv2D\r\nfrom keras.layers import BatchNormalization\r\nfrom keras.layers import GlobalAveragePooling2D\r\nfrom keras.layers.core import Dense, Activation, Flatten\r\nfrom keras.models import Model\r\nfrom keras.models import Sequential\r\nfrom keras.layers.convolutional import Convolution2D\r\nfrom keras.callbacks import EarlyStopping\r\nfrom keras.callbacks import LearningRateScheduler\r\nfrom keras.callbacks import ReduceLROnPlateau\r\nfrom keras.callbacks import ModelCheckpoint\r\nfrom keras.models import model_from_json\r\nfrom keras.regularizers import l2 # , activity_l2\r\nfrom keras import backend as K\r\nfrom keras.optimizers import SGD\r\nfrom networks.multiclass.SENets.deep_residual_learning_blocks import *\r\nfrom DLart.Constants_DLart import *\r\nfrom utils.image_preprocessing import ImageDataGenerator\r\nfrom utils.LivePlotCallback import LivePlotCallback\r\nfrom matplotlib import pyplot as plt\r\n\r\nfrom networks.multiclass.SENets.densely_connected_cnn_blocks import *\r\n\r\n\r\ndef createModel(patchSize, numClasses):\r\n if K.image_data_format() == 'channels_last':\r\n bn_axis = -1\r\n else:\r\n bn_axis = 1\r\n\r\n growthRate_k = 12\r\n compressionFactor = 1.0\r\n\r\n input_tensor = Input(shape=(patchSize[0], patchSize[1], 1))\r\n\r\n # first conv layer\r\n x = Conv2D(16, (3, 3), strides=(1, 1), padding='same', kernel_initializer='he_normal')(input_tensor)\r\n\r\n # 1. Dense Block\r\n x, numFilters = dense_block(x, numInputFilters=16, numLayers=10, growthRate_k=growthRate_k,\r\n bottleneck_enabled=False)\r\n\r\n # Transition Layer\r\n x, numFilters = transition_SE_layer(x, numFilters, compressionFactor=compressionFactor, se_ratio=16)\r\n\r\n # 2. Dense Block\r\n x, numFilters = dense_block(x, numInputFilters=numFilters, numLayers=10, growthRate_k=growthRate_k,\r\n bottleneck_enabled=False)\r\n\r\n # Transition Layer\r\n x, numFilters = transition_SE_layer(x, numFilters, compressionFactor=compressionFactor, se_ratio=16)\r\n\r\n # 3. Dense Block\r\n x, numFilters = dense_block(x, numInputFilters=numFilters, numLayers=10, growthRate_k=growthRate_k,\r\n bottleneck_enabled=False)\r\n\r\n # SE Block\r\n x = squeeze_excitation_block(x, ratio=16)\r\n\r\n x = BatchNormalization(axis=bn_axis)(x)\r\n x = Activation('relu')(x)\r\n\r\n # global average pooling\r\n x = GlobalAveragePooling2D(data_format='channels_last')(x)\r\n\r\n # fully-connected layer\r\n output = Dense(units=numClasses,\r\n activation='softmax',\r\n kernel_initializer='he_normal',\r\n name='fully-connected')(x)\r\n\r\n # create model\r\n cnn = Model(input_tensor, output, name='SE-DenseNet-34')\r\n sModelName = 'SE-DenseNet-34'\r\n\r\n return cnn, sModelName\r\n\r\n\r\ndef fTrain(X_train=None, y_train=None, X_valid=None, y_valid=None, X_test=None, y_test=None, sOutPath=None, patchSize=0,\r\n batchSizes=None, learningRates=None, iEpochs=None, dlart_handle=None):\r\n # grid search on batch_sizes and learning rates\r\n # parse inputs\r\n batchSize = batchSizes[0]\r\n learningRate = learningRates[0]\r\n\r\n # change the shape of the dataset -> at color channel -> here one for grey scale\r\n X_train = np.expand_dims(X_train, axis=-1)\r\n X_test = np.expand_dims(X_test, axis=-1)\r\n\r\n if X_valid is not None and y_valid is not None:\r\n X_valid = np.expand_dims(X_valid, axis=-1)\r\n\r\n # y_train = np.asarray([y_train[:], np.abs(np.asarray(y_train[:], dtype=np.float32) - 1)]).T\r\n # y_test = np.asarray([y_test[:], np.abs(np.asarray(y_test[:], dtype=np.float32) - 1)]).T\r\n\r\n # number of classes\r\n numClasses = np.shape(y_train)[-1]\r\n\r\n # create cnn model\r\n cnn, sModelName = createModel(patchSize=patchSize, numClasses=numClasses)\r\n\r\n fTrainInner(cnn,\r\n sModelName,\r\n X_train=X_train,\r\n y_train=y_train,\r\n X_valid=X_valid,\r\n y_valid=y_valid,\r\n X_test=X_test,\r\n y_test=y_test,\r\n sOutPath=sOutPath,\r\n patchSize=patchSize,\r\n batchSize=batchSize,\r\n learningRate=learningRate,\r\n iEpochs=iEpochs,\r\n dlart_handle=dlart_handle)\r\n\r\n K.clear_session()\r\n\r\n # for iBatch in batchSizes:\r\n # for iLearn in learningRates:\r\n # fTrainInner(cnn,\r\n # sModelName,\r\n # X_train=X_train,\r\n # y_train=y_train,\r\n # X_valid=X_valid,\r\n # y_valid=y_valid,\r\n # X_test=X_test,\r\n # y_test=y_test,\r\n # sOutPath=sOutPath,\r\n # patchSize=patchSize,\r\n # batchSize=iBatch,\r\n # learningRate=iLearn,\r\n # iEpochs=iEpochs,\r\n # dlart_handle=dlart_handle)\r\n\r\n\r\ndef fTrainInner(cnn, modelName, X_train=None, y_train=None, X_valid=None, y_valid=None, X_test=None, y_test=None,\r\n sOutPath=None, patchSize=0, batchSize=None, learningRate=None, iEpochs=None, dlart_handle=None):\r\n print('Training CNN')\r\n print('with lr = ' + str(learningRate) + ' , batchSize = ' + str(batchSize))\r\n\r\n # save names\r\n _, sPath = os.path.splitdrive(sOutPath)\r\n sPath, sFilename = os.path.split(sPath)\r\n sFilename, sExt = os.path.splitext(sFilename)\r\n\r\n model_name = sOutPath + os.sep + sFilename + '_lr_' + str(learningRate) + '_bs_' + str(batchSize)\r\n weight_name = model_name + '_weights.h5'\r\n model_json = model_name + '.json'\r\n model_all = model_name + '_model.h5'\r\n model_mat = model_name + '.mat'\r\n\r\n if (os.path.isfile(model_mat)): # no training if output file exists\r\n print('------- already trained -> go to next')\r\n return\r\n\r\n # create optimizer\r\n if dlart_handle != None:\r\n if dlart_handle.getOptimizer() == SGD_OPTIMIZER:\r\n opti = keras.optimizers.SGD(lr=learningRate,\r\n momentum=dlart_handle.getMomentum(),\r\n decay=dlart_handle.getWeightDecay(),\r\n nesterov=dlart_handle.getNesterovEnabled())\r\n elif dlart_handle.getOptimizer() == RMS_PROP_OPTIMIZER:\r\n opti = keras.optimizers.RMSprop(lr=learningRate, decay=dlart_handle.getWeightDecay())\r\n elif dlart_handle.getOptimizer() == ADAGRAD_OPTIMIZER:\r\n opti = keras.optimizers.Adagrad(lr=learningRate, epsilon=None, decay=dlart_handle.getWeightDecay())\r\n elif dlart_handle.getOptimizer() == ADADELTA_OPTIMIZER:\r\n opti = keras.optimizers.Adadelta(lr=learningRate, rho=0.95, epsilon=None,\r\n decay=dlart_handle.getWeightDecay())\r\n elif dlart_handle.getOptimizer() == ADAM_OPTIMIZER:\r\n opti = keras.optimizers.Adam(lr=learningRate, beta_1=0.9, beta_2=0.999, epsilon=None,\r\n decay=dlart_handle.getWeightDecay())\r\n else:\r\n raise ValueError(\"Unknown Optimizer!\")\r\n else:\r\n # opti = SGD(lr=learningRate, momentum=1e-8, decay=0.1, nesterov=True);#Adag(lr=0.01, epsilon=1e-06)\r\n opti = keras.optimizers.Adam(lr=learningRate, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\r\n\r\n cnn.summary()\r\n\r\n # compile model\r\n cnn.compile(loss='categorical_crossentropy', optimizer=opti, metrics=['accuracy'])\r\n\r\n # callbacks\r\n callback_earlyStopping = EarlyStopping(monitor='val_loss', patience=25, verbose=1)\r\n # callback_tensorBoard = keras.callbacks.TensorBoard(log_dir=dlart_handle.getLearningOutputPath() + '/logs',\r\n # histogram_freq=2,\r\n # batch_size=batchSize,\r\n # write_graph=True,\r\n # write_grads=True,\r\n # write_images=True,\r\n # embeddings_freq=0,\r\n # embeddings_layer_names=None,\r\n # embeddings_metadata=None)\r\n\r\n callbacks = [callback_earlyStopping]\r\n callbacks.append(\r\n ModelCheckpoint(sOutPath + os.sep + 'checkpoints/checker.hdf5', monitor='val_acc', verbose=0, period=5,\r\n save_best_only=True)) # overrides the last checkpoint, its just for security\r\n # callbacks.append(ReduceLROnPlateau(monitor='loss', factor=0.1, patience=5, min_lr=1e-4, verbose=1))\r\n callbacks.append(LearningRateScheduler(schedule=step_decay, verbose=1))\r\n callbacks.append(LivePlotCallback(dlart_handle))\r\n\r\n # data augmentation\r\n if dlart_handle.getDataAugmentationEnabled() == True:\r\n # Initialize Image Generator\r\n # all shifted and rotated images are filled with zero padded pixels\r\n datagen = ImageDataGenerator(\r\n featurewise_center=False,\r\n samplewise_center=False,\r\n featurewise_std_normalization=False,\r\n samplewise_std_normalization=False,\r\n zca_whitening=dlart_handle.getZCA_Whitening(),\r\n zca_epsilon=1e-6,\r\n rotation_range=dlart_handle.getRotation(),\r\n width_shift_range=dlart_handle.getWidthShift(),\r\n height_shift_range=dlart_handle.getHeightShift(),\r\n shear_range=0.,\r\n zoom_range=dlart_handle.getZoom(),\r\n channel_shift_range=0.,\r\n fill_mode='constant',\r\n cval=0.,\r\n horizontal_flip=dlart_handle.getHorizontalFlip(),\r\n vertical_flip=dlart_handle.getVerticalFlip(),\r\n rescale=None,\r\n histogram_equalization=dlart_handle.getHistogramEqualization(),\r\n contrast_stretching=dlart_handle.getContrastStretching(),\r\n adaptive_equalization=dlart_handle.getAdaptiveEqualization(),\r\n preprocessing_function=None,\r\n data_format=K.image_data_format()\r\n )\r\n\r\n datagen_val = ImageDataGenerator(featurewise_center=False,\r\n samplewise_center=False,\r\n featurewise_std_normalization=False,\r\n samplewise_std_normalization=False,\r\n zca_whitening=dlart_handle.getZCA_Whitening(),\r\n zca_epsilon=1e-6,\r\n rotation_range=0.,\r\n width_shift_range=0.,\r\n height_shift_range=0.,\r\n shear_range=0.,\r\n zoom_range=0.,\r\n channel_shift_range=0.,\r\n fill_mode='constant',\r\n cval=0.,\r\n horizontal_flip=False,\r\n vertical_flip=False,\r\n rescale=None,\r\n histogram_equalization=dlart_handle.getHistogramEqualization(),\r\n contrast_stretching=dlart_handle.getContrastStretching(),\r\n adaptive_equalization=dlart_handle.getAdaptiveEqualization(),\r\n preprocessing_function=None,\r\n data_format=K.image_data_format())\r\n\r\n datagen_test = ImageDataGenerator(featurewise_center=False,\r\n samplewise_center=False,\r\n featurewise_std_normalization=False,\r\n samplewise_std_normalization=False,\r\n zca_whitening=dlart_handle.getZCA_Whitening(),\r\n zca_epsilon=1e-6,\r\n rotation_range=0.,\r\n width_shift_range=0.,\r\n height_shift_range=0.,\r\n shear_range=0.,\r\n zoom_range=0.,\r\n channel_shift_range=0.,\r\n fill_mode='constant',\r\n cval=0.,\r\n horizontal_flip=False,\r\n vertical_flip=False,\r\n rescale=None,\r\n histogram_equalization=dlart_handle.getHistogramEqualization(),\r\n contrast_stretching=dlart_handle.getContrastStretching(),\r\n adaptive_equalization=dlart_handle.getAdaptiveEqualization(),\r\n preprocessing_function=None,\r\n data_format=K.image_data_format())\r\n\r\n # fit parameters from dataset\r\n datagen.fit(X_train)\r\n datagen_test.fit(X_test)\r\n\r\n # configure batch size and get one batch of images\r\n for x_batch, y_batch in datagen.flow(X_train, y_train, batch_size=9):\r\n # display first 9 images\r\n for i in range(0, 9):\r\n plt.subplot(330 + 1 + i)\r\n plt.imshow(x_batch[i].reshape(x_batch.shape[1], x_batch.shape[2]), cmap='gray')\r\n plt.show()\r\n break\r\n\r\n if X_valid is not None and y_valid is not None:\r\n # fit model on data\r\n # use validation/test split\r\n datagen_val.fit(X_valid)\r\n result = cnn.fit_generator(datagen.flow(X_train, y_train, batch_size=batchSize),\r\n steps_per_epoch=X_train.shape[0] // batchSize,\r\n epochs=iEpochs,\r\n validation_data=datagen_val.flow(X_valid, y_valid, batch_size=batchSize),\r\n callbacks=callbacks,\r\n workers=1,\r\n use_multiprocessing=False)\r\n\r\n else:\r\n # fit model on data\r\n # use test data for validation and test\r\n\r\n result = cnn.fit_generator(datagen.flow(X_train, y_train, batch_size=batchSize),\r\n steps_per_epoch=X_train.shape[0] // batchSize,\r\n epochs=iEpochs,\r\n validation_data=datagen_test.flow(X_test, y_test, batch_size=batchSize),\r\n callbacks=callbacks,\r\n workers=1,\r\n use_multiprocessing=False)\r\n\r\n # return the loss value and metrics values for the model in test mode\r\n score_test, acc_test = cnn.evaluate_generator(datagen_test.flow(X_test, y_test, batch_size=batchSize),\r\n steps=None,\r\n max_queue_size=10,\r\n workers=1,\r\n use_multiprocessing=False)\r\n\r\n prob_test = cnn.predict_generator(datagen_test.flow(X_test, y_test, batch_size=batchSize),\r\n steps=None,\r\n max_queue_size=10,\r\n workers=1,\r\n use_multiprocessing=False,\r\n verbose=1)\r\n\r\n else:\r\n if X_valid is not None and y_valid is not None:\r\n # use validation/test split\r\n result = cnn.fit(X_train,\r\n y_train,\r\n validation_data=(X_valid, y_valid),\r\n epochs=iEpochs,\r\n batch_size=batchSize,\r\n callbacks=callbacks,\r\n verbose=1)\r\n else:\r\n # use test set for validation and test\r\n result = cnn.fit(X_train,\r\n y_train,\r\n validation_data=(X_test, y_test),\r\n epochs=iEpochs,\r\n batch_size=batchSize,\r\n callbacks=callbacks,\r\n verbose=1)\r\n\r\n # return the loss value and metrics values for the model in test mode\r\n score_test, acc_test = cnn.evaluate(X_test, y_test, batch_size=batchSize, verbose=1)\r\n\r\n prob_test = cnn.predict(X_test, batchSize, 0)\r\n\r\n # save model\r\n json_string = cnn.to_json()\r\n with open(model_json, 'w') as jsonFile:\r\n jsonFile.write(json_string)\r\n\r\n # wei = cnn.get_weights()\r\n cnn.save_weights(weight_name, overwrite=True)\r\n cnn.save(model_all) # keras > v0.7\r\n model_png_dir = sOutPath + os.sep + \"model.png\"\r\n from keras.utils import plot_model\r\n plot_model(cnn, to_file=model_png_dir, show_shapes=True, show_layer_names=True)\r\n\r\n # matlab\r\n acc = result.history['acc']\r\n loss = result.history['loss']\r\n val_acc = result.history['val_acc']\r\n val_loss = result.history['val_loss']\r\n\r\n print('Saving results: ' + model_name)\r\n sio.savemat(model_name, {'model_settings': model_json,\r\n 'model': model_all,\r\n 'weights': weight_name,\r\n 'acc': acc,\r\n 'loss': loss,\r\n 'val_acc': val_acc,\r\n 'val_loss': val_loss,\r\n 'score_test': score_test,\r\n 'acc_test': acc_test,\r\n 'prob_test': prob_test})\r\n\r\n\r\ndef step_decay(epoch, lr):\r\n drop = 0.1\r\n epochs_drop = 10.0\r\n print(\"Current Learning Rate: \" + str(lr))\r\n if epoch == epochs_drop or epoch == 2 * epochs_drop or epoch == 3 * epochs_drop or epoch == 4 * epochs_drop:\r\n lr = drop * lr\r\n print(\"Reduce Learningrate by 0.1 to \" + str(lr))\r\n\r\n return lr\r\n\r\n\r\ndef fPredict(X, y, sModelPath, sOutPath, batchSize=64):\r\n \"\"\"Takes an already trained model and computes the loss and Accuracy over the samples X with their Labels y\r\n Input:\r\n X: Samples to predict on. The shape of X should fit to the input shape of the model\r\n y: Labels for the Samples. Number of Samples should be equal to the number of samples in X\r\n sModelPath: (String) full path to a trained keras model. It should be *_json.txt file. there has to be a corresponding *_weights.h5 file in the same directory!\r\n sOutPath: (String) full path for the Output. It is a *.mat file with the computed loss and accuracy stored.\r\n The Output file has the Path 'sOutPath'+ the filename of sModelPath without the '_json.txt' added the suffix '_pred.mat'\r\n batchSize: Batchsize, number of samples that are processed at once\"\"\"\r\n sModelPath = sModelPath.replace(\"_json.txt\", \"\")\r\n weight_name = sModelPath + '_weights.h5'\r\n model_json = sModelPath + '_json.txt'\r\n model_all = sModelPath + '_model.h5'\r\n\r\n # load weights and model (new way)\r\n model_json = open(model_json, 'r')\r\n model_string = model_json.read()\r\n model_json.close()\r\n model = model_from_json(model_string)\r\n\r\n model.compile(loss='categorical_crossentropy', optimizer=keras.optimizers.Adam(), metrics=['accuracy'])\r\n model.load_weights(weight_name)\r\n\r\n score_test, acc_test = model.evaluate(X, y, batch_size=batchSize)\r\n print('loss' + str(score_test) + ' acc:' + str(acc_test))\r\n prob_pre = model.predict(X, batch_size=batchSize, verbose=1)\r\n print(prob_pre[0:14, :])\r\n _, sModelFileSave = os.path.split(sModelPath)\r\n\r\n modelSave = sOutPath + sModelFileSave + '_pred.mat'\r\n print('saving Model:{}'.format(modelSave))\r\n sio.savemat(modelSave, {'prob_pre': prob_pre, 'score_test': score_test, 'acc_test': acc_test})\r\n\r\n\r\n###############################################################################\r\n## OPTIMIZATIONS ##\r\n###############################################################################\r\ndef fHyperasTrain(X_train, Y_train, X_test, Y_test, patchSize):\r\n # explicitly stated here instead of cnn = createModel() to allow optimization\r\n cnn = Sequential()\r\n # cnn.add(Convolution2D(32,\r\n # 14,\r\n # 14,\r\n # init='normal',\r\n # # activation='sigmoid',\r\n # weights=None,\r\n # border_mode='valid',\r\n # subsample=(1, 1),\r\n # W_regularizer=l2(1e-6),\r\n # input_shape=(1, patchSize[0,0], patchSize[0,1])))\r\n # cnn.add(Activation('relu'))\r\n\r\n cnn.add(Convolution2D(32, # 64\r\n 7,\r\n 7,\r\n init='normal',\r\n # activation='sigmoid',\r\n weights=None,\r\n border_mode='valid',\r\n subsample=(1, 1),\r\n W_regularizer=l2(1e-6)))\r\n cnn.add(Activation('relu'))\r\n cnn.add(Convolution2D(64, # learning rate: 0.1 -> 76%\r\n 3,\r\n 3,\r\n init='normal',\r\n # activation='sigmoid',\r\n weights=None,\r\n border_mode='valid',\r\n subsample=(1, 1),\r\n W_regularizer=l2(1e-6)))\r\n cnn.add(Activation('relu'))\r\n\r\n cnn.add(Convolution2D(128, # learning rate: 0.1 -> 76%\r\n 3,\r\n 3,\r\n init='normal',\r\n # activation='sigmoid',\r\n weights=None,\r\n border_mode='valid',\r\n subsample=(1, 1),\r\n W_regularizer=l2(1e-6)))\r\n cnn.add(Activation('relu'))\r\n\r\n # cnn.add(pool2(pool_size=(2, 2), strides=None, border_mode='valid', dim_ordering='th'))\r\n\r\n cnn.add(Flatten())\r\n # cnn.add(Dense(input_dim= 100,\r\n # output_dim= 100,\r\n # init = 'normal',\r\n # #activation = 'sigmoid',\r\n # W_regularizer='l2'))\r\n # cnn.add(Activation('sigmoid'))\r\n cnn.add(Dense(input_dim=100,\r\n output_dim=2,\r\n init='normal',\r\n # activation = 'sigmoid',\r\n W_regularizer='l2'))\r\n cnn.add(Activation('softmax'))\r\n\r\n # opti = SGD(lr={{choice([0.1, 0.01, 0.05, 0.005, 0.001])}}, momentum=1e-8, decay=0.1, nesterov=True)\r\n # cnn.compile(loss='categorical_crossentropy', optimizer=opti)\r\n\r\n epochs = 300\r\n\r\n result = cnn.fit(X_train, Y_train,\r\n batch_size=128, # {{choice([64, 128])}}\r\n nb_epoch=epochs,\r\n show_accuracy=True,\r\n verbose=2,\r\n validation_data=(X_test, Y_test))\r\n score_test, acc_test = cnn.evaluate(X_test, Y_test, verbose=0)\r\n\r\n # return {'loss': -acc_test, 'status': STATUS_OK, 'model': cnn, 'trainresult': result, 'score_test': score_test}\r\n\r\n\r\n## helper functions\r\ndef drange(start, stop, step):\r\n r = start\r\n while r < stop:\r\n yield r\r\n r += step\r\n"
] | [
[
"numpy.lib.pad",
"numpy.multiply",
"tensorflow.Variable",
"tensorflow.slice",
"tensorflow.stack",
"numpy.dtype",
"numpy.round",
"tensorflow.math.multiply",
"numpy.concatenate",
"numpy.zeros"
],
[
"numpy.expand_dims",
"tensorflow.ConfigProto",
"matplotlib.pyplot.subplot",
"numpy.shape",
"tensorflow.Session",
"scipy.io.savemat",
"matplotlib.pyplot.show"
],
[
"tensorflow.to_int64",
"tensorflow.reduce_mean",
"tensorflow.shape",
"tensorflow.stack",
"tensorflow.cast",
"tensorflow.ones_like",
"tensorflow.square",
"tensorflow.sparse_reduce_sum",
"tensorflow.tile"
],
[
"numpy.asarray",
"scipy.io.loadmat",
"tensorflow.python.keras.models.load_model",
"tensorflow.ConfigProto",
"tensorflow.Session",
"scipy.io.savemat",
"numpy.array"
],
[
"numpy.expand_dims",
"matplotlib.pyplot.subplot",
"numpy.shape",
"scipy.io.savemat",
"matplotlib.pyplot.show"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
Zshan0/Cirq | [
"610b0d4ea3a7862169610797266734c844ddcc1f",
"93bbaa853305faa65117bcbdc2063f741cb2977c",
"610b0d4ea3a7862169610797266734c844ddcc1f"
] | [
"cirq-core/cirq/protocols/apply_unitary_protocol.py",
"cirq-google/cirq_google/optimizers/optimize_for_sycamore.py",
"cirq-core/cirq/sim/clifford/stabilizer_sampler_test.py"
] | [
"# Copyright 2018 The Cirq Developers\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# https://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\"\"\"A protocol for implementing high performance unitary left-multiplies.\"\"\"\n\nfrom typing import (\n Any,\n cast,\n Iterable,\n Optional,\n Sequence,\n Tuple,\n TYPE_CHECKING,\n TypeVar,\n Union,\n)\n\nimport numpy as np\nfrom typing_extensions import Protocol\n\nfrom cirq import linalg, qis\nfrom cirq._doc import doc_private\nfrom cirq.protocols import qid_shape_protocol\nfrom cirq.protocols.decompose_protocol import (\n _try_decompose_into_operations_and_qubits,\n)\nfrom cirq.type_workarounds import NotImplementedType\n\nif TYPE_CHECKING:\n import cirq\n\n# This is a special indicator value used by the apply_unitary method\n# to determine whether or not the caller provided a 'default' argument. It must\n# be of type np.ndarray to ensure the method has the correct type signature in\n# that case. It is checked for using `is`, so it won't have a false positive if\n# the user provides a different np.array([]) value.\n\nRaiseTypeErrorIfNotProvided: np.ndarray = np.array([])\n\nTDefault = TypeVar('TDefault')\n\n\nclass ApplyUnitaryArgs:\n \"\"\"Arguments for performing an efficient left-multiplication by a unitary.\n\n The receiving object is expected to mutate `target_tensor` so that it\n contains the state after multiplication, and then return `target_tensor`.\n Alternatively, if workspace is required, the receiving object can overwrite\n `available_buffer` with the results and return `available_buffer`. Or, if\n the receiving object is attempting to be simple instead of fast, it can\n create an entirely new array and return that.\n\n Attributes:\n target_tensor: The input tensor that needs to be left-multiplied by\n the unitary effect of the receiving object. The tensor will\n have the shape (2, 2, 2, ..., 2). It usually corresponds to\n a multi-qubit superposition, but it could also be a multi-qubit\n unitary transformation or some other concept.\n available_buffer: Pre-allocated workspace with the same shape and\n dtype as the target tensor.\n axes: Which axes the unitary effect is being applied to (e.g. the\n qubits that the gate is operating on).\n \"\"\"\n\n def __init__(\n self, target_tensor: np.ndarray, available_buffer: np.ndarray, axes: Iterable[int]\n ):\n \"\"\"Inits ApplyUnitaryArgs.\n\n Args:\n target_tensor: The input tensor that needs to be left-multiplied by\n the unitary effect of the receiving object. The tensor will\n have the shape (2, 2, 2, ..., 2). It usually corresponds to\n a multi-qubit superposition, but it could also be a multi-qubit\n unitary transformation or some other concept.\n available_buffer: Pre-allocated workspace with the same shape and\n dtype as the target tensor.\n axes: Which axes the unitary effect is being applied to (e.g. the\n qubits that the gate is operating on).\n\n \"\"\"\n self.target_tensor = target_tensor\n self.available_buffer = available_buffer\n self.axes = tuple(axes)\n\n @staticmethod\n def default(\n num_qubits: Optional[int] = None, *, qid_shape: Optional[Tuple[int, ...]] = None\n ) -> 'ApplyUnitaryArgs':\n \"\"\"A default instance starting in state |0⟩.\n\n Specify exactly one argument.\n\n Args:\n num_qubits: The number of qubits to make space for in the state.\n qid_shape: The shape of the state, specifying the dimension of each\n qid.\n\n Raises:\n TypeError: If exactly neither `num_qubits` or `qid_shape` is provided or\n both are provided.\n \"\"\"\n if (num_qubits is None) == (qid_shape is None):\n raise TypeError('Specify exactly one of num_qubits or qid_shape.')\n if num_qubits is not None:\n qid_shape = (2,) * num_qubits\n qid_shape = cast(Tuple[int, ...], qid_shape) # Satisfy mypy\n num_qubits = len(qid_shape)\n state = qis.one_hot(index=(0,) * num_qubits, shape=qid_shape, dtype=np.complex128)\n return ApplyUnitaryArgs(state, np.empty_like(state), range(num_qubits))\n\n def with_axes_transposed_to_start(self) -> 'ApplyUnitaryArgs':\n \"\"\"Returns a transposed view of the same arguments.\n\n Returns:\n A view over the same target tensor and available workspace, but\n with the numpy arrays transposed such that the axes field is\n guaranteed to equal `range(len(result.axes))`. This allows one to\n say e.g. `result.target_tensor[0, 1, 0, ...]` instead of\n `result.target_tensor[result.subspace_index(0b010)]`.\n \"\"\"\n axis_set = set(self.axes)\n other_axes = [axis for axis in range(len(self.target_tensor.shape)) if axis not in axis_set]\n perm = (*self.axes, *other_axes)\n target_tensor = self.target_tensor.transpose(*perm)\n available_buffer = self.available_buffer.transpose(*perm)\n return ApplyUnitaryArgs(target_tensor, available_buffer, range(len(self.axes)))\n\n def _for_operation_with_qid_shape(\n self, indices: Iterable[int], qid_shape: Tuple[int, ...]\n ) -> 'ApplyUnitaryArgs':\n \"\"\"Creates a sliced and transposed view of `self` appropriate for an\n operation with shape `qid_shape` on qubits with the given indices.\n\n Example:\n sub_args = args._for_operation_with_qid_shape(indices, (2, 2, 2))\n # Slice where the first qubit is |1>.\n sub_args.target_tensor[..., 1, :, :]\n\n Args:\n indices: Integer indices into `self.axes` specifying which qubits\n the operation applies to.\n qid_shape: The qid shape of the operation, the expected number of\n quantum levels in each qubit the operation applies to.\n\n Returns: A new `ApplyUnitaryArgs` where `sub_args.target_tensor` and\n `sub_args.available_buffer` are sliced and transposed views of\n `self.target_tensor` and `self.available_buffer` respectively.\n \"\"\"\n slices = [slice(0, size) for size in qid_shape]\n sub_axes = [self.axes[i] for i in indices]\n axis_set = set(sub_axes)\n other_axes = [axis for axis in range(len(self.target_tensor.shape)) if axis not in axis_set]\n ordered_axes = (*other_axes, *sub_axes)\n # Transpose sub_axes to the end of the shape and slice them\n target_tensor = self.target_tensor.transpose(*ordered_axes)[(..., *slices)]\n available_buffer = self.available_buffer.transpose(*ordered_axes)[(..., *slices)]\n new_axes = range(len(other_axes), len(ordered_axes))\n return ApplyUnitaryArgs(target_tensor, available_buffer, new_axes)\n\n def subspace_index(\n self, little_endian_bits_int: int = 0, *, big_endian_bits_int: int = 0\n ) -> Tuple[Union[slice, int, 'ellipsis'], ...]:\n \"\"\"An index for the subspace where the target axes equal a value.\n\n Args:\n little_endian_bits_int: The desired value of the qubits at the\n targeted `axes`, packed into an integer. The least significant\n bit of the integer is the desired bit for the first axis, and\n so forth in increasing order. Can't be specified at the same\n time as `big_endian_bits_int`.\n big_endian_bits_int: The desired value of the qubits at the\n targeted `axes`, packed into an integer. The most significant\n bit of the integer is the desired bit for the first axis, and\n so forth in decreasing order. Can't be specified at the same\n time as `little_endian_bits_int`.\n\n Returns:\n A value that can be used to index into `target_tensor` and\n `available_buffer`, and manipulate only the part of Hilbert space\n corresponding to a given bit assignment.\n\n Example:\n If `target_tensor` is a 4 qubit tensor and `axes` is `[1, 3]` and\n then this method will return the following when given\n `little_endian_bits=0b01`:\n\n `(slice(None), 0, slice(None), 1, Ellipsis)`\n\n Therefore the following two lines would be equivalent:\n\n args.target_tensor[args.subspace_index(0b01)] += 1\n\n args.target_tensor[:, 0, :, 1] += 1\n \"\"\"\n return linalg.slice_for_qubits_equal_to(\n self.axes,\n little_endian_qureg_value=little_endian_bits_int,\n big_endian_qureg_value=big_endian_bits_int,\n qid_shape=self.target_tensor.shape,\n )\n\n\nclass SupportsConsistentApplyUnitary(Protocol):\n \"\"\"An object that can be efficiently left-multiplied into tensors.\"\"\"\n\n @doc_private\n def _apply_unitary_(\n self, args: ApplyUnitaryArgs\n ) -> Union[np.ndarray, None, NotImplementedType]:\n \"\"\"Left-multiplies a unitary effect onto a tensor with good performance.\n\n This method is given both the target tensor and workspace of the same\n shape and dtype. The method then either performs inline modifications of\n the target tensor and returns it, or writes its output into the\n workspace tensor and returns that. This signature makes it possible to\n write specialized simulation methods that run without performing large\n allocations, significantly increasing simulation performance.\n\n The target may represent a wave function, a unitary matrix, or some\n other tensor. Implementations will work in all of these cases as long as\n they correctly focus on only operating on the given axes.\n\n Args:\n args: A `cirq.ApplyUnitaryArgs` object with the `args.target_tensor`\n to operate on, an `args.available_workspace` buffer to use as\n temporary workspace, and the `args.axes` of the tensor to target\n with the unitary operation. Note that this method is permitted\n (and in fact expected) to mutate `args.target_tensor` and\n `args.available_workspace`.\n\n Returns:\n If the receiving object is not able to apply its unitary effect,\n None or NotImplemented should be returned.\n\n If the receiving object is able to work inline, it should directly\n mutate `args.target_tensor` and then return `args.target_tensor`.\n The caller will understand this to mean that the result is in\n `args.target_tensor`.\n\n If the receiving object is unable to work inline, it can write its\n output over `args.available_buffer` and then return\n `args.available_buffer`. The caller will understand this to mean\n that the result is in `args.available_buffer` (and so what was\n `args.available_buffer` will become `args.target_tensor` in the next\n call, and vice versa).\n\n The receiving object is also permitted to allocate a new\n numpy.ndarray and return that as its result.\n \"\"\"\n\n\ndef apply_unitary(\n unitary_value: Any,\n args: ApplyUnitaryArgs,\n default: TDefault = RaiseTypeErrorIfNotProvided,\n *,\n allow_decompose: bool = True,\n) -> Union[np.ndarray, TDefault]:\n \"\"\"High performance left-multiplication of a unitary effect onto a tensor.\n\n Applies the unitary effect of `unitary_value` to the tensor specified in\n `args` by using the following strategies:\n\n A. Try to use `unitary_value._apply_unitary_(args)`.\n Case a) Method not present or returns `NotImplemented`.\n Continue to next strategy.\n Case b) Method returns `None`.\n Conclude `unitary_value` has no unitary effect.\n Case c) Method returns a numpy array.\n Forward the successful result to the caller.\n\n B. Try to use `unitary_value._unitary_()`.\n Case a) Method not present or returns `NotImplemented`.\n Continue to next strategy.\n Case b) Method returns `None`.\n Conclude `unitary_value` has no unitary effect.\n Case c) Method returns a numpy array.\n Multiply the matrix onto the target tensor and return to the caller.\n\n C. Try to use `unitary_value._decompose_()` (if `allow_decompose`).\n Case a) Method not present or returns `NotImplemented` or `None`.\n Continue to next strategy.\n Case b) Method returns an OP_TREE.\n Delegate to `cirq.apply_unitaries`.\n\n D. Conclude that `unitary_value` has no unitary effect.\n\n The order that the strategies are tried depends on the number of qubits\n being operated on. For small numbers of qubits (4 or less) the order is\n ABCD. For larger numbers of qubits the order is ACBD (because it is expected\n that decomposing will outperform generating the raw matrix).\n\n Args:\n unitary_value: The value with a unitary effect to apply to the target.\n args: A mutable `cirq.ApplyUnitaryArgs` object describing the target\n tensor, available workspace, and axes to operate on. The attributes\n of this object will be mutated as part of computing the result.\n default: What should be returned if `unitary_value` doesn't have a\n unitary effect. If not specified, a TypeError is raised instead of\n returning a default value.\n allow_decompose: Defaults to True. If set to False, and applying the\n unitary effect requires decomposing the object, the method will\n pretend the object has no unitary effect.\n\n Returns:\n If the receiving object does not have a unitary effect, then the\n specified default value is returned (or a TypeError is raised). If\n this occurs, then `target_tensor` should not have been mutated.\n\n Otherwise the result is the `np.ndarray` instance storing the result.\n This may be `args.target_tensor`, `args.available_workspace`, or some\n other numpy array. It is the caller's responsibility to correctly handle\n all three of these cases. In all cases `args.target_tensor` and\n `args.available_buffer` may have been mutated.\n\n Raises:\n TypeError: `unitary_value` doesn't have a unitary effect and `default`\n wasn't specified.\n \"\"\"\n\n # Decide on order to attempt application strategies.\n if len(args.axes) <= 4:\n strats = [\n _strat_apply_unitary_from_apply_unitary,\n _strat_apply_unitary_from_unitary,\n _strat_apply_unitary_from_decompose,\n ]\n else:\n strats = [\n _strat_apply_unitary_from_apply_unitary,\n _strat_apply_unitary_from_decompose,\n _strat_apply_unitary_from_unitary,\n ]\n if not allow_decompose:\n strats.remove(_strat_apply_unitary_from_decompose)\n\n # Try each strategy, stopping if one works.\n for strat in strats:\n result = strat(unitary_value, args)\n if result is None:\n break\n if result is not NotImplemented:\n return result\n\n # Don't know how to apply. Fallback to specified default behavior.\n if default is not RaiseTypeErrorIfNotProvided:\n return default\n raise TypeError(\n \"cirq.apply_unitary failed. \"\n \"Value doesn't have a (non-parameterized) unitary effect.\\n\"\n \"\\n\"\n \"type: {}\\n\"\n \"value: {!r}\\n\"\n \"\\n\"\n \"The value failed to satisfy any of the following criteria:\\n\"\n \"- An `_apply_unitary_(self, args) method that returned a value \"\n \"besides None or NotImplemented.\\n\"\n \"- A `_unitary_(self)` method that returned a value \"\n \"besides None or NotImplemented.\\n\"\n \"- A `_decompose_(self)` method that returned a \"\n \"list of unitary operations.\\n\"\n \"\".format(type(unitary_value), unitary_value)\n )\n\n\ndef _strat_apply_unitary_from_apply_unitary(\n unitary_value: Any, args: ApplyUnitaryArgs\n) -> Optional[np.ndarray]:\n # Check for magic method.\n func = getattr(unitary_value, '_apply_unitary_', None)\n if func is None:\n return NotImplemented\n op_qid_shape = qid_shape_protocol.qid_shape(unitary_value, (2,) * len(args.axes))\n sub_args = args._for_operation_with_qid_shape(range(len(op_qid_shape)), op_qid_shape)\n sub_result = func(sub_args)\n if sub_result is NotImplemented or sub_result is None:\n return sub_result\n return _incorporate_result_into_target(args, sub_args, sub_result)\n\n\ndef _strat_apply_unitary_from_unitary(\n unitary_value: Any, args: ApplyUnitaryArgs\n) -> Optional[np.ndarray]:\n # Check for magic method.\n method = getattr(unitary_value, '_unitary_', None)\n if method is None:\n return NotImplemented\n\n # Attempt to get the unitary matrix.\n matrix = method()\n if matrix is NotImplemented or matrix is None:\n return matrix\n\n val_qid_shape = qid_shape_protocol.qid_shape(unitary_value, default=(2,) * len(args.axes))\n sub_args = args._for_operation_with_qid_shape(range(len(val_qid_shape)), val_qid_shape)\n matrix = matrix.astype(sub_args.target_tensor.dtype)\n if len(val_qid_shape) == 1 and val_qid_shape[0] <= 2:\n # Special case for single-qubit, 2x2 or 1x1 operations.\n # np.einsum is faster for larger cases.\n subspaces = [(..., level) for level in range(val_qid_shape[0])]\n sub_result = linalg.apply_matrix_to_slices(\n sub_args.target_tensor, matrix, subspaces, out=sub_args.available_buffer\n )\n else:\n # General case via np.einsum.\n sub_result = linalg.targeted_left_multiply(\n matrix.reshape(val_qid_shape * 2),\n sub_args.target_tensor,\n sub_args.axes,\n out=sub_args.available_buffer,\n )\n return _incorporate_result_into_target(args, sub_args, sub_result)\n\n\ndef _strat_apply_unitary_from_decompose(val: Any, args: ApplyUnitaryArgs) -> Optional[np.ndarray]:\n operations, qubits, _ = _try_decompose_into_operations_and_qubits(val)\n if operations is None:\n return NotImplemented\n return apply_unitaries(operations, qubits, args, None)\n\n\ndef apply_unitaries(\n unitary_values: Iterable[Any],\n qubits: Sequence['cirq.Qid'],\n args: Optional[ApplyUnitaryArgs] = None,\n default: Any = RaiseTypeErrorIfNotProvided,\n) -> Optional[np.ndarray]:\n \"\"\"Apply a series of unitaries onto a state tensor.\n\n Uses `cirq.apply_unitary` on each of the unitary values, to apply them to\n the state tensor from the `args` argument.\n\n CAUTION: if one of the given unitary values does not have a unitary effect,\n forcing the method to terminate, the method will not rollback changes\n from previous unitary values.\n\n Args:\n unitary_values: The values with unitary effects to apply to the target.\n qubits: The qubits that will be targeted by the unitary values. These\n qubits match up, index by index, with the `indices` property of the\n `args` argument.\n args: A mutable `cirq.ApplyUnitaryArgs` object describing the target\n tensor, available workspace, and axes to operate on. The attributes\n of this object will be mutated as part of computing the result. If\n not specified, this defaults to the zero state of the given qubits\n with an axis ordering matching the given qubit ordering.\n default: What should be returned if any of the unitary values actually\n don't have a unitary effect. If not specified, a TypeError is\n raised instead of returning a default value.\n\n Returns:\n If any of the unitary values do not have a unitary effect, the\n specified default value is returned (or a TypeError is raised).\n CAUTION: If this occurs, the contents of `args.target_tensor`\n and `args.available_buffer` may have been mutated.\n\n If all of the unitary values had a unitary effect that was\n successfully applied, this method returns the `np.ndarray`\n storing the final result. This `np.ndarray` may be\n `args.target_tensor`, `args.available_buffer`, or some\n other instance. The caller is responsible for dealing with\n this potential aliasing of the inputs and the result.\n\n Raises:\n TypeError: An item from `unitary_values` doesn't have a unitary effect\n and `default` wasn't specified.\n ValueError: If the number of qubits does not match the number of\n axes provided in the `args`.\n \"\"\"\n if args is None:\n qid_shape = qid_shape_protocol.qid_shape(qubits)\n args = ApplyUnitaryArgs.default(qid_shape=qid_shape)\n if len(qubits) != len(args.axes):\n raise ValueError('len(qubits) != len(args.axes)')\n qubit_map = {q.with_dimension(1): args.axes[i] for i, q in enumerate(qubits)}\n state = args.target_tensor\n buffer = args.available_buffer\n\n for op in unitary_values:\n indices = [qubit_map[q.with_dimension(1)] for q in op.qubits]\n result = apply_unitary(\n unitary_value=op, args=ApplyUnitaryArgs(state, buffer, indices), default=None\n )\n\n # Handle failure.\n if result is None:\n if default is RaiseTypeErrorIfNotProvided:\n raise TypeError(\n \"cirq.apply_unitaries failed. \"\n \"There was a non-unitary value in the `unitary_values` \"\n \"list.\\n\"\n \"\\n\"\n \"non-unitary value type: {}\\n\"\n \"non-unitary value: {!r}\".format(type(op), op)\n )\n return default\n\n # Handle aliasing of results.\n if result is buffer:\n buffer = state\n state = result\n\n return state\n\n\ndef _incorporate_result_into_target(\n args: 'ApplyUnitaryArgs', sub_args: 'ApplyUnitaryArgs', sub_result: np.ndarray\n):\n \"\"\"Takes the result of calling `_apply_unitary_` on `sub_args` and\n copies it back into `args.target_tensor` or `args.available_buffer` as\n necessary to return the result of applying the unitary to the full args.\n Also swaps the buffers so the result is always in `args.target_tensor`.\n\n Args:\n args: The original args.\n sub_args: A version of `args` with transposed and sliced views of\n it's tensors.\n sub_result: The result of calling an object's `_apply_unitary_`\n method on `sub_args`. A transposed subspace of the desired\n result.\n\n Returns:\n The full result tensor after applying the unitary. Always\n `args.target_tensor`.\n\n Raises:\n ValueError: If `sub_args` tensors are not views of `args` tensors.\n\n \"\"\"\n if not (\n np.may_share_memory(args.target_tensor, sub_args.target_tensor)\n and np.may_share_memory(args.available_buffer, sub_args.available_buffer)\n ):\n raise ValueError(\n 'sub_args.target_tensor and subargs.available_buffer must be views of '\n 'args.target_tensor and args.available_buffer respectively.'\n )\n is_subspace = sub_args.target_tensor.size < args.target_tensor.size\n if sub_result is sub_args.target_tensor:\n return args.target_tensor\n if sub_result is sub_args.available_buffer:\n if is_subspace:\n # The subspace that was modified is likely much smaller than\n # the whole tensor so copy sub_result back into target_tensor.\n sub_args.target_tensor[...] = sub_result\n return args.target_tensor\n return args.available_buffer\n # The subspace that was modified is likely much smaller than\n # the whole tensor so copy sub_result back into target_tensor.\n # It's an uncommon case where sub_result is a new array.\n if np.may_share_memory(sub_args.target_tensor, sub_result):\n # Someone did something clever. E.g. implementing SWAP with a\n # reshape.\n # Copy to available_buffer instead.\n if is_subspace:\n args.available_buffer[...] = args.target_tensor\n sub_args.available_buffer[...] = sub_result\n return args.available_buffer\n sub_args.target_tensor[...] = sub_result\n return args.target_tensor\n",
"# Copyright 2018 The Cirq Developers\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# https://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\"\"\"A combination of several optimizations targeting XmonDevice.\"\"\"\nfrom functools import lru_cache\nfrom typing import Callable, cast, List, Optional, TYPE_CHECKING\n\nimport numpy as np\n\nimport cirq\nfrom cirq_google import ops as cg_ops\nfrom cirq_google.optimizers import (\n convert_to_xmon_gates,\n ConvertToSycamoreGates,\n ConvertToSqrtIswapGates,\n)\n\nif TYPE_CHECKING:\n import cirq_google\n\n\ndef _get_common_cleanup_optimizers(tolerance: float) -> List[Callable[[cirq.Circuit], None]]:\n return [\n cirq.EjectPhasedPaulis(tolerance=tolerance).optimize_circuit,\n cirq.EjectZ(tolerance=tolerance).optimize_circuit,\n cirq.DropNegligible(tolerance=tolerance).optimize_circuit,\n ]\n\n\ndef _get_xmon_optimizers(\n tolerance: float, tabulation: Optional[cirq.TwoQubitGateTabulation]\n) -> List[Callable[[cirq.Circuit], None]]:\n if tabulation is not None:\n # coverage: ignore\n raise ValueError(\"Gate tabulation not supported for xmon\")\n\n return [\n convert_to_xmon_gates.ConvertToXmonGates().optimize_circuit,\n cirq.MergeInteractions(tolerance=tolerance, allow_partial_czs=False).optimize_circuit,\n lambda c: cirq.merge_single_qubit_gates_into_phxz(c, tolerance),\n *_get_common_cleanup_optimizers(tolerance=tolerance),\n ]\n\n\ndef _get_xmon_optimizers_part_cz(\n tolerance: float, tabulation: Optional[cirq.TwoQubitGateTabulation]\n) -> List[Callable[[cirq.Circuit], None]]:\n if tabulation is not None:\n # coverage: ignore\n raise ValueError(\"Gate tabulation not supported for xmon\")\n return [\n convert_to_xmon_gates.ConvertToXmonGates().optimize_circuit,\n cirq.MergeInteractions(tolerance=tolerance, allow_partial_czs=True).optimize_circuit,\n lambda c: cirq.merge_single_qubit_gates_into_phxz(c, tolerance),\n *_get_common_cleanup_optimizers(tolerance=tolerance),\n ]\n\n\ndef _get_sycamore_optimizers(\n tolerance: float, tabulation: Optional[cirq.TwoQubitGateTabulation]\n) -> List[Callable[[cirq.Circuit], None]]:\n return [\n ConvertToSycamoreGates(tabulation=tabulation).optimize_circuit,\n lambda c: cirq.merge_single_qubit_gates_into_phxz(c, tolerance),\n *_get_common_cleanup_optimizers(tolerance=tolerance),\n ]\n\n\ndef _get_sqrt_iswap_optimizers(\n tolerance: float, tabulation: Optional[cirq.TwoQubitGateTabulation]\n) -> List[Callable[[cirq.Circuit], None]]:\n if tabulation is not None:\n # coverage: ignore\n raise ValueError(\"Gate tabulation not supported for sqrt_iswap\")\n return [\n ConvertToSqrtIswapGates().optimize_circuit,\n lambda c: cirq.merge_single_qubit_gates_into_phxz(c, tolerance),\n *_get_common_cleanup_optimizers(tolerance=tolerance),\n ]\n\n\n_OPTIMIZER_TYPES = {\n 'xmon': _get_xmon_optimizers,\n 'xmon_partial_cz': _get_xmon_optimizers_part_cz,\n 'sqrt_iswap': _get_sqrt_iswap_optimizers,\n 'sycamore': _get_sycamore_optimizers,\n}\n\n\n@lru_cache()\ndef _gate_product_tabulation_cached(\n optimizer_type: str, tabulation_resolution: float\n) -> cirq.TwoQubitGateTabulation:\n random_state = np.random.RandomState(51)\n if optimizer_type == 'sycamore':\n return cirq.two_qubit_gate_product_tabulation(\n cirq.unitary(cg_ops.SYC), tabulation_resolution, random_state=random_state\n )\n else:\n raise NotImplementedError(f\"Two qubit gate tabulation not supported for {optimizer_type}\")\n\n\ndef optimized_for_sycamore(\n circuit: cirq.Circuit,\n *,\n new_device: Optional['cirq_google.XmonDevice'] = None,\n qubit_map: Callable[[cirq.Qid], cirq.GridQubit] = lambda e: cast(cirq.GridQubit, e),\n optimizer_type: str = 'sqrt_iswap',\n tolerance: float = 1e-5,\n tabulation_resolution: Optional[float] = None,\n) -> cirq.Circuit:\n \"\"\"Optimizes a circuit for Google devices.\n\n Uses a set of optimizers that will compile to the proper gateset for the\n device (xmon, sqrt_iswap, or sycamore gates) and then use optimizers to\n compress the gate depth down as much as is easily algorithmically possible\n by merging rotations, ejecting Z gates, etc.\n\n Args:\n circuit: The circuit to optimize.\n new_device: The device the optimized circuit should be targeted at. If\n set to None, the circuit's current device is used.\n qubit_map: Transforms the qubits (e.g. so that they are GridQubits).\n optimizer_type: A string defining the optimizations to apply.\n Possible values are 'xmon', 'xmon_partial_cz', 'sqrt_iswap',\n 'sycamore'\n tolerance: The tolerance passed to the various circuit optimization\n passes.\n tabulation_resolution: If provided, compute a gateset tabulation\n with the specified resolution and use it to approximately\n compile arbitrary two-qubit gates for which an analytic compilation\n is not known.\n Returns:\n The optimized circuit.\n\n Raises:\n ValueError: If the `optimizer_type` is not a supported type.\n \"\"\"\n copy = circuit.copy()\n if optimizer_type not in _OPTIMIZER_TYPES:\n raise ValueError(\n f'{optimizer_type} is not an allowed type. Allowed '\n f'types are: {_OPTIMIZER_TYPES.keys()}'\n )\n\n tabulation: Optional[cirq.TwoQubitGateTabulation] = None\n if tabulation_resolution is not None:\n tabulation = _gate_product_tabulation_cached(optimizer_type, tabulation_resolution)\n\n opts = _OPTIMIZER_TYPES[optimizer_type](tolerance=tolerance, tabulation=tabulation)\n for optimizer in opts:\n optimizer(copy)\n\n return cirq.Circuit(\n (op.transform_qubits(qubit_map) for op in copy.all_operations()),\n strategy=cirq.InsertStrategy.EARLIEST,\n device=new_device or copy.device,\n )\n",
"# Copyright 2020 The Cirq Developers\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# https://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\nimport numpy as np\n\nimport cirq\n\n\ndef test_produces_samples():\n a, b = cirq.LineQubit.range(2)\n c = cirq.Circuit(\n cirq.H(a),\n cirq.CNOT(a, b),\n cirq.measure(a, key='a'),\n cirq.measure(b, key='b'),\n )\n\n result = cirq.StabilizerSampler().sample(c, repetitions=100)\n assert 5 < sum(result['a']) < 95\n assert np.all(result['a'] ^ result['b'] == 0)\n\n\ndef test_reset():\n q = cirq.LineQubit(0)\n sampler = cirq.StabilizerSampler()\n c = cirq.Circuit(cirq.X(q), cirq.reset(q), cirq.measure(q))\n assert sampler.sample(c)['0'][0] == 0\n c = cirq.Circuit(cirq.H(q), cirq.reset(q), cirq.measure(q))\n assert sampler.sample(c)['0'][0] == 0\n c = cirq.Circuit(cirq.reset(q), cirq.measure(q))\n assert sampler.sample(c)['0'][0] == 0\n"
] | [
[
"numpy.empty_like",
"numpy.array",
"numpy.may_share_memory"
],
[
"numpy.random.RandomState"
],
[
"numpy.all"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
aditya-giri/Cirq | [
"e5af689f184c8c5ccd9c076b2907a444b2479629"
] | [
"examples/direct_fidelity_estimation.py"
] | [
"\"\"\"Implements direct fidelity estimation.\n\nFidelity between the desired pure state rho and the actual state sigma is\ndefined as:\nF(rho, sigma) = Tr (rho sigma)\n\nIt is a unit-less measurement between 0.0 and 1.0. The following two papers\nindependently described a faster way to estimate its value:\n\nDirect Fidelity Estimation from Few Pauli Measurements\nhttps://arxiv.org/abs/1104.4695\n\nPractical characterization of quantum devices without tomography\nhttps://arxiv.org/abs/1104.3835\n\nThis code implements the algorithm proposed for an example circuit (defined in\nthe function build_circuit()) and a noise (defines in the variable noise).\n\"\"\"\n\nfrom typing import cast, List, Optional, Tuple\nimport argparse\nimport asyncio\nfrom dataclasses import dataclass\nimport itertools\nimport random\nimport sys\nimport numpy as np\nimport cirq\n\n\ndef build_circuit() -> Tuple[cirq.Circuit, List[cirq.Qid]]:\n # Builds an arbitrary circuit to test. Do not include a measurement gate.\n # The circuit need not be Clifford, but if it is, simulations will be\n # faster.\n qubits: List[cirq.Qid] = cast(List[cirq.Qid], cirq.LineQubit.range(3))\n circuit: cirq.Circuit = cirq.Circuit(cirq.CNOT(qubits[0], qubits[2]),\n cirq.Z(qubits[0]), cirq.H(qubits[2]),\n cirq.CNOT(qubits[2], qubits[1]),\n cirq.X(qubits[0]), cirq.X(qubits[1]),\n cirq.CNOT(qubits[0], qubits[2]))\n print('Circuit used:')\n print(circuit)\n return circuit, qubits\n\n\ndef compute_characteristic_function(circuit: cirq.Circuit,\n pauli_string: cirq.PauliString,\n qubits: List[cirq.Qid],\n density_matrix: np.ndarray):\n n_qubits = len(qubits)\n d = 2**n_qubits\n\n qubit_map = dict(zip(qubits, range(n_qubits)))\n # rho_i or sigma_i in https://arxiv.org/abs/1104.3835\n trace = pauli_string.expectation_from_density_matrix(\n density_matrix, qubit_map)\n assert np.isclose(trace.imag, 0.0, atol=1e-6)\n trace = trace.real\n\n prob = trace * trace / d # Pr(i) in https://arxiv.org/abs/1104.3835\n\n return trace, prob\n\n\nasync def estimate_characteristic_function(circuit: cirq.Circuit,\n pauli_string: cirq.PauliString,\n qubits: List[cirq.Qid],\n sampler: cirq.Sampler,\n samples_per_term: int):\n \"\"\"\n Estimates the characteristic function using a (noisy) circuit simulator by\n sampling the results.\n\n Args:\n circuit: The circuit to run the simulation on.\n pauli_string: The Pauli string.\n qubits: The list of qubits.\n sampler: Either a noisy simulator or an engine.\n samples_per_term: An integer greater than 0, the number of samples.\n\n Returns:\n The estimated characteristic function.\n \"\"\"\n p = cirq.PauliSumCollector(circuit=circuit,\n observable=pauli_string,\n samples_per_term=samples_per_term)\n\n await p.collect_async(sampler=sampler)\n\n sigma_i = p.estimated_energy()\n assert np.isclose(sigma_i.imag, 0.0, atol=1e-6)\n sigma_i = sigma_i.real\n\n return sigma_i\n\n\ndef _randomly_sample_from_stabilizer_bases(\n stabilizer_basis: List[cirq.DensePauliString],\n n_measured_operators: int, n_qubits: int):\n \"\"\"\n Given a stabilizer basis, randomly creates Pauli states by including the\n basis vector or not.\n\n Args:\n stabilizer_basis: A list of Pauli strings that is the stabilizer basis\n to sample from.\n n_measured_operators: The total number of Pauli measurements, or None to\n explore each Pauli state once.\n n_qubits: An integer that is the number of qubits.\n\n Returns:\n A list of Pauli strings that is the Pauli states built.\n \"\"\"\n dense_pauli_strings = []\n for _ in range(n_measured_operators):\n # Build the Pauli string as a random sample of the basis elements.\n dense_pauli_string = cirq.DensePauliString.eye(n_qubits)\n for stabilizer in stabilizer_basis:\n if np.random.randint(2) == 1:\n dense_pauli_string *= stabilizer\n dense_pauli_strings.append(dense_pauli_string)\n return dense_pauli_strings\n\n\ndef _enumerate_all_from_stabilizer_bases(\n stabilizer_basis: List[cirq.DensePauliString], n_qubits: int):\n \"\"\"\n Given a stabilizer basis, creates the exhaustive list of Pauli states that\n are spanned by the basis.\n\n Args:\n stabilizer_basis: A list of Pauli strings that is the stabilizer basis\n to build all the Pauli strings.\n n_qubits: An integer that is the number of qubits.\n\n Returns:\n A list of Pauli strings that is the Pauli states built.\n \"\"\"\n dense_pauli_strings = []\n for coefficients in itertools.product([False, True], repeat=n_qubits):\n dense_pauli_string = cirq.DensePauliString.eye(n_qubits)\n for (keep, stabilizer) in zip(coefficients, stabilizer_basis):\n if keep:\n dense_pauli_string *= stabilizer\n dense_pauli_strings.append(dense_pauli_string)\n return dense_pauli_strings\n\n\n@dataclass\nclass PauliTrace:\n \"\"\"\n A class that contains the Pauli states as described on page 2 of:\n https://arxiv.org/abs/1104.3835\n \"\"\"\n # Pauli string.\n P_i: cirq.PauliString\n # Coefficient of the ideal pure state expanded in the Pauli basis scaled by\n # sqrt(dim H), formally defined at bottom of left column of page 2.\n rho_i: float\n # A probablity (between 0.0 and 1.0) that is the relevance distribution,\n # formally defined at top of right column of page 2.\n Pr_i: float\n\n\ndef _estimate_pauli_traces_clifford(n_qubits: int,\n clifford_state: cirq.CliffordState,\n n_measured_operators: Optional[int]\n ) -> List[PauliTrace]:\n \"\"\"\n Estimates the Pauli traces in case the circuit is Clifford. When we have a\n Clifford circuit, there are 2**n Pauli traces that have probability 1/2**n\n and all the other traces have probability 0. In addition, there is a fast\n way to compute find out what the traces are. See the documentation of\n cirq.CliffordState for more detail. This function uses the speedup to sample\n the Pauli states with non-zero probability.\n\n Args:\n n_qubits: An integer that is the number of qubits.\n clifford_state: The basis of the Pauli states with non-zero probability.\n n_measured_operators: The total number of Pauli measurements, or None to\n explore each Pauli state once.\n\n Returns:\n A list of Pauli states (represented as tuples of Pauli string, rho_i,\n and probability.\n \"\"\"\n\n # When the circuit consists of Clifford gates only, we can sample the\n # Pauli states more efficiently as described on page 4 of:\n # https://arxiv.org/abs/1104.4695\n\n d = 2**n_qubits\n\n # The stabilizers_basis variable only contains basis vectors. For\n # example, if we have n=3 qubits, then we should have 2**n=8 Pauli\n # states that we can sample, but the basis will still have 3 entries. We\n # must flip a coin for each, whether or not to include them.\n stabilizer_basis: List[cirq.DensePauliString] = clifford_state.stabilizers()\n\n if n_measured_operators is not None:\n dense_pauli_strings = _randomly_sample_from_stabilizer_bases(\n stabilizer_basis, n_measured_operators, n_qubits)\n assert len(dense_pauli_strings) == n_measured_operators\n else:\n dense_pauli_strings = _enumerate_all_from_stabilizer_bases(\n stabilizer_basis, n_qubits)\n assert len(dense_pauli_strings) == 2**n_qubits\n\n pauli_traces: List[PauliTrace] = []\n for dense_pauli_string in dense_pauli_strings:\n # The code below is equivalent to calling\n # clifford_state.wave_function() and then calling\n # compute_characteristic_function() on the results (albeit with a\n # wave function instead of a density matrix). It is, however,\n # unncessary to do so. Instead we directly obtain the scalar rho_i.\n rho_i = dense_pauli_string.coefficient\n\n assert np.isclose(rho_i.imag, 0.0, atol=1e-6)\n rho_i = rho_i.real\n\n dense_pauli_string *= rho_i\n\n assert np.isclose(abs(rho_i), 1.0, atol=1e-6)\n Pr_i = 1.0 / d\n\n pauli_traces.append(\n PauliTrace(P_i=dense_pauli_string.sparse(), rho_i=rho_i, Pr_i=Pr_i))\n return pauli_traces\n\n\ndef _estimate_pauli_traces_general(qubits: List[cirq.Qid],\n circuit: cirq.Circuit,\n n_measured_operators: Optional[int]\n ) -> List[PauliTrace]:\n \"\"\"\n Estimates the Pauli traces in case the circuit is not Clifford. In this case\n we cannot use the speedup implemented in the function\n _estimate_pauli_traces_clifford() above, and so do a slow, density matrix\n simulation.\n\n Args:\n qubits: The list of qubits.\n circuit: The (non Clifford) circuit.\n n_measured_operators: The total number of Pauli measurements, or None to\n explore each Pauli state once.\n\n Returns:\n A list of Pauli states (represented as tuples of Pauli string, rho_i,\n and probability.\n \"\"\"\n\n n_qubits = len(qubits)\n\n dense_simulator = cirq.DensityMatrixSimulator()\n # rho in https://arxiv.org/abs/1104.3835\n clean_density_matrix = cast(\n cirq.DensityMatrixTrialResult,\n dense_simulator.simulate(circuit)).final_density_matrix\n\n all_operators = itertools.product([cirq.I, cirq.X, cirq.Y, cirq.Z],\n repeat=n_qubits)\n if n_measured_operators is not None:\n dense_operators = random.sample(tuple(all_operators),\n n_measured_operators)\n else:\n dense_operators = list(all_operators)\n\n pauli_traces: List[PauliTrace] = []\n for P_i in dense_operators:\n pauli_string = cirq.PauliString(dict(zip(qubits, P_i)))\n rho_i, Pr_i = compute_characteristic_function(circuit, pauli_string,\n qubits,\n clean_density_matrix)\n pauli_traces.append(PauliTrace(P_i=pauli_string, rho_i=rho_i,\n Pr_i=Pr_i))\n return pauli_traces\n\n\n@dataclass\nclass TrialResult:\n \"\"\"\n Contains the results of a trial, either by simulator or actual run\n \"\"\"\n # The Pauli trace that was measured\n pauli_trace: PauliTrace\n # Coefficient of the measured/simulated pure state expanded in the Pauli\n # basis scaled by sqrt(dim H), formally defined at bottom of left column of\n # second page of https://arxiv.org/abs/1104.3835\n sigma_i: float\n\n\n@dataclass\nclass DFEIntermediateResult:\n \"\"\"\n A container for the various debug and run data from calling the function\n direct_fidelity_estimation(). This is useful when running a long-computation\n on an actual computer, which is expensive. This way, runs can be more easily\n debugged offline.\n \"\"\"\n # If the circuit is Clifford, the Clifford state from which we can extract\n # a list of Pauli strings for a basis of the stabilizers.\n clifford_state: Optional[cirq.CliffordState]\n # The list of Pauli traces we can sample from.\n pauli_traces: List[PauliTrace]\n # Measurement results from sampling the circuit.\n trial_results: List[TrialResult]\n\n\ndef direct_fidelity_estimation(circuit: cirq.Circuit, qubits: List[cirq.Qid],\n sampler: cirq.Sampler,\n n_measured_operators: Optional[int],\n samples_per_term: int):\n \"\"\"\n Implementation of direct fidelity estimation, as per 'Direct Fidelity\n Estimation from Few Pauli Measurements' https://arxiv.org/abs/1104.4695 and\n 'Practical characterization of quantum devices without tomography'\n https://arxiv.org/abs/1104.3835.\n\n Args:\n circuit: The circuit to run the simulation on.\n qubits: The list of qubits.\n sampler: Either a noisy simulator or an engine.\n n_measured_operators: The total number of Pauli measurements, or None to\n explore each Pauli state once.\n samples_per_term: if set to 0, we use the 'sampler' parameter above as\n a noise (must be of type cirq.DensityMatrixSimulator) and\n simulate noise in the circuit. If greater than 0, we instead use the\n 'sampler' parameter directly to estimate the characteristic\n function.\n Returns:\n The estimated fidelity and a log of the run.\n \"\"\"\n # n_measured_operators is upper-case N in https://arxiv.org/abs/1104.3835\n\n # Number of qubits, lower-case n in https://arxiv.org/abs/1104.3835\n n_qubits = len(qubits)\n\n clifford_circuit = True\n clifford_state: Optional[cirq.CliffordState] = None\n try:\n clifford_state = cirq.CliffordState(\n qubit_map={qubits[i]: i for i in range(len(qubits))})\n for gate in circuit.all_operations():\n clifford_state.apply_unitary(gate)\n except ValueError:\n clifford_circuit = False\n\n # Computes for every \\hat{P_i} of https://arxiv.org/abs/1104.3835\n # estimate rho_i and Pr(i). We then collect tuples (rho_i, Pr(i), \\hat{Pi})\n # inside the variable 'pauli_traces'.\n if clifford_circuit:\n assert clifford_state is not None\n pauli_traces = _estimate_pauli_traces_clifford(\n n_qubits, cast(cirq.CliffordState, clifford_state),\n n_measured_operators)\n else:\n pauli_traces = _estimate_pauli_traces_general(qubits, circuit,\n n_measured_operators)\n\n p = np.asarray([x.Pr_i for x in pauli_traces])\n\n if n_measured_operators is None:\n # Since we enumerate all the possible traces, the probs should add to 1.\n assert np.isclose(np.sum(p), 1.0, atol=1e-6)\n p /= np.sum(p)\n\n fidelity = 0.0\n\n if samples_per_term == 0:\n # sigma in https://arxiv.org/abs/1104.3835\n if not isinstance(sampler, cirq.DensityMatrixSimulator):\n raise TypeError('sampler is not a cirq.DensityMatrixSimulator '\n 'but samples_per_term is zero.')\n noisy_simulator = cast(cirq.DensityMatrixSimulator, sampler)\n noisy_density_matrix = cast(\n cirq.DensityMatrixTrialResult,\n noisy_simulator.simulate(circuit)).final_density_matrix\n\n if clifford_circuit and n_measured_operators is None:\n # In case the circuit is Clifford and we compute an exhaustive list of\n # Pauli traces, instead of sampling we can simply enumerate them because\n # they all have the same probability.\n measured_pauli_traces = pauli_traces\n else:\n # Otherwise, randomly sample as per probability.\n measured_pauli_traces = np.random.choice(pauli_traces,\n size=len(pauli_traces),\n p=p)\n\n trial_results: List[TrialResult] = []\n for pauli_trace in measured_pauli_traces:\n measure_pauli_string: cirq.PauliString = pauli_trace.P_i\n rho_i = pauli_trace.rho_i\n\n if samples_per_term > 0:\n sigma_i = asyncio.get_event_loop().run_until_complete(\n estimate_characteristic_function(circuit, measure_pauli_string,\n qubits, sampler,\n samples_per_term))\n else:\n sigma_i, _ = compute_characteristic_function(\n circuit, measure_pauli_string, qubits, noisy_density_matrix)\n\n trial_results.append(\n TrialResult(pauli_trace=pauli_trace, sigma_i=sigma_i))\n\n fidelity += sigma_i / rho_i\n\n estimated_fidelity = fidelity / len(pauli_traces)\n\n dfe_intermediate_result = DFEIntermediateResult(\n clifford_state=clifford_state,\n pauli_traces=pauli_traces,\n trial_results=trial_results)\n\n return estimated_fidelity, dfe_intermediate_result\n\n\ndef parse_arguments(args):\n \"\"\"Helper function that parses the given arguments.\"\"\"\n parser = argparse.ArgumentParser('Direct fidelity estimation.')\n\n # TODO: Offer some guidance on how to set this flag. Maybe have an\n # option to do an exhaustive sample and do numerical studies to know which\n # choice is the best.\n # Github issue: https://github.com/quantumlib/Cirq/issues/2802\n parser.add_argument('--n_measured_operators',\n default=10,\n type=int,\n help='Numbers of measured operators (Pauli strings). '\n 'If the circuit is Clifford, these operators are '\n 'computed by sampling for the basis of stabilizers. If '\n 'the circuit is not Clifford, this is a random sample '\n 'all the possible operators. If the value of this '\n 'parameter is None, we enumerate all the operators '\n 'which is 2**n_qubit for Clifford circuits and '\n '4**n_qubits otherwise.')\n\n parser.add_argument('--samples_per_term',\n default=0,\n type=int,\n help='Number of samples per trial or 0 if no sampling.')\n\n return vars(parser.parse_args(args))\n\n\ndef main(*, n_measured_operators: Optional[int], samples_per_term: int):\n circuit, qubits = build_circuit()\n\n noise = cirq.ConstantQubitNoiseModel(cirq.depolarize(0.1))\n print('Noise model: %s' % (noise))\n noisy_simulator = cirq.DensityMatrixSimulator(noise=noise)\n\n estimated_fidelity, _ = direct_fidelity_estimation(\n circuit,\n qubits,\n noisy_simulator,\n n_measured_operators=n_measured_operators,\n samples_per_term=samples_per_term)\n print('Estimated fidelity: %f' % (estimated_fidelity))\n\n\nif __name__ == '__main__':\n main(**parse_arguments(sys.argv[1:]))\n"
] | [
[
"numpy.asarray",
"numpy.random.randint",
"numpy.sum",
"numpy.isclose"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
frmunozz/IrregularMatchedFilter | [
"b64c348345b16d777839f13dc585d1816cf81ca6"
] | [
"developing/lombScargle.py"
] | [
"from gatspy.periodic import LombScargleFast\nfrom scipy import signal\nfrom astropy.stats import LombScargle\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nplt.style.use('seaborn-paper')\nimport time\n\"\"\"\ncomparison between many implementations of lomb-scargle periodogram\n\"\"\"\n# 3 parts separated in time, one with slight irregularities in time sampling\n# another with change of spacing and the last one with big outlier in spacing\nN = 120\nT = np.zeros(N)\ndt_implicit = 1 / N\nt0 = np.linspace(0, int(N/3)-1, int(N/3))\nnp.random.seed(1)\ne = np.random.normal(0, dt_implicit * 0.5, N//3)\nT[0:N//3] = t0 * dt_implicit + e\nshift = 30 * dt_implicit\n\nnp.random.seed(2)\nt0 = np.linspace(int(N/3), int(N*1/2)-1, int(N/6))\ne = np.random.normal(0, dt_implicit * 0.5, N//6)\nT[N//3:N//2] = shift + t0 * dt_implicit / 2 + e\n\nnp.random.seed(3)\nt0 = np.linspace(int(N/2), int(N*2/3)-1, int(N/6))\ne = np.random.normal(0, dt_implicit * 0.5, N//6)\nT[N//2:2*N//3] = t0 * 2 * dt_implicit + e\n\nnp.random.seed(4)\nt0 = np.linspace(2*N//3, N-1, N - 2*N//3)\ne = np.random.normal(0, dt_implicit * 0.5, N - 2*N//3)\nT[2*N//3:N] = 2 * shift + t0 * dt_implicit / 2 + e\nT.sort()\n\n# signal is sinusoidal again with same frequency\nfreq_of_sin = 10\ns = np.sin(freq_of_sin * 2 * np.pi * T)\n# apply noise\nnp.random.seed(1)\nnoise = np.random.normal(0, 0.3, N)\ndata = s + noise\nplt.figure(0)\nplt.plot(T, data, alpha=0.5)\nplt.plot(T, s, \"k.-\")\nplt.show()\n\nt_i = time.time()\nfrequency, power = LombScargle(T, data).autopower()\nt_f1 = time.time()\nmodel = LombScargleFast().fit(T, data, None)\nperiods, power2 = model.periodogram_auto(nyquist_factor=max(frequency))\nt_f2 = time.time()\npgram = signal.lombscargle(T, data, frequency, normalize=True)\nt_f3 = time.time()\n\nplt.figure(1)\nplt.plot(frequency, power, 'r--', label=\"LS from astropy, time: {}\".format(round(t_f1-t_i, 3)))\nplt.plot(1 / periods, power2, 'g', alpha=0.6, label=\"LS from gatspy, time: {}\".format(round(t_f2-t_f1, 3)))\nplt.plot(frequency, pgram, 'b', label=\"LS from scipy, time: {}\".format(round(t_f3-t_f2, 3)))\nplt.xlim([0, 200])\nplt.title(\"Lomb-Scargle periodogram comparison for {} points\".format(N))\nplt.xlabel(\"frequency [Hz]\")\nplt.ylabel(\"Lomb-Scargle Power\")\nplt.axvline(freq_of_sin, color='k', linestyle='solid', label=\"real frequency expected\")\nplt.axvline(freq_of_sin * 2 * np.pi, color='k', alpha=0.5, linestyle='solid', label=\"real angular frequency expected\")\nplt.legend()\nplt.show()\n\n\"\"\"\nat first sight the implementation from astropy seems to be the most faster but its necessary to run \nseveral repetitions for different numbers of points to see exactply which is more faster, for know \nthis is not necessary to do\n\"\"\"\n"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.axvline",
"numpy.random.seed",
"numpy.linspace",
"numpy.sin",
"matplotlib.pyplot.plot",
"scipy.signal.lombscargle",
"numpy.random.normal",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"numpy.zeros",
"matplotlib.pyplot.style.use",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.6",
"1.10",
"1.4",
"1.9",
"1.5",
"1.2",
"1.7",
"1.0",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
mojtaba-eshghie/ethereum-rtm | [
"2a999ab5dcd557350922b311dbaba46f2f929d1c"
] | [
"prepare-data2.py"
] | [
"#!/usr/bin/python3\n\nimport csv\nimport pandas as pd\nimport numpy as np\nimport json\nimport subprocess\n\n'''\nwith open('data/final.csv', 'r') as final_csv:\n csv_reader = csv.reader(final_csv, delimiter=',')\n line_count = 0\n for row in csv_reader:\n print(row)\n'''\ndata = pd.read_csv('data/final.csv')\nsc_balances_before_file = open('data/sc-balances-before-exec.json')\nsc_balances_after_file = open('data/sc-balances-after-exec.json')\n\nbefore_exec_sc_data = json.load(sc_balances_before_file)\nafter_exec_sc_data = json.load(sc_balances_after_file)\n\n\ngas_used = []\ninput_sizes = []\nvictim_balance_deltas = []\nattacker_balance_deltas = []\nlabels = []\ntx_hashs = []\ncall_stack_depths = []\n\n'''\nfor sc_address, before_balance in before_exec_sc_data.items():\n \n'''\n\nfor i in range(0, data.shape[0]):\n\n labels.append(data.iloc[i]['fuzz_string'].split(',')[-2])\n \n \n tx_hashs.append(data.iloc[i]['tx_hash'])\n \n gas_used.append(int(data.iloc[i]['gas_used']))\n\n\n\n '''\n from => is the attacker\n to => is the victim\n '''\n attacker_addr = data.iloc[i]['from']\n victim_addr = data.iloc[i]['to']\n\n victim_balance_deltas.append(int(after_exec_sc_data[victim_addr]) - int(before_exec_sc_data[victim_addr]))\n attacker_balance_deltas.append(int(after_exec_sc_data[attacker_addr]) - int(before_exec_sc_data[attacker_addr]))\n\n \n\n\n\n\n # call_stack_depths\n index = str(i + 26)\n #print(index)\n \n if index == '424':\n call_stack_depths.append(3.3)\n continue\n\n result = subprocess.run([\"./compare.py\", index], stdout=subprocess.PIPE)\n\n call_stack_depths.append(float(result.stdout))\n\n\n print('Data point added for tx #{}'.format(index))\n\n\noutput_df = pd.DataFrame({\n 'tx_hash': tx_hashs,\n 'gas_used': gas_used,\n 'victim_balance_delta': victim_balance_deltas,\n 'attacker_balance_delta': attacker_balance_deltas,\n 'call_stack_depth': call_stack_depths, \n 'label': labels\n})\n\noutput_df.to_csv('data/final_prepared.csv', index=True)\nprint('Successfully store the final_prepared.csv file')"
] | [
[
"pandas.read_csv",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
notantony/Grid-Anchor-based-Image-Cropping-Pytorch | [
"32a2dea9151c123c8e589bd196450f56cf3ef7d1",
"32a2dea9151c123c8e589bd196450f56cf3ef7d1"
] | [
"rod_align/_ext/rod_align/__init__.py",
"TestAccuracy.py"
] | [
"\nfrom torch.utils.ffi import _wrap_function\nfrom ._rod_align import lib as _lib, ffi as _ffi\n\n__all__ = []\ndef _import_symbols(locals):\n for symbol in dir(_lib):\n fn = getattr(_lib, symbol)\n if callable(fn):\n locals[symbol] = _wrap_function(fn, _ffi)\n else:\n locals[symbol] = fn\n __all__.append(symbol)\n\n_import_symbols(locals())\n",
"from croppingDataset import GAICD\nfrom croppingModel import build_crop_model\nimport time\nimport math\nimport sys\nimport torch\nfrom torch.autograd import Variable\nimport torch.backends.cudnn as cudnn\nimport torch.utils.data as data\nimport argparse\nfrom scipy.stats import spearmanr, pearsonr\n\nparser = argparse.ArgumentParser(\n description='Single Shot MultiBox Detector Training With Pytorch')\nparser.add_argument('--dataset_root', default='dataset/GAIC/', help='Dataset root directory path')\nparser.add_argument('--image_size', default=256, type=int, help='Batch size for training')\nparser.add_argument('--batch_size', default=1, type=int, help='Batch size for training')\nparser.add_argument('--num_workers', default=0, type=int, help='Number of workers used in dataloading')\nparser.add_argument('--cuda', default=True, help='Use CUDA to train model')\nparser.add_argument('--net_path', default='weights/ablation/cropping/mobilenetv2/downsample4_multi_Aug1_Align9_Cdim8/23_0.625_0.583_0.553_0.525_0.785_0.762_0.748_0.723_0.783_0.806.pth_____',\n help='Directory for saving checkpoint models')\nargs = parser.parse_args()\n\nif torch.cuda.is_available():\n if args.cuda:\n torch.set_default_tensor_type('torch.cuda.FloatTensor')\n if not args.cuda:\n print(\"WARNING: It looks like you have a CUDA device, but aren't \" +\n \"using CUDA.\\nRun with --cuda for optimal training speed.\")\n torch.set_default_tensor_type('torch.FloatTensor')\nelse:\n torch.set_default_tensor_type('torch.FloatTensor')\n\n\ndata_loader = data.DataLoader(GAICD(image_size=args.image_size, dataset_dir=args.dataset_root, set='test'), args.batch_size, num_workers=args.num_workers, shuffle=False)\n\ndef test():\n\n net = build_crop_model(scale='multi', alignsize=9, reddim=8, loadweight=True, model='mobilenetv2', downsample=4)\n\n net.load_state_dict(torch.load(args.net_path))\n\n if args.cuda:\n net = torch.nn.DataParallel(net,device_ids=[0])\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n net = net.cuda()\n\n net.eval()\n\n acc4_5 = []\n acc4_10 = []\n wacc4_5 = []\n wacc4_10 = []\n srcc = []\n pcc = []\n for n in range(4):\n acc4_5.append(0)\n acc4_10.append(0)\n wacc4_5.append(0)\n wacc4_10.append(0)\n\n for id, sample in enumerate(data_loader):\n image = sample['image']\n bboxs = sample['bbox']\n MOS = sample['MOS']\n\n roi = []\n\n for idx in range(0,len(bboxs['xmin'])):\n roi.append((0, bboxs['xmin'][idx],bboxs['ymin'][idx],bboxs['xmax'][idx],bboxs['ymax'][idx]))\n\n if args.cuda:\n image = Variable(image.cuda())\n roi = Variable(torch.Tensor(roi))\n else:\n image = Variable(image)\n roi = Variable(torch.Tensor(roi))\n\n t0 = time.time()\n out = net(image,roi)\n t1 = time.time()\n print('timer: %.4f sec.' % (t1 - t0))\n\n id_MOS = sorted(range(len(MOS)), key=lambda k: MOS[k], reverse=True)\n id_out = sorted(range(len(out)), key=lambda k: out[k], reverse=True)\n\n rank_of_returned_crop = []\n for k in range(4):\n rank_of_returned_crop.append(id_MOS.index(id_out[k]))\n\n for k in range(4):\n temp_acc_4_5 = 0.0\n temp_acc_4_10 = 0.0\n for j in range(k+1):\n if MOS[id_out[j]] >= MOS[id_MOS[4]]:\n temp_acc_4_5 += 1.0\n if MOS[id_out[j]] >= MOS[id_MOS[9]]:\n temp_acc_4_10 += 1.0\n acc4_5[k] += temp_acc_4_5 / (k+1.0)\n acc4_10[k] += temp_acc_4_10 / (k+1.0)\n\n for k in range(4):\n temp_wacc_4_5 = 0.0\n temp_wacc_4_10 = 0.0\n temp_rank_of_returned_crop = rank_of_returned_crop[:(k+1)]\n temp_rank_of_returned_crop.sort()\n for j in range(k+1):\n if temp_rank_of_returned_crop[j] <= 4:\n temp_wacc_4_5 += 1.0 * math.exp(-0.2*(temp_rank_of_returned_crop[j]-j))\n if temp_rank_of_returned_crop[j] <= 9:\n temp_wacc_4_10 += 1.0 * math.exp(-0.1*(temp_rank_of_returned_crop[j]-j))\n wacc4_5[k] += temp_wacc_4_5 / (k+1.0)\n wacc4_10[k] += temp_wacc_4_10 / (k+1.0)\n\n\n MOS_arr = []\n out = torch.squeeze(out).cpu().detach().numpy()\n for k in range(len(MOS)):\n MOS_arr.append(MOS[k].numpy()[0])\n srcc.append(spearmanr(MOS_arr,out)[0])\n pcc.append(pearsonr(MOS_arr,out)[0])\n\n\n for k in range(4):\n acc4_5[k] = acc4_5[k] / 200.0\n acc4_10[k] = acc4_10[k] / 200.0\n wacc4_5[k] = wacc4_5[k] / 200.0\n wacc4_10[k] = wacc4_10[k] / 200.0\n\n avg_srcc = sum(srcc) / 200.0\n avg_pcc = sum(pcc) / 200.0\n\n sys.stdout.write('[%.3f, %.3f, %.3f, %.3f] [%.3f, %.3f, %.3f, %.3f]\\n' % (acc4_5[0],acc4_5[1],acc4_5[2],acc4_5[3],acc4_10[0],acc4_10[1],acc4_10[2],acc4_10[3]))\n sys.stdout.write('[%.3f, %.3f, %.3f, %.3f] [%.3f, %.3f, %.3f, %.3f]\\n' % (wacc4_5[0],wacc4_5[1],wacc4_5[2],wacc4_5[3],wacc4_10[0],wacc4_10[1],wacc4_10[2],wacc4_10[3]))\n sys.stdout.write('[Avg SRCC: %.3f] [Avg PCC: %.3f]\\n' % (avg_srcc,avg_pcc))\n\n\nif __name__ == '__main__':\n test()\n"
] | [
[
"torch.utils.ffi._wrap_function"
],
[
"torch.set_default_tensor_type",
"torch.Tensor",
"torch.load",
"scipy.stats.pearsonr",
"torch.cuda.is_available",
"scipy.stats.spearmanr",
"torch.nn.DataParallel",
"torch.squeeze",
"torch.autograd.Variable"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"1.3",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
StudentsZhouPengfei/Automatically-Differentiable-Quantum-Circuit-for-Many-qubit-State-Preparation | [
"42d3a77380e78819375c9fb2c5600ddc89a3ae3f"
] | [
"XY_Model_propare_state3_chi64_A0.py"
] | [
"import torch as tc\r\nimport numpy as np\r\nimport copy\r\nimport os,sys\r\nimport Circle_Function_Class_A0 as ev\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib\r\nmatplotlib.use('Agg')\r\nfrom torch.optim.lr_scheduler import StepLR\r\nimport BasicFunSJR as bfs\r\nfrom CNNBTN import Paras_VL_CNN_BTN_Collected1chg1\r\nimport BasicFun as bf\r\n\r\ntmp = sys.argv[0][sys.argv[0].rfind(os.sep) + 1:] # 返回文件名\r\nmark = tmp[-5]\r\nwhich_gpu = tmp[-4] # 调用固定\r\n\r\npara = Paras_VL_CNN_BTN_Collected1chg1()\r\npara['dataset'] = 'fashion-mnist'\r\npara['device'] = bf.choose_device(which_gpu)\r\npara['log_name'] = './record' + mark + which_gpu\r\n\r\nstart = tc.cuda.Event(enable_timing=True)\r\nend = tc.cuda.Event(enable_timing=True)\r\n\r\nos.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'\r\nos.environ['CUDA_VISIBLE_DEVICE'] = '0'\r\n\r\n# tc.manual_seed(7) # 固定随机数,使产生的随机数可以复现\r\ndtype = tc.float32 # float 监控norm\r\nmps_num = 48\r\nlr = 1e-2\r\nit_time = 50\r\npt_time = 50 # 交错优化所在的次数\r\ndt_print = 10\r\nstep_size = it_time * pt_time // 5 # lr学习率递减的间隔epoch\r\nx1_axis = list() # 作图横轴 优化次数\r\nidentity_4 = tc.eye(4, dtype=dtype).to(para['device']) # 第二层演化小量变化的单位阵量子门\r\nvol = tc.tensor(1e-3, dtype=dtype).to(para['device']) # 为其小量变化幅度, 对优化次数影响不大\r\ncon_vol = tc.tensor(1e-5, dtype=dtype).to(para['device'])\r\nentropy_list = list()\r\naverage = tc.tensor(0, dtype=dtype).to(para['device']) # 计算纠缠熵 所用到的初始值\r\nk_bood = 64\r\nfile_name = r'./tar_data.npz'\r\nout_file_name = r'./layer_out_data.npz'\r\nLoss_accuracy_range = 0.0001 # 控制Loss精度的范围,达到精度范围自动跳出循环\r\nbase_it_time = it_time//3 # 进行优化的最少次数,与分层优化有关\r\ncenter_position = 24\r\n\r\nlayer_num = 3 # 控制不同层的门进行优化\r\ngatenum = (mps_num - 1)*layer_num # 控制变分参数量子门的个数\r\ntar_mpslist = list()\r\nini_state = list()\r\ny_loss_layer = list() # 分层交错进行 每层的精度\r\ny_loss_conda = list() # 协同优化 的精度\r\n\r\nread_gatenum = (mps_num - 1)*(layer_num -1)\r\nzero_gatetensor = tc.zeros(gatenum, 4, 4)\r\n\r\nconba_gatalist = list()\r\nlayer_gatelist = list() # 在后续被reshape成(2, 4, 2)的三阶tensor\r\n\r\nlayer_gatelist_0 = list() # 将门分层储存\r\nlayer_gatelist_1 = list() # 将门分层储存\r\nlayer_gatelist_2 = list() # 将门分层储存\r\nlayer_gatelist_3 = list() # 将门分层储存\r\nlayer_gatelist_4 = list() # 将门分层储存\r\nlayer_gatelist_5 = list() # 将门分层储存\r\n\r\nlayer_optimize = list() # 分层存储优化器\r\nloss_ = list([list([]), list([]), list([]), list([]), list([]), list([]), list([]), list([]), list([]), list([]),\r\n list([]), list([]), list([])])\r\n\r\nhalf_entropy_list = list([]) # 制作热图\r\nhalf_entropy_list.append(tc.zeros([pt_time+1, mps_num-1])) # 最后一次为目标纠缠熵\r\nnumber_list = list([0]) \r\n\r\nprint('The quantum circuit is' + str(layer_num))\r\nprint('lr=:' + str(lr) + ', k_bood=: ' + str(k_bood) + ', A small amount of vol per unit door is: ' + str(vol))\r\n\r\ndata = np.load(file_name)\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist0']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist1']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist2']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist3']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist4']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist5']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist6']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist7']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist8']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist9']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist10']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist11']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist12']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist13']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist14']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist15']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist16']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist17']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist18']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist19']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist20']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist21']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist22']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist23']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist24']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist25']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist26']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist27']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist28']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist29']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist30']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist31']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist32']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist33']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist34']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist35']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist36']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist37']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist38']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist39']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist40']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist41']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist42']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist43']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist44']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist45']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist46']).to(para['device']))\r\ntar_mpslist.append(tc.from_numpy(data['tar_mpslist47']).to(para['device']))\r\n\r\n\r\ndef fprint(content, file=None, print_screen=True, append=True):\r\n if file is None:\r\n file = './record.log'\r\n if append:\r\n way = 'ab'\r\n else:\r\n way = 'wb'\r\n with open(file, way, buffering=0) as log:\r\n log.write((content + '\\n').encode(encoding='utf-8'))\r\n if print_screen:\r\n print(content)\r\n\r\n\r\ndef mps_norm(tar_tensor_): # 对目标量子态进行归一化 log归一化\r\n tv = tc.einsum('asb,asd->bd', tar_tensor_[0].data, tar_tensor_[0].data)\r\n t_norm = tc.norm(tv)\r\n tv = tv / t_norm\r\n tar_tensor_[0] = tar_tensor_[0].data / tc.sqrt(t_norm)\r\n for gt in range(1, mps_num):\r\n if gt < mps_num - 1:\r\n tv = tc.einsum('ac,asb,csd->bd', tv, tar_tensor_[gt].data, tar_tensor_[gt].data)\r\n else:\r\n tv = tc.einsum('ac,asb,csd->bd', tv, tar_tensor_[gt].data, tar_tensor_[gt].data)\r\n norm_t = tc.norm(tv)\r\n tv = tv / norm_t\r\n tar_tensor_[gt] = tar_tensor_[gt] / tc.sqrt(norm_t)\r\n\r\n\r\ndef qr_left_and_right_location(MPS_list, location, vol, feature_num=2): # 对目标MPS进行正交,并求解其纠缠熵\r\n # print('location', location)\r\n for k in range(location):\r\n # print('k', k)\r\n q, r = tc.qr(MPS_list[k].reshape(-1, MPS_list[k].shape[2]))\r\n r = r\r\n MPS_list[k] = q.reshape(-1, feature_num, q.shape[1])\r\n MPS_list[k + 1] = tc.einsum('nl, lmk-> nmk', [r, MPS_list[k + 1]])\r\n for i in range(len(MPS_list) - 1, location, -1):\r\n # print('i', i)\r\n q, r = tc.qr(MPS_list[i].reshape(MPS_list[i].shape[0], -1).t())\r\n q_shape = q.t().shape\r\n MPS_list[i] = q.t().reshape(q_shape[0], feature_num, -1)\r\n r = r\r\n MPS_list[i - 1] = tc.einsum('ldk, nk-> ldn', [MPS_list[i - 1], r])\r\n MPS_list[location] = MPS_list[location]/tc.norm(MPS_list[location])\r\n # u, s, v = tc.svd(MPS_list[location].reshape(-1, MPS_list[location].shape[2]))\r\n u, s, v = tc.svd(MPS_list[location].reshape(MPS_list[location].shape[0], -1))\r\n s = s[s > vol]\r\n y = (-1) * tc.sum(tc.pow(s, 2) * tc.log(tc.pow(s, 2)), dim=0).item()\r\n return y, MPS_list # y 返回纠缠熵 , mps_list返回正交化的目标mps的list()\r\n\r\n\r\ndef half_entropy(out_mps):\r\n for ht in range(1, mps_num):\r\n h_entropy = qr_left_and_right_location(out_mps, ht, 1e-16)[0]\r\n half_entropy_list[0][number_list[0], ht-1] = h_entropy\r\n number_list[0] = number_list[0] + 1\r\n\r\n\r\nentro_tar = copy.deepcopy(tar_mpslist)\r\n\r\nfor et in range(1, mps_num):\r\n entropy = qr_left_and_right_location(entro_tar, et, 1e-16)[0]\r\n entropy_list.append(entropy)\r\n\r\nfor m in range(mps_num - 2):\r\n average_ = entropy_list[m]\r\n average = average + average_\r\n\r\naverage = average / (mps_num - 1) # 求解平均纠缠熵\r\n\r\ncenter_entropy = qr_left_and_right_location(entro_tar, center_position, 1e-16)[0]\r\nprint('平均纠缠熵是:{}'.format(average))\r\nprint('正交中心为第' + str(center_position) + '个tensor的MPS纠缠熵是:{}'.format(center_entropy))\r\n\r\nfor nn in range(mps_num): # 初始真空零态\r\n ini_state.append(tc.tensor([1, 0], dtype=dtype).reshape(1, 2, 1).to(para['device']))\r\n\r\nread_memory_gate = bfs.load('read_memory_gate_data', 'gate')\r\n\r\nfor vt in range(read_gatenum): # 为了分层优化的下一层结果比单层好,随机初始化小量微扰的单位阵\r\n unitary_gate = read_memory_gate[vt].to(para['device'])\r\n unitary_gate.requires_grad = True\r\n layer_gatelist.append(unitary_gate)\r\n\r\nfor jt in range(gatenum//layer_num):\r\n vol_gate = tc.mul(tc.rand((4, 4), dtype=dtype).to(para['device']), vol)\r\n unitary_gate = tc.add(vol_gate, identity_4)\r\n unitary_gate.requires_grad = True\r\n layer_gatelist.append(unitary_gate)\r\n\r\nmps_norm(ini_state) # 对初始量子态进行归一化\r\n\r\n# lay_optimize_1 = tc.optim.Adam(layer_gatelist, lr=lr) # 分层优化的量子门参数,在分层优化结束之后进行协同优化\r\n\r\nprint('分层储存优化器进入list')\r\n\r\n\r\nfor it in range(gatenum): # 将分层优化的loss的list 根据层数区分开\r\n if it < (gatenum//layer_num)*1:\r\n layer_gatelist_0.append(layer_gatelist[it])\r\n else:\r\n if it < (gatenum//layer_num)*2:\r\n layer_gatelist_1.append(layer_gatelist[it])\r\n else:\r\n if it < (gatenum//layer_num)*3:\r\n layer_gatelist_2.append(layer_gatelist[it])\r\n else:\r\n if it < (gatenum//layer_num)*4:\r\n layer_gatelist_3.append(layer_gatelist[it])\r\n else:\r\n if it < (gatenum//layer_num)*5:\r\n layer_gatelist_4.append(layer_gatelist[it])\r\n else:\r\n layer_gatelist_5.append(layer_gatelist[it])\r\n\r\nlay_optimize_0 = tc.optim.Adam(layer_gatelist_0, lr=lr) # 分层优化的量子门参数,在分层优化结束之后进行协同优化\r\nlay_optimize_1 = tc.optim.Adam(layer_gatelist_1, lr=lr)\r\nlay_optimize_2 = tc.optim.Adam(layer_gatelist_2, lr=lr)\r\n\r\nlayer_optimize.append(lay_optimize_0) # 将三层优化器\r\nlayer_optimize.append(lay_optimize_1)\r\nlayer_optimize.append(lay_optimize_2)\r\n\r\nscheduler_0 = StepLR(lay_optimize_0, step_size=step_size, gamma=0.1)\r\nscheduler_1 = StepLR(lay_optimize_1, step_size=step_size, gamma=0.1)\r\nscheduler_2 = StepLR(lay_optimize_2, step_size=step_size, gamma=0.1)\r\n\r\nscheduler = list()\r\nscheduler.append(scheduler_0)\r\nscheduler.append(scheduler_1)\r\nscheduler.append(scheduler_2)\r\n\r\nevo = ev.Evolve(mps_num, k_bood, 2, gatenum, layer_num)\r\nevo.init_tensor_list(copy.deepcopy(ini_state))\r\n\r\nfor bt in range(layer_num):\r\n print('初始化第' + str(bt) + '的学习率:', layer_optimize[bt].defaults['lr'])\r\n\r\nstart.record() # 开始计算模型的运算时间花费\r\n\r\nfor pt in range(pt_time): # 交错优化所在的次数\r\n fprint('Circle优化位于第' + str(pt) + '次', file=para['log_name'])\r\n for lay_num in range(layer_num):\r\n fprint('Circle优化位于第' + str(lay_num) + '层', file=para['log_name'])\r\n for vt in range(it_time):\r\n for llt in range(lay_num, lay_num + 1): # 先将优化层进行演化,演化完成后将其存进新的list,作为下一层初始\r\n evo.layered_evolve_mps(layer_gatelist, llt)\r\n if vt == it_time - 1:\r\n evo.storage_layer_out_optimization(llt, 0)\r\n for at in range(lay_num + 1, layer_num): # 将不变分的量子门演化进入线路\r\n evo.layered_evolve_mps(layer_gatelist, at)\r\n lay_loss = evo.log_fidelity(tar_mpslist) # 借助了mps跨越指数复杂度的优势\r\n if ((vt + 1) % dt_print) == 0:\r\n if vt == 0:\r\n fprint('block')\r\n else:\r\n fprint('At t = ' + str(vt) + ', loss = ' + str(lay_loss.item()), file=para['log_name'])\r\n loss_[lay_num].append(lay_loss.item())\r\n lay_loss.backward()\r\n layer_optimize[lay_num].step()\r\n layer_optimize[lay_num].zero_grad()\r\n if ((vt + 1) % dt_print) == 0:\r\n fprint(\"第%d个epoch的学习率:%f\" % (vt, layer_optimize[lay_num].param_groups[0]['lr']),\r\n file=para['log_name'])\r\n scheduler[lay_num].step()\r\n tc.cuda.empty_cache() # 删除不必要的变量\r\n if lay_num == layer_num-1:\r\n if vt == it_time - 1:\r\n half_entropy(evo.out_optimization())\r\n if vt == it_time - 1:\r\n evo.read_layer_out_optimization(lay_num, 0)\r\n else:\r\n evo.read_layer_out_optimization(lay_num, 1)\r\n\r\nhalf_entropy(tar_mpslist) # 热图的最后一行为目标态纠缠的信息\r\n\r\nbfs.save('.', 'out_memory_half_entropy_data', [half_entropy_list], ['half_entropy'])\r\n\r\nfor dt in range(gatenum):\r\n zero_gatetensor[dt, :, :] = layer_gatelist[dt].data\r\n\r\nbfs.save('.', 'out_memory_gate_data', [zero_gatetensor], ['gate'])\r\n\r\nout_layer = evo.out_optimization()\r\nout_layer_numpy = list()\r\n\r\nfor nt in range(mps_num): # 将目标MPS转存成numpy数组\r\n out_layer_numpy.append(out_layer[nt].numpy())\r\n\r\nnp.savez(out_file_name,\r\n tar_mpslist0=out_layer_numpy[0], tar_mpslist1=out_layer_numpy[1], tar_mpslist2=out_layer_numpy[2],\r\n tar_mpslist3=out_layer_numpy[3], tar_mpslist4=out_layer_numpy[4], tar_mpslist5=out_layer_numpy[5],\r\n tar_mpslist6=out_layer_numpy[6], tar_mpslist7=out_layer_numpy[7], tar_mpslist8=out_layer_numpy[8],\r\n tar_mpslist9=out_layer_numpy[9],\r\n tar_mpslist10=out_layer_numpy[10], tar_mpslist11=out_layer_numpy[11], tar_mpslist12=out_layer_numpy[12],\r\n tar_mpslist13=out_layer_numpy[13], tar_mpslist14=out_layer_numpy[14], tar_mpslist15=out_layer_numpy[15],\r\n tar_mpslist16=out_layer_numpy[16], tar_mpslist17=out_layer_numpy[17], tar_mpslist18=out_layer_numpy[18],\r\n tar_mpslist19=out_layer_numpy[19],\r\n tar_mpslist20=out_layer_numpy[20], tar_mpslist21=out_layer_numpy[21], tar_mpslist22=out_layer_numpy[22],\r\n tar_mpslist23=out_layer_numpy[23], tar_mpslist24=out_layer_numpy[24], tar_mpslist25=out_layer_numpy[25],\r\n tar_mpslist26=out_layer_numpy[26], tar_mpslist27=out_layer_numpy[27], tar_mpslist28=out_layer_numpy[28],\r\n tar_mpslist29=out_layer_numpy[29],\r\n tar_mpslist30=out_layer_numpy[30], tar_mpslist31=out_layer_numpy[31], tar_mpslist32=out_layer_numpy[32],\r\n tar_mpslist33=out_layer_numpy[33], tar_mpslist34=out_layer_numpy[34], tar_mpslist35=out_layer_numpy[35],\r\n tar_mpslist36=out_layer_numpy[36], tar_mpslist37=out_layer_numpy[37], tar_mpslist38=out_layer_numpy[38],\r\n tar_mpslist39=out_layer_numpy[39],\r\n tar_mpslist40=out_layer_numpy[40], tar_mpslist41=out_layer_numpy[41], tar_mpslist42=out_layer_numpy[42],\r\n tar_mpslist43=out_layer_numpy[43], tar_mpslist44=out_layer_numpy[44], tar_mpslist45=out_layer_numpy[45],\r\n tar_mpslist46=out_layer_numpy[46], tar_mpslist47=out_layer_numpy[47])\r\n\r\nfor nt in range(mps_num): # 将目标MPS转存成numpy数组\r\n tar_mpslist[nt] = tar_mpslist[nt].cpu().numpy()\r\n\r\nend.record() # 截至记录模型花费计算的时间\r\n\r\n# Waits for everything to finish running\r\ntc.cuda.synchronize() # 等待当前设备上所有流中的所有核心完成。\r\n\r\nprint('Runtime: ', start.elapsed_time(end))\r\n\r\nfor i in range(pt_time*5):\r\n x1_axis.append(i*10)\r\n\r\ncolor_list = list(['deeppink', 'red', 'gold', 'black', 'lime', 'peru', 'purple', 'blue'])\r\nplt.figure(num=1, figsize=(16, 12), dpi=100)\r\nplt.tick_params(labelsize=16)\r\nplt.xlabel(\"num of optimize\", fontsize=20) # x轴上的名字\r\nplt.ylabel(\"negative-logarithmic fidelities (NLFs) per site\", fontsize=20)\r\nplt.grid(axis='x', c='g', linestyle='--', alpha=0.5)\r\nfor kt in range(layer_num):\r\n plt.plot(x1_axis, loss_[kt], color=color_list[kt], linewidth=3, label=' Circle layered Optimize' + str(kt))\r\n\r\nplt.legend(prop={'family': 'Times New Roman', 'size': 16}, loc='upper right')\r\nplt.savefig('./MPS_Step_3layer_Circle.jpg')\r\n\r\n\r\n"
] | [
[
"matplotlib.pyplot.legend",
"numpy.savez",
"torch.zeros",
"torch.pow",
"torch.cuda.synchronize",
"torch.norm",
"torch.add",
"torch.sqrt",
"torch.einsum",
"torch.eye",
"torch.from_numpy",
"torch.tensor",
"torch.rand",
"numpy.load",
"matplotlib.pyplot.figure",
"torch.optim.Adam",
"torch.optim.lr_scheduler.StepLR",
"torch.cuda.Event",
"torch.cuda.empty_cache",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.ylabel",
"matplotlib.use",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.tick_params"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
DrJonoG/StomataGSMax | [
"18e5f993ed875ae6af07a4c7d1c0e4ff97e2c947"
] | [
"datasets/DataAugmentations.py"
] | [
"from scipy import ndimage\nfrom skimage import measure\n\nimport numpy as np\nimport cv2\n\n\ndef crop_rectangle(image, rect):\n # rect has to be upright\n num_rows = image.shape[0]\n num_cols = image.shape[1]\n\n if not inside_rect(rect = rect, num_cols = num_cols, num_rows = num_rows):\n print(\"Proposed rectangle is not fully in the image.\")\n return None\n\n rect_center = rect[0]\n rect_center_x = rect_center[0]\n rect_center_y = rect_center[1]\n rect_width = rect[1][0]\n rect_height = rect[1][1]\n\n image = image[rect_center_y-rect_height//2:rect_center_y+rect_height-rect_height//2, rect_center_x-rect_width//2:rect_center_x+rect_width-rect_width//2]\n return image\n\ndef rect_bbx(rect):\n box = cv2.boxPoints(rect)\n\n x_max = int(np.max(box[:,0]))\n x_min = int(np.min(box[:,0]))\n y_max = int(np.max(box[:,1]))\n y_min = int(np.min(box[:,1]))\n\n center = (int((x_min + x_max) // 2), int((y_min + y_max) // 2))\n width = int(x_max - x_min)\n height = int(y_max - y_min)\n angle = 0\n\n return (center, (width, height), angle)\n\ndef inside_rect(rect, num_cols, num_rows):\n rect_center = rect[0]\n rect_center_x = rect_center[0]\n rect_center_y = rect_center[1]\n\n rect_width, rect_height = rect[1]\n\n rect_angle = rect[2]\n\n if (rect_center_x < 0) or (rect_center_x > num_cols):\n return False\n if (rect_center_y < 0) or (rect_center_y > num_rows):\n return False\n\n # https://docs.opencv.org/3.0-beta/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html\n box = cv2.boxPoints(rect)\n\n x_max = int(np.max(box[:,0]))\n x_min = int(np.min(box[:,0]))\n y_max = int(np.max(box[:,1]))\n y_min = int(np.min(box[:,1]))\n\n if (x_max <= num_cols) and (x_min >= 0) and (y_max <= num_rows) and (y_min >= 0):\n return True\n else:\n return False\n\ndef image_rotate_without_crop(mat, angle):\n # https://stackoverflow.com/questions/22041699/rotate-an-image-without-cropping-in-opencv-in-c\n # angle in degrees\n\n height, width = mat.shape[:2]\n image_center = (width/2, height/2)\n\n rotation_mat = cv2.getRotationMatrix2D(image_center, angle, 1)\n\n abs_cos = abs(rotation_mat[0,0])\n abs_sin = abs(rotation_mat[0,1])\n\n bound_w = int(height * abs_sin + width * abs_cos)\n bound_h = int(height * abs_cos + width * abs_sin)\n\n rotation_mat[0, 2] += bound_w/2 - image_center[0]\n rotation_mat[1, 2] += bound_h/2 - image_center[1]\n\n rotated_mat = cv2.warpAffine(mat, rotation_mat, (bound_w, bound_h), flags=cv2.INTER_NEAREST)\n\n return rotated_mat\n\ndef crop_rotated_rectangle(image, rect):\n # Crop a rotated rectangle from a image\n num_rows = image.shape[0]\n num_cols = image.shape[1]\n\n if not inside_rect(rect = rect, num_cols = num_cols, num_rows = num_rows):\n print(\"Proposed rectangle is not fully in the image.\")\n return []\n\n rotated_angle = rect[2]\n\n rect_bbx_upright = rect_bbx(rect = rect)\n rect_bbx_upright_image = crop_rectangle(image = image, rect = rect_bbx_upright)\n\n rotated_rect_bbx_upright_image = image_rotate_without_crop(mat = rect_bbx_upright_image, angle = rotated_angle)\n\n rect_width = rect[1][0]\n rect_height = rect[1][1]\n\n crop_center = (rotated_rect_bbx_upright_image.shape[1]//2, rotated_rect_bbx_upright_image.shape[0]//2)\n\n return rotated_rect_bbx_upright_image[crop_center[1]-rect_height//2 : crop_center[1]+(rect_height-rect_height//2), crop_center[0]-rect_width//2 : crop_center[0]+(rect_width-rect_width//2)]\n\n\ndef adjustment_center(position, half_crop, jitter, upper_bounds):\n # Adjust center position if out of bounds\n if position - (half_crop) <= 0:\n y_low = half_crop\n elif position + (half_crop) >= upper_bounds:\n y_low = upper_bounds - (half_crop)\n else:\n y_low = position\n iteration = 0\n found = False\n while iteration < 50:\n adjustment = (jitter / 50) * iteration\n y_low = y_low * np.random.uniform((1 - jitter) + adjustment, (1 + jitter) - adjustment)\n if y_low - (half_crop) >= 0 and y_low + (half_crop) <= upper_bounds:\n found = True\n break\n iteration += 1\n if not found:\n y_low = position\n return y_low\n"
] | [
[
"numpy.max",
"numpy.random.uniform",
"numpy.min"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
declanwalsh/aero-bumps | [
"823ec1533de585971adacc701b4a0cf7b7b45035"
] | [
"flutter_output.py"
] | [
"# -*- coding: utf-8 -*-\r\n\"\"\"flutter_output\r\n\r\nGenerates graphs, csv's and other files for export of analysis\r\n\r\nMORE DETAILS\r\n\r\n Typical usage example:\r\n\r\n foo = ClassFoo()\r\n bar = foo.FunctionBar()\r\n\r\nTODO\r\n- Add spectrogram of changes in modal frequencies at different airspeeds\r\n\"\"\"\r\n\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n\r\nimport csv\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.ticker as ticker\r\nimport numpy as np\r\n\r\nimport flutter_config as cfg\r\nfrom flutter_config import cfg_analysis\r\n\r\nimport bisect\r\n\r\n# ---------------------------------\r\n# FUNCTIONS - COMPARE RESULTS\r\n# ---------------------------------\r\n\r\n\r\ndef compare_data_acc(results):\r\n\r\n plot_modal_variation_with_airspeed(results, [10, 24])\r\n plot_modal_variation_with_airspeed(results, [30])\r\n\r\n plot_modal_variation_with_airspeed_3D(results, 10, [280, 290, 300, 310, 320, 330, 340, 350])\r\n plot_modal_variation_with_airspeed_3D(results, 24, [330, 340, 350])\r\n plot_modal_variation_with_airspeed_3D(results, 30, [0.68, 0.70, 0.72, 0.74, 0.76, 0.78, 0.80, 0.81])\r\n\r\n if cfg.CALC_DAMPING:\r\n plot_damping_variation_with_airspeed(results, [10, 24])\r\n plot_damping_variation_with_airspeed(results, [30])\r\n\r\n return 1\r\n\r\n\r\ndef plot_damping_variation_with_airspeed(results, altitude_list, title=None, subtitle=None):\r\n\r\n fig, ax = plt.subplots()\r\n min_airspeed = 1000\r\n max_airspeed = 0\r\n altitude_str = \"\"\r\n\r\n for altitude in altitude_list:\r\n for idx in range(len(cfg_analysis.FREQ_FILTER_MODE)):\r\n modal_damping_results, modal_airspeed_results = get_damping_variation_with_airspeed(results, altitude, idx)\r\n\r\n print(modal_damping_results)\r\n print(modal_airspeed_results)\r\n\r\n # case where no modes were detected for frequency and empty list returned\r\n if not modal_airspeed_results or not modal_damping_results:\r\n print(\"No modes for {}\".format(cfg_analysis.FREQ_FILTER_MODE[idx]))\r\n continue\r\n\r\n min_airspeed = min(min(modal_airspeed_results), min_airspeed)\r\n max_airspeed = max(max(modal_airspeed_results), max_airspeed)\r\n\r\n label_str = \"{:.1f}\".format(cfg_analysis.FREQ_FILTER_MODE[idx]) + \" Hz (nom.) @ \" + str(altitude) + \"K\"\r\n # marker='o'\r\n ax.plot(modal_airspeed_results, modal_damping_results, label=label_str, marker=\"*\")\r\n\r\n altitude_str = \"_\" + altitude_str + str(altitude) + \"K\"\r\n\r\n ax.plot([0, 1000], [-0.03, -0.03], linestyle='--', color='red', label=\"Limit\")\r\n\r\n plt.ylabel(\"Structural Damping\")\r\n\r\n if max_airspeed < 2:\r\n plt.xlabel(\"Mach Number\")\r\n else:\r\n plt.xlabel(\"Airspeed (KIAS)\")\r\n\r\n if title is None:\r\n str_title = \"Damping Variation\"\r\n\r\n plt.suptitle(str_title, fontsize=20, y=1)\r\n\r\n if subtitle is None:\r\n subtitle = cfg_analysis.ACC_BASIS_STR\r\n\r\n plt.title(subtitle, fontsize=16)\r\n\r\n tick_spacing = 0.03\r\n\r\n ax.legend()\r\n ax.set_xlim([min_airspeed, max_airspeed])\r\n ax.set_ylim([-0.18, 0])\r\n ax.yaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))\r\n fig.set_size_inches(cfg.FIGURE_WIDTH, cfg.FIGURE_HEIGHT)\r\n plt.show()\r\n\r\n if cfg.SAVE_FIG:\r\n fig.savefig(cfg.IMAGE_FILE_ROOT + cfg_analysis.ANALYSIS_FILE_ROOT +\r\n cfg_analysis.ACC_BASIS_STR + \"_DAMPING\" + altitude_str + \".png\")\r\n\r\n\r\ndef plot_modal_variation_with_airspeed(results, altitude_list, title=None, subtitle=None):\r\n\r\n fig, ax = plt.subplots()\r\n min_airspeed = 1000\r\n max_airspeed = 0\r\n altitude_str = \"\"\r\n\r\n for altitude in altitude_list:\r\n for modal_freq in cfg_analysis.FREQ_FILTER_MODE:\r\n modal_freq_results, modal_airspeed_results = get_modal_variation_with_airspeed(results, altitude, modal_freq)\r\n\r\n # case where no modes were detectec for frequency and empty list returned\r\n if not modal_airspeed_results or not modal_freq_results:\r\n print(\"No modes for {}\".format(modal_freq))\r\n continue\r\n\r\n min_airspeed = min(min(modal_airspeed_results), min_airspeed)\r\n max_airspeed = max(max(modal_airspeed_results), max_airspeed)\r\n\r\n label_str = \"{:.1f}\".format(modal_freq) + \" Hz (nom.) @ \" + str(altitude) + \"K\"\r\n\r\n # marker='o'\r\n ax.plot(modal_airspeed_results, modal_freq_results, label=label_str, marker=\"*\")\r\n\r\n altitude_str = \"_\" + altitude_str + str(altitude) + \"K\"\r\n\r\n plt.ylabel(\"Frequency (Hz)\")\r\n\r\n if max_airspeed < 2:\r\n plt.xlabel(\"Mach Number\")\r\n else:\r\n plt.xlabel(\"Airspeed (KIAS)\")\r\n\r\n if title is None:\r\n str_title = \"Modal Frequency Variation\"\r\n\r\n plt.suptitle(str_title, fontsize=20, y=1)\r\n\r\n if subtitle is None:\r\n subtitle = cfg_analysis.ACC_BASIS_STR\r\n\r\n plt.title(subtitle, fontsize=16)\r\n\r\n ax.legend()\r\n ax.set_xlim([min_airspeed, max_airspeed])\r\n ax.set_ylim([0, 10])\r\n fig.set_size_inches(cfg.FIGURE_WIDTH, cfg.FIGURE_HEIGHT)\r\n plt.show()\r\n\r\n if cfg.SAVE_FIG:\r\n fig.savefig(cfg.IMAGE_FILE_ROOT + cfg_analysis.ANALYSIS_FILE_ROOT +\r\n cfg_analysis.ACC_BASIS_STR + \"_FREQUENCY\" + altitude_str + \".png\")\r\n\r\n\r\ndef plot_modal_variation_with_airspeed_3D(results, altitude, airspeed_values, title=None, subtitle=None):\r\n\r\n fig = plt.figure()\r\n ax = fig.add_subplot(111, projection='3d')\r\n\r\n max_freq = 12\r\n\r\n f_big = []\r\n Gxx_big = []\r\n airspeed_big = []\r\n\r\n altitude_str = \"_\" + str(altitude) + \"K\"\r\n\r\n for airspeed in airspeed_values:\r\n f, Gxx = get_freq_variation_with_airspeed(results, altitude, airspeed, max_freq)\r\n\r\n if len(f) > 0:\r\n airspeed_list = [airspeed]*len(f)\r\n f_big.extend(f)\r\n airspeed_big.extend(airspeed_list)\r\n Gxx_big.extend(Gxx)\r\n ax.plot(f, airspeed_list, Gxx)\r\n\r\n ax.set_ylim(min(airspeed_values), max(airspeed_values))\r\n ax.set_xlim(0, max_freq)\r\n\r\n ax.set_xlabel('Frequency (Hz)')\r\n ax.set_ylabel('Airspeed')\r\n ax.set_zlabel('Amplitude')\r\n\r\n if title is None:\r\n plt.suptitle(\"Modal Frequency Variation @ \" + str(altitude) + \"K\", fontsize=20, y=1)\r\n\r\n fig.set_size_inches(cfg.FIGURE_WIDTH, cfg.FIGURE_HEIGHT)\r\n\r\n plt.draw()\r\n\r\n if cfg.SAVE_FIG:\r\n fig.savefig(cfg.IMAGE_FILE_ROOT + cfg_analysis.ANALYSIS_FILE_ROOT +\r\n cfg_analysis.ACC_BASIS_STR + \"_FREQUENCY_3D_line\" + altitude_str + \".png\")\r\n\r\n fig = plt.figure()\r\n ax = fig.add_subplot(111, projection='3d')\r\n\r\n # surface expects a regular 2D grid structure\r\n # colourmaps = https://matplotlib.org/3.1.0/tutorials/colors/colormaps.html\r\n ax.plot_trisurf(f_big, airspeed_big, Gxx_big, cmap=\"plasma\", antialiased=True)\r\n\r\n ax.set_ylim(min(airspeed_values), max(airspeed_values))\r\n ax.set_xlim(0, max_freq)\r\n\r\n ax.set_xlabel('Frequency (Hz)')\r\n ax.set_ylabel('Airspeed')\r\n ax.set_zlabel('Amplitude')\r\n\r\n if title is None:\r\n plt.suptitle(\"Modal Frequency Variation @ \" + str(altitude) + \"K\", fontsize=20, y=1)\r\n\r\n fig.set_size_inches(cfg.FIGURE_WIDTH, cfg.FIGURE_HEIGHT)\r\n\r\n plt.draw()\r\n\r\n if cfg.SAVE_FIG:\r\n fig.savefig(cfg.IMAGE_FILE_ROOT + cfg_analysis.ANALYSIS_FILE_ROOT +\r\n cfg_analysis.ACC_BASIS_STR + \"_FREQUENCY_3D_shaded\" + altitude_str + \".png\")\r\n\r\n return fig, ax\r\n\r\n\r\ndef get_freq_variation_with_airspeed(results, altitude, airspeed, max_freq):\r\n\r\n f = []\r\n Gxx = []\r\n\r\n for test_point in results:\r\n if test_point[\"altitude\"] == altitude and test_point[\"airspeed\"] == airspeed:\r\n f_results = test_point[\"f\"]\r\n Gxx_results = test_point[\"Gxx\"]\r\n\r\n f = f_results\r\n Gxx = Gxx_results\r\n\r\n idx_max_freq = bisect.bisect(f, max_freq)\r\n f = f[:idx_max_freq]\r\n Gxx = Gxx[:idx_max_freq]\r\n\r\n return f, Gxx\r\n\r\n\r\ndef get_damping_variation_with_airspeed(results, altitude, modal_freq_idx):\r\n\r\n damping_ratio = []\r\n modal_airspeed = []\r\n\r\n for test_point in results:\r\n if test_point[\"altitude\"] == altitude:\r\n\r\n damping_ratio_results = test_point[\"damping_modal_ratio\"]\r\n\r\n damping_ratio.append(-2*damping_ratio_results[modal_freq_idx])\r\n modal_airspeed.append(test_point[\"airspeed\"])\r\n\r\n return damping_ratio, modal_airspeed\r\n\r\n\r\ndef get_modal_variation_with_airspeed(results, altitude, modal_freq_of_interest):\r\n\r\n modal_freq = []\r\n modal_airspeed = []\r\n\r\n for test_point in results:\r\n if test_point[\"altitude\"] == altitude:\r\n\r\n modal_freq_match = get_closest_match(test_point[\"modal_freq\"],\r\n modal_freq_of_interest, cfg_analysis.FREQ_FILTER_VARIATION)\r\n\r\n if modal_freq_match is not None:\r\n modal_freq.append(modal_freq_match)\r\n modal_airspeed.append(test_point[\"airspeed\"])\r\n\r\n return modal_freq, modal_airspeed\r\n\r\n\r\ndef get_closest_match(data, target, limit):\r\n \"\"\"Returns the closest value in a list to a target within a limit\r\n Returns none if no values in the list are within the limit to the target\r\n \"\"\"\r\n\r\n closest = None\r\n\r\n # TODO - this might be able to be skipped over more efficiently\r\n min_difference = abs(target - limit)\r\n\r\n for value in data:\r\n difference = abs(value - target)\r\n if difference < min_difference and difference < limit:\r\n min_difference = difference\r\n closest = value\r\n\r\n return closest\r\n\r\n\r\n# ---------------------------------\r\n# FUNCTIONS - PLOTTING\r\n# ---------------------------------\r\n\r\ndef plot_value_variation_with_airspeed(airspeed, data, legend_str, title_str):\r\n \"\"\" damping and airspeed should be array of arrays\r\n each array is a different test point\r\n \"\"\"\r\n # TODO assert(len(airspeed) == len(damping))\r\n\r\n fig, ax = plt.subplots()\r\n\r\n for idx in len(airspeed):\r\n ax.plot(airspeed[idx], data[idx], label=legend_str[idx])\r\n\r\n\r\ndef extract_relevant_value(data_list, acceptable_range):\r\n\r\n relevant_value = None\r\n\r\n for value in data_list:\r\n if value >= acceptable_range[0] and value <= acceptable_range[1]:\r\n if relevant_value is None:\r\n relevant_value = value\r\n else:\r\n print(\"More than one value in the data list falls within range - returning None\")\r\n return None\r\n\r\n return relevant_value\r\n\r\n\r\ndef plot_histogram(data):\r\n \"\"\"Plots simple histogram of data\"\"\"\r\n\r\n plt.hist(data, bins='auto') # arguments are passed to np.histogram\r\n plt.title(\"Histogram of data\")\r\n plt.ylabel(\"Counts in sample\")\r\n plt.xlabel(\"Signal (automatically binned)\")\r\n plt.show()\r\n\r\n\r\ndef welch_plot(f, Gxx, f_max, Gxx_max, title=None, subtitle=None):\r\n \"\"\"Plots the frequency domain of the signal\"\"\"\r\n # TODO - make this handle maximum values nicer\r\n\r\n fig, ax = plt.subplots()\r\n # marker='o'\r\n ax.plot(f, Gxx, label=\"Signal\")\r\n ax.set_xlim([0, 50])\r\n\r\n # ax.set_yscale('log')\r\n # ax.set_ylim([10**-4,10**2])\r\n plt.ylabel(\"Relative strength\")\r\n plt.xlabel(\"Frequency (Hz)\")\r\n\r\n if title is None:\r\n str_title = \"PSD of Data\"\r\n else:\r\n str_title = \"PSD of \" + title\r\n\r\n plt.suptitle(str_title, fontsize=20, y=1)\r\n\r\n if subtitle is not None:\r\n plt.title(subtitle, fontsize=16)\r\n\r\n plt.plot(f_max, Gxx_max, \"x\", label=\"Peaks\")\r\n ax.legend(loc='upper right')\r\n fig.set_size_inches(cfg.FIGURE_WIDTH, cfg.FIGURE_HEIGHT)\r\n plt.show()\r\n\r\n if cfg.SAVE_FIG:\r\n fig.savefig(cfg.IMAGE_FILE_ROOT + cfg_analysis.ANALYSIS_FILE_ROOT + title + \"_FREQ\" + \".png\")\r\n\r\n\r\ndef plot_acc(data, time, title=None, peaks_idx=None, fileref=None,\r\n subtitle=None, limits=None, save_image=True, filtered_image=False):\r\n \"\"\"plots time varying data using Matplotlib\"\"\"\r\n\r\n # TODO - colour extracted section different (to accout for the 1 second on either side)\r\n fig, ax = plt.subplots()\r\n ax.plot(time, data, label=\"Signal\")\r\n plt.ylabel(\"Signal (V or g's)\")\r\n plt.xlabel(\"Time (s)\")\r\n if title is None:\r\n plt.suptitle(\"Signal Variation with Time (raw)\")\r\n title = fileref\r\n else:\r\n plt.suptitle(\"Signal of \" + title, fontsize=20, y=1)\r\n\r\n if subtitle is not None:\r\n if filtered_image:\r\n plt.title(\"Filtered between: \" + subtitle + \" (Hz)\", fontsize=16)\r\n else:\r\n plt.title(subtitle, fontsize=16)\r\n\r\n if peaks_idx is not None:\r\n ax.plot(time[peaks_idx[0]], data[peaks_idx[0]], \"x\", label=\"Identified peaks\")\r\n for i in list(range(len(peaks_idx[0]))):\r\n ax.annotate(i, (time[peaks_idx[0][i]], data[peaks_idx[0][[i]]]),\r\n textcoords=\"offset points\", xytext=(0, 10), ha=\"center\")\r\n\r\n if limits is not None:\r\n ax.set(ylim=limits)\r\n\r\n ax.legend(loc='upper right')\r\n fig.set_size_inches(cfg.FIGURE_WIDTH, cfg.FIGURE_HEIGHT)\r\n\r\n plt.show()\r\n\r\n if cfg.SAVE_FIG and save_image:\r\n if filtered_image:\r\n fig.savefig(cfg.IMAGE_FILE_ROOT + cfg_analysis.ANALYSIS_FILE_ROOT +\r\n cfg.FILTERED_IMAGE_FILE_ROOT + title + subtitle + \"_FILTERED\" + \".png\")\r\n else:\r\n fig.savefig(cfg.IMAGE_FILE_ROOT + cfg_analysis.ANALYSIS_FILE_ROOT + title + \"_TIME\" + \".png\")\r\n\r\n return plt\r\n\r\n\r\ndef plot_atmosphere(altitude, time, temperature=None, fig=None, fileref=None):\r\n \"\"\"Plots atmosphere data from test data\r\n Overlays on a vibration profile (if one is provided) or creates new graph (if none is provided)\r\n \"\"\"\r\n\r\n if fig is None:\r\n fig, ax = plt.subplots()\r\n\r\n ax.plot(time, altitude, label=\"Altitude\")\r\n plt.ylabel(\"Pressure Altitude (ft)\")\r\n plt.xlabel(\"Time (s)\")\r\n\r\n return None\r\n\r\n\r\n# ---------------------------------\r\n# FUNCTIONS - CSV\r\n# ---------------------------------\r\n\r\n\r\ndef save_csv_output(data, filename):\r\n \"\"\"Saves the data out as a csv\r\n saves in rows instead of columns as easier to work with\r\n \"\"\"\r\n\r\n print(f\"Saving csv with data to {filename}.csv\")\r\n\r\n filename_complete = cfg.OUTPUT_FILE_ROOT + filename + \".csv\"\r\n with open(filename_complete, mode='w', newline='') as csv_file:\r\n csv_writer = csv.writer(csv_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\r\n for cols in data:\r\n csv_writer.writerow(cols)\r\n\r\n print(\"CSV saved.\")\r\n\r\n return 1\r\n"
] | [
[
"matplotlib.ticker.MultipleLocator",
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.draw",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.suptitle",
"matplotlib.pyplot.show",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
RicardoP0/multimodal-matchmap | [
"aa44c574a57073833004172734394882889d8d3b"
] | [
"dataset_preproc/preproc_audio/generate_spectogram.py"
] | [
"# %%\nimport pandas as pd\nimport librosa\nimport librosa.display\nimport os\nimport numpy as np\nimport joblib\n\n\ndef scale_minmax(X, min=0.0, max=1.0):\n X_std = (X - X.min()) / (X.max() - X.min())\n X_scaled = X_std * (max - min) + min\n return X_scaled\n\n\ndef gen_melspect(\n file_path,\n output_name,\n sr=None,\n n_fft=2048,\n n_mels=128,\n win_length=None,\n hop_length=512,\n min_dur=8.0,\n output_length=251,\n image=False,\n dataset=\"iemocap\",\n deltas=False,\n start=None,\n end=None,\n means=None,\n stds=None,\n):\n\n y, sr = librosa.load(file_path, sr=sr)\n if means is not None:\n y = (y - means) / stds\n if start is not None:\n y = y[int(start * sr) : int(end * sr)]\n\n def pad(a, i):\n return a[0:i] if a.shape[0] > i else np.hstack((a, np.zeros(i - a.shape[0])))\n\n def trim_pad_sample(x):\n samples = []\n duration_s = x.shape[0] / float(sr)\n if duration_s < min_dur:\n samples.append(pad(x, int(sr * min_dur)))\n\n elif duration_s / min_dur > 2 or (duration_s / min_dur) % 1 > 0.65:\n pos = int(min_dur * sr)\n samples = []\n samples.append(x[:pos])\n x = x[pos:]\n dur_s = x.shape[0] / sr\n if dur_s / min_dur > 2 or (dur_s / min_dur) % 1 > 0.65:\n\n def append_sample(lst):\n temp = []\n for item in lst:\n if len(item) > 1 and type(item) == list:\n temp.append(item)\n else:\n temp.append(item)\n return temp\n\n for item in append_sample(trim_pad_sample(x)):\n samples.append(item)\n else:\n\n x = x[: int(min_dur * float(sr))]\n samples.append(x)\n return samples\n\n if dataset == \"iemocap\":\n samples = trim_pad_sample(y)\n else:\n duration_s = y.shape[0] / float(sr)\n if duration_s > min_dur:\n y = y[: int(min_dur * sr)]\n samples = [y]\n\n k = 0\n for item in samples:\n y = item\n res = librosa.feature.melspectrogram(\n y,\n sr=sr,\n n_fft=n_fft,\n n_mels=n_mels,\n win_length=win_length,\n hop_length=hop_length,\n window=\"hamming\",\n fmin=300,\n fmax=8000,\n )\n res = librosa.power_to_db(res, np.max)\n\n if res.shape[1] > output_length:\n res = res[:, :output_length]\n # print(mfccs.shape)\n elif res.shape[1] < output_length:\n res = np.pad(res, ((0, 0), (0, output_length - res.shape[1])), \"constant\")\n\n if deltas:\n logmel_delta = librosa.feature.delta(res)\n deltadelta = librosa.feature.delta(res, order=2)\n if means is not None:\n res = librosa.util.normalize(res)\n logmel_delta = librosa.util.normalize(logmel_delta)\n deltadelta = librosa.util.normalize(deltadelta)\n\n res = np.stack([res, logmel_delta, deltadelta])\n\n joblib.dump(res, output_name.format(k))\n k += 1\n\n\n# %%\n\n\nif __name__ == \"__main__\":\n n_mels = 128 # number of bins in spectrogram. Height of image\n # time_steps = 384 # number of time-steps. Width of image\n n_fft = 2048\n hop_length = 512 # 1524 # number of samples per time-step in spectrogram\n win_length = 128 # n_fft512\n min_dur = 8.0\n dataset = \"iemocap\"\n grayscale = True\n mlst = []\n if dataset == \"iemocap\":\n \"\"\"\n pd.Series(mlst).describe()\n count 2170.000000\n mean 4.379649\n std 3.415235\n min 0.779937\n 25% 2.109938\n 50% 3.259937\n 75% 5.667500\n max 34.138750\n dtype: float64\n \"\"\"\n # load audio. Using example from librosa\n print(os.getcwd())\n source_path = \"IEMOCAP_full_release.tar/IEMOCAP_full_release/Session{}/sentences/wav/\"\n dest_path = \"datasets/IEMOCAP/LOGMEL_DELTAS/\"\n\n df = pd.read_csv(\"df_iemocap.csv\")\n processed_files = []\n for _, row in df.iterrows():\n if row.name in processed_files:\n continue\n sess_path = source_path.format(row.wav_file[4])\n folder = row.wav_file[:-5]\n source_file = os.path.join(sess_path, folder, row.wav_file + \".wav\")\n\n if not os.path.exists(dest_path + folder):\n os.makedirs(dest_path + folder)\n\n # print('dest',dest_path + i)\n # print('source',file_path)\n sr = 16000\n preemph_coef = 0.97\n sample_rate = sr\n window_size = 0.025\n window_stride = 0.01\n num_mel_bins = 40\n\n n_fft = 512 # int(sample_rate * window_size)\n win_length = int(sample_rate * window_size) # None#\n hop_length = int(sample_rate * window_stride) # 256#\n\n same_rows = df[df.wav_file == row.wav_file]\n init_start = 0.0\n for _, i in same_rows.iterrows():\n file_name = i.wav_file + \"_\" + str(i.name)\n out = dest_path + folder + \"/\" + file_name + \"_{}.joblib\"\n end = i.end_time - i.start_time + init_start\n\n gen_melspect(\n source_file,\n out,\n sr=sr,\n min_dur=3.0,\n output_length=300,\n dataset=dataset,\n n_fft=n_fft,\n win_length=win_length,\n hop_length=hop_length,\n n_mels=num_mel_bins,\n deltas=True,\n start=init_start,\n end=end,\n )\n init_start = end\n processed_files.append(i.name)\n"
] | [
[
"pandas.read_csv",
"numpy.zeros",
"numpy.pad",
"numpy.stack"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
TabQ/gugu | [
"5b07beeddf51bc981f9624e17b53f1bfd4e9080f"
] | [
"gugu/reference.py"
] | [
"# -*- coding:utf-8 -*-\n\"\"\"\n投资参考类\nCreated on 2019/01/03\n@author: TabQ\n@group : gugu\n@contact: [email protected]\n\"\"\"\n\nfrom __future__ import division\n\nimport math\nimport time\nimport pandas as pd\nfrom pandas.compat import StringIO\nimport lxml.html\nfrom lxml import etree\nimport re\nimport json\nfrom gugu.utility import Utility\nfrom gugu.base import Base, cf\n\nclass Reference(Base):\n def distriPlan(self, year=2015, top=25, retry=3, pause=0.001):\n \"\"\"\n 获取分配预案数据\n Parameters\n --------\n year:年份\n top:取最新n条数据,默认取最近公布的25条\n retry : int, 默认 3\n 如遇网络等问题重复执行的次数 \n pause : int, 默认 0.001\n 重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题\n \n returns\n -------\n DataFrame or List: [{'code', 'name', ...}, ...]\n code:股票代码\n name:股票名称\n year:分配年份\n report_date:公布日期\n divi:分红金额(每10股)\n shares:转增和送股数(每10股)\n \"\"\"\n self._data = pd.DataFrame()\n \n if top == 'all':\n self._writeHead()\n \n self._data, pages = self.__handleDistriPlan(year, 0, retry, pause)\n for i in range(1, int(pages)):\n self._data = self._data.append(self.__handleDistriPlan(year, i, retry, pause), ignore_index=True)\n \n return self._result()\n elif top <= 25:\n self._data, pages = self.__handleDistriPlan(year, 0, retry, pause)\n self._data = self._data.head(top)\n \n return self._result()\n else:\n if isinstance(top, int):\n self._writeHead()\n \n allPages = int(math.ceil(top/25))\n self._data, pages = self.__handleDistriPlan(year, 0, retry, pause)\n pages = min(allPages, int(pages))\n for i in range(1, pages):\n self._data = self._data.append(self.__handleDistriPlan(year, i, retry, pause), ignore_index=True)\n \n self._data = self._data.head(top)\n \n return self._result()\n else:\n print(cf.TOP_PARAS_MSG)\n \n \n def __handleDistriPlan(self, year, pageNo, retry, pause):\n for _ in range(retry):\n time.sleep(pause)\n \n try:\n if pageNo > 0:\n self._writeConsole()\n \n # http://quotes.money.163.com/data/caibao/fpyg.html?reportdate=2018&sort=declaredate&order=desc&page=0\n html = lxml.html.parse(cf.DP_163_URL % (year, pageNo)) \n res = html.xpath('//table[@class=\\\"fn_cm_table\\\"]/tr')\n if self._PY3:\n sarr = [etree.tostring(node).decode('utf-8') for node in res]\n else:\n sarr = [etree.tostring(node) for node in res]\n sarr = ''.join(sarr)\n sarr = '<table>%s</table>' % sarr\n df = pd.read_html(sarr)[0]\n df = df.drop(0, axis=1)\n df.columns = cf.DP_163_COLS\n df['divi'] = df['plan'].map(self.__bonus)\n df['shares'] = df['plan'].map(self.__gift)\n df = df.drop('plan', axis=1)\n df['code'] = df['code'].astype(object)\n df['code'] = df['code'].map(lambda x : str(x).zfill(6))\n pages = []\n if pageNo == 0:\n page = html.xpath('//div[@class=\\\"mod_pages\\\"]/a')\n if len(page)>1:\n asr = page[len(page)-2]\n pages = asr.xpath('text()')\n except Exception as e:\n print(e)\n else:\n if pageNo == 0:\n return df, pages[0] if len(pages)>0 else 0\n else:\n return df\n \n raise IOError(cf.NETWORK_URL_ERROR_MSG)\n \n \n def __bonus(self, x):\n if self._PY3:\n reg = re.compile(r'分红(.*?)元', re.UNICODE)\n res = reg.findall(x)\n return 0 if len(res)<1 else float(res[0]) \n else:\n if isinstance(x, unicode):\n s1 = unicode('分红','utf-8')\n s2 = unicode('元','utf-8')\n reg = re.compile(r'%s(.*?)%s'%(s1, s2), re.UNICODE)\n res = reg.findall(x)\n return 0 if len(res)<1 else float(res[0])\n else:\n return 0\n \n \n def __gift(self, x):\n if self._PY3:\n reg1 = re.compile(r'转增(.*?)股', re.UNICODE)\n reg2 = re.compile(r'送股(.*?)股', re.UNICODE)\n res1 = reg1.findall(x)\n res2 = reg2.findall(x)\n res1 = 0 if len(res1)<1 else float(res1[0])\n res2 = 0 if len(res2)<1 else float(res2[0])\n \n return res1 + res2\n else:\n if isinstance(x, unicode):\n s1 = unicode('转增','utf-8')\n s2 = unicode('送股','utf-8')\n s3 = unicode('股','utf-8')\n reg1 = re.compile(r'%s(.*?)%s'%(s1, s3), re.UNICODE)\n reg2 = re.compile(r'%s(.*?)%s'%(s2, s3), re.UNICODE)\n res1 = reg1.findall(x)\n res2 = reg2.findall(x)\n res1 = 0 if len(res1)<1 else float(res1[0])\n res2 = 0 if len(res2)<1 else float(res2[0])\n \n return res1 + res2\n else:\n return 0\n \n \n def forecast(self, year, quarter, retry=3, pause=0.001):\n \"\"\"\n 获取业绩预告数据\n Parameters\n --------\n year:int 年度 e.g:2014\n quarter:int 季度 :1、2、3、4,只能输入这4个季度\n 说明:由于是从网站获取的数据,需要一页页抓取,速度取决于您当前网络速度\n retry : int, 默认 3\n 如遇网络等问题重复执行的次数 \n pause : int, 默认 0.001\n 重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题 \n Return\n --------\n DataFrame or List: [{'code':, 'name':, ...}, ...]\n code,代码\n name,名称\n type,业绩变动类型【预增、预亏等】\n report_date,发布日期\n pre_eps,上年同期每股收益\n range,业绩变动范围\n \"\"\"\n self._data = pd.DataFrame()\n \n if Utility.checkQuarter(year, quarter) is True:\n self._writeHead()\n self._data = self.__handleForecast(year, quarter, 1, pd.DataFrame(), retry, pause)\n self._data = pd.DataFrame(self._data, columns=cf.FORECAST_COLS)\n self._data['code'] = self._data['code'].map(lambda x: str(x).zfill(6))\n \n return self._result()\n \n \n def __handleForecast(self, year, quarter, pageNo, dataArr, retry, pause):\n self._writeConsole()\n \n for _ in range(retry):\n time.sleep(pause)\n \n try:\n # http://vip.stock.finance.sina.com.cn/q/go.php/vFinanceAnalyze/kind/performance/index.phtml?s_i=&s_a=&s_c=&s_type=&reportdate=2018&quarter=3&p=1&num=60\n request = self._session.get( cf.FORECAST_URL%( year, quarter, pageNo, cf.PAGE_NUM[1]), timeout=10 )\n request.encoding = 'gbk'\n text = request.text.replace('--', '')\n html = lxml.html.parse(StringIO(text))\n res = html.xpath(\"//table[@class=\\\"list_table\\\"]/tr\")\n if self._PY3:\n sarr = [etree.tostring(node).decode('utf-8') for node in res]\n else:\n sarr = [etree.tostring(node) for node in res]\n sarr = ''.join(sarr)\n sarr = '<table>%s</table>'%sarr\n df = pd.read_html(sarr)[0]\n df = df.drop([4, 5, 8], axis=1)\n df.columns = cf.FORECAST_COLS\n dataArr = dataArr.append(df, ignore_index=True)\n nextPage = html.xpath('//div[@class=\\\"pages\\\"]/a[last()]/@onclick')\n if len(nextPage)>0:\n pageNo = re.findall(r'\\d+',nextPage[0])[0]\n return self.__handleForecast(year, quarter, pageNo, dataArr, retry, pause)\n else:\n return dataArr\n except Exception as e:\n print(e)\n \n raise IOError(cf.NETWORK_URL_ERROR_MSG)\n \n \n def restrictedLift(self, year=None, month=None, retry=3, pause=0.001):\n \"\"\"\n 获取限售股解禁数据\n Parameters\n --------\n year:年份,默认为当前年\n month:解禁月份,默认为当前月\n retry : int, 默认 3\n 如遇网络等问题重复执行的次数 \n pause : int, 默认 0\n 重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题\n \n Return\n ------\n DataFrame or List: [{'code':, 'name':, ...}, ...]\n code:股票代码\n name:名称\n date:解禁日期\n count:解禁数量(万股)\n ratio:占总盘比率\n \"\"\"\n self._data = pd.DataFrame()\n \n year = Utility.getYear() if year is None else year\n month = Utility.getMonth() if month is None else month\n \n for _ in range(retry):\n time.sleep(pause)\n \n try:\n # http://datainterface.eastmoney.com/EM_DataCenter/JS.aspx?type=FD&sty=BST&st=3&sr=true&fd=2019&stat=1\n request = self._session.get( cf.RL_URL % (year, month), timeout = 10 )\n if self._PY3:\n request.encoding = 'utf-8'\n lines = request.text\n except Exception as e:\n print(e)\n else:\n da = lines[3:len(lines)-3]\n list = []\n for row in da.split('\",\"'):\n list.append([data for data in row.split(',')])\n self._data = pd.DataFrame(list)\n self._data = self._data[[1, 3, 4, 5, 6]]\n for col in [5, 6]:\n self._data[col] = self._data[col].astype(float)\n self._data[5] = self._data[5]/10000\n self._data[6] = self._data[6]*100\n self._data[5] = self._data[5].map(cf.FORMAT)\n self._data[6] = self._data[6].map(cf.FORMAT)\n self._data.columns = cf.RL_COLS\n \n return self._result()\n \n raise IOError(cf.NETWORK_URL_ERROR_MSG)\n\n\n def fundHoldings(self, year, quarter, retry=3, pause=0.001):\n \"\"\"\n 获取基金持股数据\n Parameters\n --------\n year:年份e.g 2014\n quarter:季度(只能输入1,2,3,4这个四个数字)\n retry : int, 默认 3\n 如遇网络等问题重复执行的次数 \n pause : int, 默认 0\n 重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题\n \n Return\n ------\n DataFrame or List: [{'code':, 'name':, ...}, ...]\n code:股票代码\n name:名称\n date:报告日期\n nums:基金家数\n nlast:与上期相比(增加或减少了)\n count:基金持股数(万股)\n clast:与上期相比\n amount:基金持股市值\n ratio:占流通盘比率\n \"\"\"\n self._data = pd.DataFrame()\n \n start, end = cf.QUARTS_DIC[str(quarter)]\n if quarter == 1:\n start = start % str(year-1)\n end = end % year\n else:\n start, end = start % year, end % year\n\n self._writeHead()\n\n self._data, pages = self.__handleFoundHoldings(start, end, 0, retry, pause)\n for idx in range(1, pages):\n self._data = self._data.append(self.__handleFoundHoldings(start, end, idx, retry, pause), ignore_index=True)\n\n return self._result()\n\n\n def __handleFoundHoldings(self, start, end, pageNo, retry, pause):\n for _ in range(retry):\n time.sleep(pause)\n if pageNo>0:\n self._writeConsole()\n try:\n # http://quotes.money.163.com/hs/marketdata/service/jjcgph.php?host=/hs/marketdata/service/jjcgph.php&page=0&query=start:2018-06-30;end:2018-09-30&order=desc&count=60&type=query&req=73259\n request = self._session.get( cf.FUND_HOLDS_URL % (pageNo, start, end, Utility.random(5)), timeout=10 )\n if self._PY3:\n request.encoding = 'utf-8'\n lines = request.text\n lines = lines.replace('--', '0')\n lines = json.loads(lines)\n data = lines['list']\n df = pd.DataFrame(data)\n df = df.drop(['CODE', 'ESYMBOL', 'EXCHANGE', 'NAME', 'RN', 'SHANGQIGUSHU', 'SHANGQISHIZHI', 'SHANGQISHULIANG'], axis=1)\n for col in ['GUSHU', 'GUSHUBIJIAO', 'SHIZHI', 'SCSTC27']:\n df[col] = df[col].astype(float)\n df['SCSTC27'] = df['SCSTC27']*100\n df['GUSHU'] = df['GUSHU']/10000\n df['GUSHUBIJIAO'] = df['GUSHUBIJIAO']/10000\n df['SHIZHI'] = df['SHIZHI']/10000\n df['GUSHU'] = df['GUSHU'].map(cf.FORMAT)\n df['GUSHUBIJIAO'] = df['GUSHUBIJIAO'].map(cf.FORMAT)\n df['SHIZHI'] = df['SHIZHI'].map(cf.FORMAT)\n df['SCSTC27'] = df['SCSTC27'].map(cf.FORMAT)\n df.columns = cf.FUND_HOLDS_COLS\n df = df[['code', 'name', 'date', 'nums', 'nlast', 'count', \n 'clast', 'amount', 'ratio']]\n except Exception as e:\n print(e)\n else:\n if pageNo == 0:\n return df, int(lines['pagecount'])\n else:\n return df\n\n raise IOError(cf.NETWORK_URL_ERROR_MSG)\n\n\n def ipo(self, retry=3, pause=0.001):\n \"\"\"\n 获取新股上市数据\n Parameters\n --------\n retry : int, 默认 3\n 如遇网络等问题重复执行的次数 \n pause : int, 默认 0\n 重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题\n \n Return\n ------\n DataFrame or List: [{'code':, 'name':, ...}, ...]\n code:股票代码\n xcode:申购代码\n name:名称\n ipo_date:上网发行日期\n issue_date:上市日期\n amount:发行数量(万股)\n markets:上网发行数量(万股)\n price:发行价格(元)\n pe:发行市盈率\n limit:个人申购上限(万股)\n funds:募集资金(亿元)\n ballot:网上中签率(%)\n \"\"\"\n self._data = pd.DataFrame()\n\n self._writeHead()\n\n self._data = self.__handleIpo(self._data, 1, retry, pause)\n\n return self._result()\n\n\n def __handleIpo(self, data, pageNo, retry, pause):\n self._writeConsole()\n\n for _ in range(retry):\n time.sleep(pause)\n\n try:\n # http://vip.stock.finance.sina.com.cn/corp/view/vRPD_NewStockIssue.php?page=1&cngem=0&orderBy=NetDate&orderType=desc\n html = lxml.html.parse(cf.NEW_STOCKS_URL % pageNo)\n res = html.xpath('//table[@id=\\\"NewStockTable\\\"]/tr')\n if not res:\n return data\n \n if self._PY3:\n sarr = [etree.tostring(node).decode('utf-8') for node in res]\n else:\n sarr = [etree.tostring(node) for node in res]\n sarr = ''.join(sarr)\n sarr = sarr.replace('<font color=\"red\">*</font>', '')\n sarr = '<table>%s</table>'%sarr\n df = pd.read_html(StringIO(sarr), skiprows=[0, 1])[0]\n df = df.drop([df.columns[idx] for idx in [12, 13, 14, 15]], axis=1)\n df.columns = cf.NEW_STOCKS_COLS\n df['code'] = df['code'].map(lambda x : str(x).zfill(6))\n df['xcode'] = df['xcode'].map(lambda x : str(x).zfill(6))\n res = html.xpath('//table[@class=\\\"table2\\\"]/tr[1]/td[1]/a/text()')\n tag = '下一页' if self._PY3 else unicode('下一页', 'utf-8')\n hasNext = True if tag in res else False \n data = data.append(df, ignore_index=True)\n pageNo += 1\n if hasNext:\n data = self.__handleIpo(data, pageNo, retry, pause)\n except Exception as ex:\n print(ex)\n else:\n return data\n \n \n def shMargins(self, retry=3, pause=0.001):\n \"\"\"\n 沪市融资融券历史数据\n Parameters\n --------\n retry : int, 默认 3\n 如遇网络等问题重复执行的次数 \n pause : int, 默认 0\n 重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题\n \n Return\n ------\n DataFrame or List: [{'date':, 'close':, ...}, ...]\n date: 日期\n close: 上证指数收盘点数\n zdf: 上证指数收盘涨跌幅(%)\n rzye: 融资余额(元)\n rzyezb: 融资余额占比(%)\n rzmre: 融资买入额(元)\n rzche: 融资偿还额(元)\n rzjmre: 融资净买入额(元)\n rqye: 融券余额(元)\n rqyl: 融券余量(股)\n rqmcl: 融券卖出量(股)\n rqchl: 融券偿还量(股)\n rqjmcl: 融券净卖出量(股)\n rzrqye: 融资融券余额(元)\n rzrqyecz: 融资融券余额差值(元)\n \"\"\"\n self._data = pd.DataFrame()\n \n self._writeHead()\n \n self._data = self.__handleMargins(self._data, 1, 'SH', Utility.random(8), cf.MAR_COLS, retry, pause)\n self._data.rename(columns={'tdate':'date'}, inplace=True)\n \n return self._result()\n \n \n def szMargins(self, retry=3, pause=0.001):\n \"\"\"\n 深市融资融券历史数据\n Parameters\n --------\n retry : int, 默认 3\n 如遇网络等问题重复执行的次数 \n pause : int, 默认 0\n 重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题\n \n Return\n ------\n DataFrame or List: [{'date':, 'close':, ...}, ...]\n date: 日期\n close: 深证成指收盘点数\n zdf: 深证成指收盘涨跌幅(%)\n rzye: 融资余额(元)\n rzyezb: 融资余额占比(%)\n rzmre: 融资买入额(元)\n rzche: 融资偿还额(元)\n rzjmre: 融资净买入额(元)\n rqye: 融券余额(元)\n rqyl: 融券余量(股)\n rqmcl: 融券卖出量(股)\n rqchl: 融券偿还量(股)\n rqjmcl: 融券净卖出量(股)\n rzrqye: 融资融券余额(元)\n rzrqyecz: 融资融券余额差值(元)\n \"\"\"\n self._data = pd.DataFrame()\n \n self._writeHead()\n \n self._data = self.__handleMargins(self._data, 1, 'SZ', Utility.random(8), cf.MAR_COLS, retry, pause)\n self._data.rename(columns={'tdate':'date'}, inplace=True)\n \n return self._result()\n \n \n def __handleMargins(self, dataArr, page, market, randInt, column, retry, pause):\n self._writeConsole()\n \n for _ in range(retry):\n time.sleep(pause)\n \n try:\n request = self._session.get( cf.MAR_URL % (page, market, randInt) )\n text = request.text.split('=')[1]\n text = text.replace('{pages:', '{\"pages\":').replace(',data:', ',\"data\":').replace('T00:00:00', '').replace('\"-\"', '0')\n dataDict = Utility.str2Dict(text)\n data = dataDict['data']\n df = pd.DataFrame(data, columns=column)\n \n df['close'] = df['close'].map(cf.FORMAT)\n df['rzyezb'] = df['rzyezb'].astype(float)\n \n dataArr = dataArr.append(df, ignore_index=True)\n if page < dataDict['pages']:\n dataArr = self.__handleMargins(dataArr, page+1, market, randInt, column, retry, pause)\n except Exception as e:\n print(e)\n else:\n return dataArr\n \n raise IOError(cf.NETWORK_URL_ERROR_MSG)\n \n \n def marginDetailsAllByDate(self, date, retry=3, pause=0.001):\n \"\"\"\n 按日期获取两市融资融券明细列表\n Parameters\n --------\n date : string\n 选择日期 format:YYYY-MM-DD\n retry : int, 默认 3\n 如遇网络等问题重复执行的次数 \n pause : int, 默认 0\n 重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题\n \n Return\n ------\n DataFrame or List: [{'code':, 'name':, ...}, ...]\n code: 股票代码\n name: 名称\n rzye: 当日融资余额(元)\n rzyezb: 当日融资余额占比(%)\n rzmre: 当日融资买入额(元)\n rzche: 当日融资偿还额(元)\n rzjmre: 当日融资净买入额(元)\n rqye: 当日融券余额(元)\n rqyl: 当日融券余量(股)\n rqmcl: 当日融券卖出量(股)\n rqchl: 当日融券偿还量(股)\n rqjmcl: 当日融券净卖出量(股)\n rzrqye: 当日融资融券余额(元)\n rzrqyecz: 当日融资融券余额差值(元)\n \"\"\"\n self._data = pd.DataFrame()\n \n self._writeHead()\n \n self._data = self.__handleMarginDetailsAllByDate(self._data, date, 1, Utility.random(8), retry, pause)\n self._data.rename(columns={'scode':'code', 'sname':'name'}, inplace=True)\n \n return self._result()\n \n \n def __handleMarginDetailsAllByDate(self, dataArr, date, page, randInt, retry, pause):\n self._writeConsole()\n \n for _ in range(retry):\n time.sleep(pause)\n \n try:\n request = self._session.get(cf.MAR_BOTH_DETAIL % (date, page, randInt))\n text = request.text.split('=')[1]\n text = text.replace('{pages:', '{\"pages\":').replace(',data:', ',\"data\":').replace('\"-\"', '0')\n dataDict = Utility.str2Dict(text)\n data = dataDict['data']\n df = pd.DataFrame(data, columns=cf.MAR_DET_All_COLS)\n \n df['date'] = date\n df['rzyezb'] = df['rzyezb'].astype(float)\n \n dataArr = dataArr.append(df, ignore_index=True)\n if page < dataDict['pages']:\n dataArr = self.__handleMarginDetailsAllByDate(dataArr, date, page+1, randInt, retry, pause)\n except Exception as e:\n print(e)\n else:\n return dataArr\n \n raise IOError(cf.NETWORK_URL_ERROR_MSG)\n \n \n def marginTotal(self, retry=3, pause=0.001):\n \"\"\"\n 两市合计融资融券历史数据\n Parameters\n --------\n retry : int, 默认 3\n 如遇网络等问题重复执行的次数 \n pause : int, 默认 0\n 重复请求数据过程中暂停的秒数,防止请求间隔时间太短出现的问题\n \n Return\n ------\n DataFrame or List: [{'date':, 'close':, ...}, ...]\n date: 日期\n close: 沪深300收盘点数\n zdf: 沪深300收盘涨跌幅(%)\n rzye: 融资余额(元)\n rzyezb: 融资余额占比(%)\n rzmre: 融资买入额(元)\n rzche: 融资偿还额(元)\n rzjmre: 融资净买入额(元)\n rqye: 融券余额(元)\n rqyl: 融券余量(股)\n rqmcl: 融券卖出量(股)\n rqchl: 融券偿还量(股)\n rqjmcl: 融券净卖出量(股)\n rzrqye: 融资融券余额(元)\n rzrqyecz: 融资融券余额差值(元)\n \"\"\"\n self._data = pd.DataFrame()\n \n self._writeHead()\n \n self._data = self.__handleMarginTotal(self._data, 1, Utility.random(8), retry, pause)\n self._data.rename(columns={'tdate':'date'}, inplace=True)\n \n return self._result()\n \n \n def __handleMarginTotal(self, dataArr, page, randInt, retry, pause):\n self._writeConsole()\n \n for _ in range(retry):\n time.sleep(pause)\n \n try:\n request = self._session.get(cf.MAR_TOTAL_URL % (page, randInt), timeout=10)\n text = request.text.split('=')[1]\n text = text.replace('{pages:', '{\"pages\":').replace(',data:', ',\"data\":').replace('T00:00:00', '').replace('\"-\"', '0')\n dataDict = Utility.str2Dict(text)\n data = dataDict['data']\n df = pd.DataFrame(data, columns=cf.MAR_TOTAL_COLS)\n \n df['close'] = df['close'].map(cf.FORMAT)\n df['rzyezb'] = df['rzyezb'].astype(float)\n \n dataArr = dataArr.append(df, ignore_index=True)\n if page < dataDict['pages']:\n dataArr = self.__handleMarginTotal(dataArr, page+1, randInt, retry, pause)\n except Exception as e:\n print(e)\n else:\n return dataArr\n \n raise IOError(cf.NETWORK_URL_ERROR_MSG)\n \n"
] | [
[
"pandas.compat.StringIO",
"pandas.DataFrame",
"pandas.read_html"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
bathienle/master-thesis-code | [
"58182f54a56c34fb4a33d67743ca515c80e33657"
] | [
"src/experiments/simple.py"
] | [
"\"\"\"\nTraining without inclusion and exclusion map or train with U-Net model\n\"\"\"\n\nimport csv\nimport numpy as np\nimport time\nimport torch\nimport os\n\nfrom argparse import ArgumentParser\nfrom torch.optim import Adam\nfrom torch.utils.data import DataLoader\n\nfrom src import (\n NuClick, UNet, TestDataset, Loss, convert_time, str2bool\n)\n\n\n# Check if GPU is available\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\ndef parse_arguments():\n \"\"\"\n Parse the arguments of the program.\n\n Return\n ------\n args : class argparse.Namespace\n The parsed arguments.\n \"\"\"\n\n parser = ArgumentParser(description=\"Train a model without signal maps.\")\n\n # Training parameters\n parser.add_argument(\n '--shuffle',\n type=str2bool,\n default=True,\n help=\"Whether to shuffle the training images or not.\"\n )\n parser.add_argument(\n '--epochs',\n type=int,\n default=15,\n help=\"Number of epochs to train the model.\"\n )\n parser.add_argument(\n '--bs',\n dest='batch_size',\n type=int,\n default=16,\n help=\"The batch size for the training\"\n )\n parser.add_argument(\n '--lr',\n type=float,\n default=3e-3,\n help=\"The learning rate of the optimizer.\"\n )\n parser.add_argument(\n '--wd',\n type=float,\n default=5e-5,\n help=\"The weight decay of the optimizer.\"\n )\n parser.add_argument(\n '--model',\n default=\"nuclick\",\n help=\"The model to use.\"\n )\n\n # Misc parameters\n parser.add_argument(\n '--type',\n help=\"The type of object to detect.\"\n )\n parser.add_argument(\n '--data',\n help=\"Path to the dataset.\"\n )\n parser.add_argument(\n '--dest',\n default='./',\n help=\"The path to save the weights of the model.\"\n )\n parser.add_argument(\n '--resume',\n type=bool,\n default=False,\n help=\"Resume the training of the model.\")\n parser.add_argument(\n '--checkpoint',\n help=\"Checkpoint of the state of the training.\"\n )\n parser.add_argument(\n '--step',\n type=int,\n default=20,\n help=\"Save a checkpoint every step epoch.\"\n )\n parser.add_argument(\n '--stat',\n dest='stat_path',\n default='./statistics.csv',\n help=\"Path to save statistic about training.\"\n )\n\n return parser.parse_args()\n\n\ndef train(model, trainloader, criterion, optimizer, batch_size):\n \"\"\"\n Train the model for one epoch using gradient accumulation technique.\n Parameters\n ----------\n model : torch model\n The model to train.\n trainloader : torch DataLoader\n The training dataset.\n criterion : torch loss\n The loss function.\n optimizer : torch optimizer\n The optimizer.\n batch_size : int\n The real batch size.\n Return\n ------\n losses : list of float\n The losses during the training.\n \"\"\"\n\n model.train()\n losses = []\n\n for index, (inputs, targets) in enumerate(trainloader):\n inputs, targets = inputs.to(device), targets.to(device)\n\n predictions = model(inputs)\n\n loss = criterion(predictions, targets)\n\n (loss / batch_size).backward()\n\n losses.append(loss.item() * inputs.size(0))\n\n if (index + 1) % batch_size == 0:\n optimizer.step()\n optimizer.zero_grad()\n\n return losses\n\n\ndef validate(model, valloader, criterion):\n \"\"\"\n Validate the model for one epoch.\n\n Parameters\n ----------\n model : torch model\n The model to train.\n valloader : torch DataLoader\n The validation dataset.\n criterion : torch loss\n The loss function.\n\n Return\n ------\n losses : list of float\n The losses during the validation.\n \"\"\"\n\n model.eval()\n losses = []\n\n with torch.no_grad():\n for inputs, targets in valloader:\n inputs, targets = inputs.to(device), targets.to(device)\n\n predictions = model(inputs)\n\n loss = criterion(predictions, targets)\n losses.append(loss.item() * inputs.size(0))\n\n return losses\n\n\nif __name__ == \"__main__\":\n args = parse_arguments()\n\n # Reproducibility\n torch.manual_seed(0)\n np.random.seed(0)\n\n # Statistics\n header = ['epoch', 'train_mean_loss', 'train_std_loss', 'val_mean_loss',\n 'val_std_loss', 'duration']\n if not os.path.exists(args.stat_path):\n with open(args.stat_path, 'w', newline='') as file:\n writer = csv.DictWriter(file, fieldnames=header)\n writer.writeheader()\n\n # Build the training and validation set\n train_data = TestDataset(os.path.join(args.data, 'train'))\n val_data = TestDataset(os.path.join(args.data, 'val'))\n trainloader = DataLoader(train_data, 4, shuffle=args.shuffle)\n valloader = DataLoader(val_data, args.batch_size, shuffle=args.shuffle)\n\n if args.model == \"nuclick\":\n model = NuClick(in_channels=3)\n elif args.model == \"unet\":\n model = UNet()\n\n model = model.to(device)\n\n optimizer = Adam(model.parameters(), args.lr, weight_decay=args.wd)\n criterion = Loss()\n\n # Check if resume the training\n if args.resume:\n state = torch.load(args.checkpoint, map_location=device)\n\n start_epoch = state['epoch']\n model.load_state_dict(state['model_state_dict'])\n optimizer.load_state_dict(state['optimizer_state_dict'])\n else:\n start_epoch = 0\n\n total_time = 0.0\n\n # Training the model\n for epoch in range(start_epoch, args.epochs):\n start_time = time.time()\n\n # Train the model for one epoch\n train_losses = train(\n model, trainloader, criterion, optimizer, args.batch_size\n )\n\n # Perform the validation test on the model\n val_losses = validate(model, valloader, criterion)\n\n # Compute the time taken for one epoch\n elapsed_time = time.time() - start_time\n minutes, seconds = convert_time(elapsed_time)\n total_time += elapsed_time\n\n # Statistics\n with open(args.stat_path, 'a', newline='') as file:\n csv.writer(file).writerow([\n epoch,\n np.mean(train_losses),\n np.std(train_losses),\n np.mean(val_losses),\n np.std(val_losses),\n f\"{minutes:.0f}m{seconds:.0f}s\"\n ])\n\n # Checkpoint save\n if epoch % args.step and args.checkpoint:\n state = {\n 'epoch': epoch,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict()\n }\n\n torch.save(\n state,\n os.path.join(args.dest, f'{args.type}_checkpoint.pth')\n )\n\n minutes, seconds = convert_time(total_time)\n print(f\"Training complete in {minutes:.0f}m {seconds:.0f}s\")\n\n # Save the trained model\n torch.save(\n model.state_dict(),\n os.path.join(args.dest, f'{args.type}_model.pth')\n )\n\n # Save the training state for further training\n if args.checkpoint:\n state = {\n 'epoch': epoch,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict()\n }\n\n torch.save(\n state,\n os.path.join(args.dest, f'{args.type}_checkpoint.pth')\n )\n"
] | [
[
"numpy.random.seed",
"torch.load",
"torch.manual_seed",
"torch.utils.data.DataLoader",
"numpy.std",
"torch.no_grad",
"numpy.mean",
"torch.cuda.is_available"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
jych/Theano | [
"c74da33de3768e231ffa0d92d9d11667a2a5aedb",
"c74da33de3768e231ffa0d92d9d11667a2a5aedb",
"d7d722faa96aac95c19f460bf60e8e8654ff58df",
"c74da33de3768e231ffa0d92d9d11667a2a5aedb",
"c74da33de3768e231ffa0d92d9d11667a2a5aedb"
] | [
"theano/scan_module/scan_op.py",
"theano/sandbox/scan_module/scan.py",
"theano/sandbox/neighbourhoods.py",
"theano/compile/ops.py",
"theano/sandbox/test_scan.py"
] | [
"\"\"\"\nThis module provides the Scan Op\n\nSee scan.py for details on scan\n\n\nMemory reuse in scan\n--------------------\n\nTo reduce the number of memory allocations and copies associated with calling\nthe inner function and recovering the outputs at every iteration, Scan uses a\nmemory pre-allocation mechanism for some of its outputs. Instead of repeatedly\ncalling the inner function and copying the outputs to designated locations,\nit tries to make the inner function write the outputs directly to the\ndesignated locations.\n\nThis is achieved by initializing, at every iteration, the output storage\nof the inner function with references to previously allocated memory. Other\nthan the code in the Python and Cython backends to do this and to ensure that\nthe pre-allocated memory has been used, the memory pre-allocation mechanism\nrelies on the following elements to work properly :\n- In make_thunk(), when compiling the inner function, the borrow flag must\n be set to False for the inputs. This will prevent aliasing between the\n inputs and the outputs of the inner function which could lead to invalid\n results.\n- In make_thunk(), again, the borrow flag must be set to True for the outputs.\n This will make Theano consider the output storages as persistent and make\n Theano provide them as pre-allocated storage to the ops that compute the\n outputs of the inner function instead of letting these ops allocate their\n own output storage.\n- The ops that produce the outputs of the inner function must be prevented\n from working inplace because if they do, they're not using the pre-allocated\n storage. This is achieved by including the optimization\n 'add_no_output_from_inplace' to the compilation mode used by scan. It\n prevents other optimizations from altering the graph such that outputs are\n produced by inplace operations.\n- The ScanSaveMem optimization, whose goal is to limit the amount of memory\n used by scan, needs to allocate buffers large enough to be able, at every\n iteration, to simultaneously read the needed previous states and storing\n the new states. Before the memory reuse feature, the buffers could be\n smaller because, often, Scan only needed buffers large enough to read the\n needed previous states. This is because all the outputs of the inner\n function were computed before any of them was stored in the buffers. Now,\n the outputs are stored as they are computed which means that, if the buffer\n is too small, computing an output can overwrite an input that is still\n needed to compute another output.\n\"\"\"\nfrom __future__ import print_function\n\n__docformat__ = 'restructedtext en'\n__authors__ = (\"Razvan Pascanu \"\n \"Frederic Bastien \"\n \"James Bergstra \"\n \"Pascal Lamblin \")\n__copyright__ = \"(c) 2010, Universite de Montreal\"\n__contact__ = \"Razvan Pascanu <r.pascanu@gmail>\"\n\nimport itertools\nimport logging\nimport time\n\nimport numpy\nfrom six import iteritems\nfrom six.moves import xrange\n\nimport theano\nfrom theano.compat import exc_message\nfrom theano.compile import function, Param, Out\nfrom theano import compile, config, gradient, gof, tensor\nfrom theano.gof import PureOp, Apply\nfrom theano.gof.graph import io_connection_pattern\nfrom theano.compat import OrderedDict, izip\nfrom theano.tensor import TensorType\nfrom theano.tensor.opt import Shape_i\nfrom theano.gradient import grad_undefined, DisconnectedType, NullType\nfrom six import string_types\nfrom theano.compile.profiling import ScanProfileStats\n\nfrom theano.scan_module import scan_utils\nfrom theano.scan_module.scan_utils import safe_new, forced_replace\n\n# Logging function for sending warning or info\n_logger = logging.getLogger('theano.scan_module.scan_op')\n\n\nfrom theano.configparser import AddConfigVar, BoolParam\n\nAddConfigVar('scan.allow_gc',\n \"Allow/disallow gc inside of Scan (default: False)\",\n BoolParam(False))\n\nAddConfigVar('scan.allow_output_prealloc',\n \"Allow/disallow memory preallocation for outputs inside of scan \"\n \"(default: True)\",\n BoolParam(True))\n\n\nclass Scan(PureOp):\n def __init__(self,\n inputs,\n outputs,\n info,\n typeConstructor=None,\n ):\n \"\"\"\n :param inputs: inputs of the inner function of scan\n :param outputs: outputs of the inner function of scan\n :param info: dictionary containing different properties of\n the scan op (like number of different types of\n arguments, name, mode, if it should run on GPU or\n not, etc.)\n :param typeConstructor: function that constructs an equivalent\n to Theano TensorType\n\n\n Note: ``typeConstructor`` had been added to refactor how\n Theano deals with the GPU. If it runs on the GPU, scan needs\n to construct certain outputs (those who reside in the GPU\n memory) as the GPU-specific type. However we can not import\n gpu code in this file (as it is in sandbox, and not available\n on each machine) so the workaround is that the GPU\n optimization passes to the constructor of this class a\n function that is able to construct a GPU type. This way the\n class Scan does not need to be aware of the details for the\n GPU, it just constructs any tensor using this function (which\n by default constructs normal tensors).\n \"\"\"\n if 'gpua' not in info:\n info['gpua'] = False\n # adding properties into self\n self.inputs = inputs\n self.outputs = outputs\n self.__dict__.update(info)\n # I keep a version of info in self, to use in __eq__ and __hash__,\n # since info contains all tunable parameters of the op, so for two\n # scan to be equal this tunable parameters should be the same\n self.info = info\n # build a list of output types for any Apply node using this op.\n self.output_types = []\n idx = 0\n jdx = 0\n tensorConstructor = lambda broadcastable, dtype: TensorType(\n broadcastable=broadcastable, dtype=dtype)\n if typeConstructor is None:\n typeConstructor = tensorConstructor\n\n while idx < self.n_mit_mot_outs:\n # Not that for mit_mot there are several output slices per\n # output sequence\n o = outputs[idx]\n self.output_types.append(\n typeConstructor(\n broadcastable=(False,) + o.type.broadcastable,\n dtype=o.type.dtype))\n\n idx += len(self.mit_mot_out_slices[jdx])\n jdx += 1\n\n # mit_sot / sit_sot / nit_sot\n end = idx + self.n_mit_sot + self.n_sit_sot + self.n_nit_sot\n\n for o in outputs[idx:end]:\n self.output_types.append(\n typeConstructor(\n broadcastable=(False,) + o.type.broadcastable,\n dtype=o.type.dtype))\n\n # shared outputs + possibly the ending condition\n for o in outputs[end:]:\n self.output_types.append(o.type)\n\n if self.as_while:\n self.output_types = self.output_types[:-1]\n\n mode_instance = compile.mode.get_mode(self.mode)\n # Clone mode_instance, altering \"allow_gc\" for the linker,\n # and adding a message if the mode is a ProfileMode.\n if self.name:\n message = self.name + \" sub profile\"\n else:\n message = \"Scan sub profile\"\n\n self.mode_instance = mode_instance.clone(\n link_kwargs=dict(allow_gc=self.allow_gc),\n message=message)\n\n # Now that scan has its mode instance, if memory pre-allocation is\n # activated for the outputs, we activate the optimization\n # add_no_output_from_inplace in this mode instance. This will prevent\n # Scan from producing outputs by means of inplace operations and\n # therefore allow it to pre-allocate memory storage for the outputs,\n # avoiding needless copies.\n if theano.config.scan.allow_output_prealloc:\n self.mode_instance = self.mode_instance.including(\n \"add_no_output_from_inplace\")\n\n if not hasattr(self, 'name') or self.name is None:\n self.name = 'scan_fn'\n # to have a fair __eq__ comparison later on, we update the info with\n # the actual mode used to compile the function and the name of the\n # function that we set in case none was given\n self.info['name'] = self.name\n\n # Pre-computing some values to speed up perform\n self.mintaps = [numpy.min(x) for x in self.tap_array]\n self.mintaps += [0 for x in xrange(self.n_nit_sot)]\n self.seqs_arg_offset = 1 + self.n_seqs\n self.shared_arg_offset = (self.seqs_arg_offset +\n self.n_mit_mot +\n self.n_mit_sot +\n self.n_sit_sot)\n self.nit_sot_arg_offset = (self.shared_arg_offset +\n self.n_shared_outs)\n self.n_outs = self.n_mit_mot + self.n_mit_sot + self.n_sit_sot\n self.n_tap_outs = self.n_mit_mot + self.n_mit_sot\n if self.info['gpu'] or self.info['gpua']:\n self._hash_inner_graph = self.info['gpu_hash']\n else:\n tmp_in, tmp_out = scan_utils.reconstruct_graph(self.inputs,\n self.outputs)\n local_fgraph = gof.FunctionGraph(tmp_in, tmp_out, clone=False)\n self._cmodule_key = gof.CLinker().cmodule_key_(local_fgraph, [])\n self._hash_inner_graph = hash(self._cmodule_key)\n\n # Compute mappings between outer inputs, outer outputs, inner\n # inputs and inner outputs to determine with variables are associated\n # with the same states.\n self.var_mappings = self.get_oinp_iinp_iout_oout_mappings()\n\n def validate_inner_graph(self):\n \"\"\" Perform some elementary validations on the inner graph to ensure\n that it is coherent.\n \"\"\"\n\n # For every recurrent output, iterate over the associated inner\n # inputs and output and ensure that they have the same dtype\n nb_recurr_outputs = self.n_mit_mot + self.n_mit_sot + self.n_sit_sot\n\n for outer_oidx in xrange(nb_recurr_outputs):\n\n inner_iidxs = self.var_mappings['inner_inp_from_outer_out'][outer_oidx]\n inner_oidxs = self.var_mappings['inner_out_from_outer_out'][outer_oidx]\n\n for (inner_iidx, inner_oidx) in itertools.product(inner_iidxs,\n inner_oidxs):\n\n type_input = self.inputs[inner_iidx].type\n type_output = self.outputs[inner_oidx].type\n if (type_input != type_output):\n raise TypeError(\"Inconsistency in the inner graph of \"\n \"scan '%s' : an input and an output are \"\n \"associated with the same recurrent state \"\n \"and should have the same type but have \"\n \"type '%s' and '%s' respectively.\" %\n (self.name, type_input, type_output))\n\n # If scan has the flag 'gpu' set to false (meaning that is shouldn't\n # use the CUDA gpu backend ), ensure that is has no input and no\n # output with type CudaNdarrayType\n from theano.sandbox.cuda import CudaNdarrayType\n if not self.info.get(\"gpu\", False):\n for inp in self.inputs:\n if isinstance(inp.type, CudaNdarrayType):\n raise TypeError(\"Inconsistency in the inner graph of \"\n \"scan '%s' : one of the inputs to the \"\n \"inner graph is of type CudaNdarray but \"\n \"the attributes of the scan op indicate \"\n \"that it shouldn't be the case\")\n\n for out in self.outputs:\n if isinstance(out.type, CudaNdarrayType):\n raise TypeError(\"Inconsistency in the inner graph of \"\n \"scan '%s' : one of the outputs to the \"\n \"inner graph is of type CudaNdarray but \"\n \"the attributes of the scan op indicate \"\n \"that it shouldn't be the case\")\n\n # If scan has the flag 'gpua' set to false (meaning that is shouldn't\n # use the gpuarray gpu backend ), ensure that is has no input and no\n # output with type GpuArrayType\n from theano.sandbox.gpuarray import GpuArrayType\n if not self.info.get(\"gpua\", False):\n for inp in self.inputs:\n if isinstance(inp.type, GpuArrayType):\n raise TypeError(\"Inconsistency in the inner graph of \"\n \"scan '%s' : one of the inputs to the \"\n \"inner graph is of type GpuArrayType but \"\n \"the attributes of the scan op indicate \"\n \"that it shouldn't be the case\")\n\n for out in self.outputs:\n if isinstance(out.type, GpuArrayType):\n raise TypeError(\"Inconsistency in the inner graph of \"\n \"scan '%s' : one of the outputs to the \"\n \"inner graph is of type GpuArrayType but \"\n \"the attributes of the scan op indicate \"\n \"that it shouldn't be the case\")\n\n def __setstate__(self, d):\n self.__dict__.update(d)\n if \"allow_gc\" not in self.__dict__:\n self.allow_gc = True\n self.info['allow_gc'] = True\n if not hasattr(self, 'gpua'):\n self.gpua = False\n self.info['gpua'] = False\n if not hasattr(self, 'var_mappings'):\n # Generate the mappings between inner and outer inputs and outputs\n # if they haven't already been generated.\n self.var_mappings = self.get_oinp_iinp_iout_oout_mappings()\n\n # Ensure that the graph associated with the inner function is valid.\n self.validate_inner_graph()\n\n def make_node(self, *inputs):\n \"\"\"\n Conventions:\n inner_X - the variable corresponding to X in the inner function\n of scan (the lambda function executed at every time\n step)\n outer_X - the variable corresponding to X in the outer graph,\n i.e. the main graph (where the scan op lives)\n inner_X_out - the variable representing the new value of X after\n executing one step of scan (i.e. outputs given by\n the inner function)\n \"\"\"\n assert numpy.all(isinstance(i, gof.Variable) for i in inputs)\n # Check that the number of inputs to the Scan node corresponds to\n # the number of inputs of the inner function of scan\n n_outer_ins = len(inputs) - len(self.outer_nitsot(inputs)) - 1\n n_inner_ins = (len(self.inner_seqs(self.inputs)) +\n len(self.mitmot_taps()) +\n len(self.mitsot_taps()) +\n len(self.inner_sitsot(self.inputs)) +\n len(self.inner_shared(self.inputs)) +\n len(self.inner_non_seqs(self.inputs)))\n assert n_outer_ins == n_inner_ins, \\\n (\"The number of inputs given to the inner function of scan\"\n \" does not match the number of inputs given to scan.\")\n new_inputs = [inputs[0]]\n # assert dtype is consistent\n err_msg1 = ('When compiling the inner function of scan (the '\n 'function called by scan in each of its iterations) '\n 'the following error has been encountered: The '\n '%s %s (argument number %d) has dtype '\n '%s and %d dimension(s). The corresponding variable '\n 'in the inner function of scan %s '\n 'however has dtype %s and %d dimension(s). This '\n 'variable in the inner function of scan should '\n 'have the same dtype and one fewer dimension '\n 'compared to its corresponding variable in the initial '\n 'state (outputs_info in scan nomenclature). For example, '\n 'if the inner function of scan returns a vector '\n 'of size d and scan uses the values of '\n 'the previous time-step, then the initial state in scan '\n 'should be a matrix of shape (1, d). '\n 'The first dimension of this '\n 'matrix corresponds to the number of previous time-steps '\n 'that scan uses in each of its iterations. '\n 'In order to solve this issue if the two variable currently '\n 'have the same dimensionality, you can increase the '\n 'dimensionality of the varialbe in the initial state of scan '\n 'by using dimshuffle or shape_padleft. '\n )\n err_msg2 = ('When compiling the inner function of scan the '\n 'following error has been encountered: The '\n 'initial state (`outputs_info` in scan nomenclature) '\n 'of variable %s (argument number %d) '\n 'has dtype %s, while the result of the inner function '\n '(`fn`) has dtype %s. This can happen if the inner '\n 'function of scan results in an upcast or downcast.')\n err_msg3 = ('When compiling the inner function of scan (the '\n 'function called by scan in each of its iterations) '\n 'the following error has been encountered: The '\n 'initial state (`outputs_info` in scan nomenclature) '\n 'of variable %s (argument number %d) has %d dimension(s), '\n 'while the corresponding variable in the result of the inner '\n 'function of scan (`fn`) has %d dimension(s) (it should '\n 'be one less than the initial state). For example, '\n 'if the inner function of scan returns a vector '\n 'of size d and scan uses the values of '\n 'the previous time-step, then the initial state in scan '\n 'should be a matrix of shape (1, d). '\n 'The first dimension of this '\n 'matrix corresponds to the number of previous time-steps '\n 'that scan uses in each of its iterations. '\n 'In order to solve this issue if the two varialbe currently '\n 'have the same dimensionality, you can increase the '\n 'dimensionality of the variable in the initial state of scan '\n 'by using dimshuffle or shape_padleft. '\n )\n\n def format(var, as_var):\n \"\"\" This functions ensures that ``out`` has the same dtype as\n ``inp`` as well as calling filter_variable to make sure they are\n both TensorType or CudaNdarrayType. It internally deals with the\n corner case where inp.ndim + 1 = out.ndim\n \"\"\"\n if not hasattr(var, 'dtype'):\n return var\n rval = var\n if rval.type.dtype != as_var.type.dtype:\n rval = rval.astype(as_var.type.dtype)\n if rval.ndim == as_var.ndim:\n rval = as_var.type.filter_variable(rval)\n else:\n tmp = as_var.type.clone(\n broadcastable=(tuple(var.broadcastable[:1]) +\n tuple(as_var.broadcastable)))\n rval = tmp.filter_variable(rval)\n return rval\n\n # Check if input sequences and variables representing a slice of\n # them have the same dtype\n argoffset = 0\n for inner_seq, outer_seq in zip(self.inner_seqs(self.inputs),\n self.outer_seqs(inputs)):\n new_inputs.append(format(outer_seq, as_var=inner_seq))\n\n argoffset += len(self.outer_seqs(inputs))\n # Check that this 3 things have the same dtype for mit_mot:\n # - initial state of the output\n # - variable representing an input slice of the otuput\n # - variable representing an output slice of the otuput\n ipos = 0\n opos = 0\n inner_mitmot = self.inner_mitmot(self.inputs)\n inner_mitmot_outs = self.inner_mitmot_outs(self.outputs)\n for idx, (itaps, otaps, _outer_mitmot) in enumerate(\n zip(self.mitmot_taps(),\n self.mitmot_out_taps(),\n self.outer_mitmot(inputs))):\n outer_mitmot = format(_outer_mitmot, as_var=inner_mitmot[ipos])\n new_inputs.append(outer_mitmot)\n for k in xrange(len(itaps)):\n if (inner_mitmot[ipos + k].type.dtype !=\n outer_mitmot.type.dtype or\n inner_mitmot[ipos + k].ndim != outer_mitmot.ndim - 1):\n raise ValueError(err_msg1 % ('initial state (outputs_info'\n ' in scan nomenclature) ',\n str(outer_mitmot),\n argoffset + idx,\n outer_mitmot.type.dtype,\n outer_mitmot.type.ndim,\n str(inner_mitmot[ipos + k]),\n inner_mitmot[ipos +\n k].type.dtype,\n inner_mitmot[ipos + k].type.ndim))\n ipos += len(itaps)\n for k in xrange(len(otaps)):\n if (inner_mitmot_outs[opos + k].type.dtype !=\n outer_mitmot.type.dtype):\n raise ValueError(err_msg2 %\n (str(outer_mitmot),\n argoffset + idx,\n outer_mitmot.type.dtype,\n inner_mitmot_outs[opos + k].type.dtype))\n if inner_mitmot_outs[opos + k].ndim != outer_mitmot.ndim - 1:\n raise ValueError(err_msg3 %\n (str(outer_mitmot),\n argoffset + idx,\n outer_mitmot.ndim,\n inner_mitmot_outs[opos + k].ndim))\n opos += len(otaps)\n argoffset += len(self.outer_mitmot(inputs))\n # Same checks as above but for outputs of type mit_sot\n ipos = 0\n inner_mitsots = self.inner_mitsot(self.inputs)\n for idx, (itaps, _outer_mitsot, inner_mitsot_out) in enumerate(\n zip(self.mitsot_taps(),\n self.outer_mitsot(inputs),\n self.inner_mitsot_outs(self.outputs))):\n outer_mitsot = format(_outer_mitsot, as_var=inner_mitsots[ipos])\n new_inputs.append(outer_mitsot)\n\n for k in xrange(len(itaps)):\n if (inner_mitsots[ipos + k].type.dtype != \\\n outer_mitsot.type.dtype or\n inner_mitsots[ipos + k].ndim != outer_mitsot.ndim - 1):\n raise ValueError(err_msg1 % ('initial state (outputs_info'\n ' in scan nomenclature) ',\n str(outer_mitsot),\n argoffset + idx,\n outer_mitsot.type.dtype,\n outer_mitsot.type.ndim,\n str(inner_mitsots[ipos + k]),\n inner_mitsots[ipos + k].type.dtype,\n inner_mitsots[ipos + k].type.ndim))\n ipos += len(itaps)\n if inner_mitsot_out.type.dtype != outer_mitsot.type.dtype:\n raise ValueError(err_msg2 %\n (str(outer_mitsot),\n argoffset + idx,\n outer_mitsot.type.dtype,\n inner_mitsot_out.type.dtype))\n if inner_mitsot_out.ndim != outer_mitsot.ndim - 1:\n raise ValueError(err_msg3 %\n (str(outer_mitsot),\n argoffset + idx,\n outer_mitsot.ndim,\n inner_mitsot_out.ndim))\n\n argoffset += len(self.outer_mitsot(inputs))\n # Same checks as above but for outputs of type sit_sot\n for idx, (inner_sitsot, _outer_sitsot, inner_sitsot_out) in enumerate(\n zip(self.inner_sitsot(self.inputs),\n self.outer_sitsot(inputs),\n self.inner_sitsot_outs(self.outputs))):\n outer_sitsot = format(_outer_sitsot, as_var=inner_sitsot)\n new_inputs.append(outer_sitsot)\n if (inner_sitsot.ndim != outer_sitsot.ndim - 1):\n raise ValueError(err_msg1 % ('initial state (outputs_info'\n ' in scan nomenclature) ',\n str(outer_sitsot),\n argoffset + idx,\n outer_sitsot.type.dtype,\n outer_sitsot.type.ndim,\n str(inner_sitsot),\n inner_sitsot.type.dtype,\n inner_sitsot.type.ndim))\n if inner_sitsot_out.type.dtype != outer_sitsot.type.dtype:\n raise ValueError(err_msg2 %\n (str(outer_sitsot),\n argoffset + idx,\n outer_sitsot.type.dtype,\n inner_sitsot_out.type.dtype))\n if inner_sitsot_out.ndim != outer_sitsot.ndim - 1:\n raise ValueError(err_msg3 %\n (str(outer_sitsot),\n argoffset + idx,\n outer_sitsot.type.ndim,\n inner_sitsot_out.type.ndim))\n\n argoffset += len(self.outer_sitsot(inputs))\n # Check that the shared variable and their update rule have the same\n # dtype. Maybe even same type ?!\n for idx, (inner_shared, inner_shared_out, _outer_shared) in enumerate(\n zip(self.inner_shared(self.inputs),\n self.inner_shared_outs(self.outputs),\n self.outer_shared(inputs))):\n outer_shared = format(_outer_shared, as_var=inner_shared)\n new_inputs.append(outer_shared)\n if (hasattr(outer_shared, 'dtype') and\n outer_shared.dtype != inner_shared_out.dtype):\n raise ValueError(err_msg2 % (str(outer_shared),\n idx + argoffset,\n outer_shared.dtype,\n inner_shared_out.dtype))\n if (hasattr(outer_shared, 'dtype') and\n outer_shared.ndim != inner_shared_out.ndim):\n raise ValueError(err_msg3 % (str(outer_shared),\n idx + argoffset,\n outer_shared.ndim,\n inner_shared_out.ndim))\n\n if (hasattr(outer_shared, 'dtype') and\n (outer_shared.dtype != inner_shared.dtype or\n outer_shared.ndim != inner_shared.ndim)):\n raise ValueError(err_msg1 % ('initial state (outputs_info'\n ' in scan nomenclature) ',\n str(outer_shared),\n argoffset + idx,\n outer_shared.dtype,\n outer_shared.ndim,\n str(inner_shared),\n inner_shared.dtype,\n inner_shared.ndim))\n # We do not need to call `format` on outer_nisot arguments.\n # outer_nitsot stands for no input tap single output tap. This means\n # these are states that do not feed anything back in the recurrent\n # computation, and hence they do not have an initial state. The scan\n # node however receives an input for each such argument, the input\n # in this case is just a int saying how many steps of this output we\n # need to store. This input does not have the same dtype, nor is it the same\n # type of tensor as the output, it is always a scalar int.\n new_inputs += self.outer_nitsot(inputs)\n for inner_nonseq, _outer_nonseq in zip(\n self.inner_non_seqs(self.inputs),\n self.outer_non_seqs(inputs)):\n outer_nonseq = format(_outer_nonseq, as_var=inner_nonseq)\n new_inputs.append(outer_nonseq)\n if inner_nonseq.type != outer_nonseq.type:\n raise ValueError(('Argument %s given to scan node does not'\n ' match its correspondance %s') %\n (str(outer_nonseq), str(inner_nonseq)))\n\n for outer_nitsot in self.outer_nitsot(inputs):\n # For every nit_sot input we get as input a int/uint that\n # depicts the size in memory for that sequence. This feature is\n # used by truncated BPTT and by scan space optimization\n if (str(outer_nitsot.type.dtype)[:3] not in ('uin', 'int') or\n outer_nitsot.ndim != 0):\n raise ValueError('For output %s you need to provide a '\n 'scalar int !', str(outer_nitsot))\n assert len(new_inputs) == len(inputs)\n\n # The vector_seqs and vector_outs are just a workaround\n # strange NumPy behavior: vector_ndarray[int] return a NumPy\n # scalar and not a NumPy ndarray of 0 dimensions.\n self.vector_seqs = [isinstance(seq, (tensor.TensorVariable,\n tensor.TensorConstant)) and\n seq.ndim == 1 for seq in\n new_inputs[1:1 + self.n_seqs]]\n self.vector_outs = [isinstance(arg, (tensor.TensorVariable,\n tensor.TensorConstant)) and\n arg.ndim == 1 for arg in\n new_inputs[1 + self.n_seqs: (1 + self.n_seqs +\n self.n_outs)]]\n self.vector_outs += [False] * self.n_nit_sot\n\n apply_node = Apply(self,\n new_inputs,\n [t() for t in self.output_types])\n return apply_node\n\n def __eq__(self, other):\n # Check if we are dealing with same type of objects\n if not type(self) == type(other):\n return False\n if not 'destroy_map' in self.info:\n self.info['destroy_map'] = OrderedDict()\n if not 'destroy_map' in other.info:\n other.info['destroy_map'] = OrderedDict()\n keys_to_check = ['truncate_gradient', 'profile',\n 'n_seqs', 'tap_array',\n 'as_while', 'n_mit_sot', 'destroy_map',\n 'n_nit_sot', 'n_shared_outs',\n 'n_sit_sot', 'gpu', 'gpua', 'n_mit_mot_outs',\n 'n_mit_mot', 'mit_mot_out_slices']\n # This are some safety checks ( namely that the inner graph has the\n # same number of inputs and same number of outputs )\n if not len(self.inputs) == len(other.inputs):\n return False\n elif not len(self.outputs) == len(other.outputs):\n return False\n for key in keys_to_check:\n if self.info[key] != other.info[key]:\n return False\n # If everything went OK up to here, there is still one thing to\n # check. Namely, do the internal graph represent same\n # computations\n for self_in, other_in in izip(self.inputs, other.inputs):\n if self_in.type != other_in.type:\n return False\n\n return scan_utils.equal_computations(self.outputs,\n other.outputs,\n self.inputs,\n other.inputs)\n\n def __str__(self):\n if self.gpu:\n gpu_str = 'gpu'\n else:\n gpu_str = 'cpu'\n if self.as_while:\n name = 'do_while'\n else:\n name = 'for'\n aux_txt = '%s'\n if getattr(self, 'destroy_map', None) is None:\n self.destroy_map = OrderedDict()\n if len(self.destroy_map.keys()) > 0:\n # Check if all outputs are inplace\n if (sorted(self.destroy_map.keys()) == \\\n sorted(range(self.n_mit_mot +\n self.n_mit_sot +\n self.n_sit_sot))):\n aux_txt += 'all_inplace,%s,%s}'\n else:\n aux_txt += '{inplace{'\n for k in self.destroy_map.keys():\n aux_txt += str(k) + ','\n aux_txt += '},%s,%s}'\n else:\n aux_txt += '{%s,%s}'\n aux_txt = aux_txt % (name, gpu_str, str(self.name))\n return aux_txt\n\n def __hash__(self):\n return hash((type(self),\n # and a hash representing the inner graph using the\n # CLinker.cmodule_key_\n self._hash_inner_graph,\n scan_utils.hash_listsDictsTuples(self.info)))\n\n def make_thunk(self, node, storage_map, compute_map, no_recycling):\n \"\"\"\n :param node: something previously returned by self.make_node\n\n :param storage_map: dict variable -> one-element-list where a computed\n value for this variable may be found.\n\n :param compute_map: dict variable -> one-element-list where a boolean\n value will be found. The boolean indicates whether the\n variable's storage_map container contains a valid value (True)\n or if it has not been computed yet (False).\n\n :param no_recycling: list of variables for which it is forbidden to\n reuse memory allocated by a previous call.\n\n :note: If the thunk consults the storage_map on every call, it is safe\n for it to ignore the no_recycling argument, because elements of the\n no_recycling list will have a value of None in the storage map. If\n the thunk can potentially cache return values (like CLinker does),\n then it must not do so for variables in the no_recycling list.\n \"\"\"\n\n # Before building the thunk, validate that the inner graph is\n # coherent\n self.validate_inner_graph()\n\n # Setting up all my variables in what I believe is a more Cython\n # friendly form\n\n node_input_storage = [storage_map[r] for r in node.inputs]\n node_output_storage = [storage_map[r] for r in node.outputs]\n node_input_compute = [compute_map[r] for r in node.inputs]\n node_output_compute = [compute_map[r] for r in node.outputs]\n #_logger.debug('Compiling node %i of graph' % node_idx)\n # If a shared variable is the result of a ViewOp it is a clear\n # indication that we need to copy that value after the perform of\n # scan is done\n slices = (self.n_mit_mot_outs +\n self.n_mit_sot +\n self.n_sit_sot +\n self.n_nit_sot)\n if theano.config.scan.allow_output_prealloc:\n wrapped_inputs = [Param(x, borrow=False) for x in\n self.inputs]\n wrapped_outputs = [Out(x, borrow=True) for x in\n self.outputs[:slices]]\n else:\n wrapped_inputs = [Param(x, borrow=True) for x in\n self.inputs]\n wrapped_outputs = [Out(x, borrow=False) for x in\n self.outputs[:slices]]\n wrapped_outputs += self.outputs[slices:]\n profile = None\n if (theano.config.profile or\n (isinstance(self.profile, (string_types, bool, int))\n and self.profile)):\n if isinstance(self.profile, string_types):\n profile = ScanProfileStats(name=self.profile)\n else:\n profile = ScanProfileStats(name=self.name)\n elif self.profile:\n profile = self.profile\n # make_thunk can be called many times on the same op\n # we do not want to recompile the inner fct every time.\n if not getattr(self, 'fn', None):\n self.fn = function(wrapped_inputs,\n wrapped_outputs,\n mode=self.mode_instance,\n name=self.name,\n profile=profile,\n on_unused_input='ignore')\n\n try:\n cython_mintaps = numpy.asarray(self.mintaps, dtype='int32')\n cython_tap_array_len = \\\n numpy.asarray([len(x) for x in self.tap_array],\n dtype='int32')\n if len(self.tap_array) == 0:\n d1 = 0\n else:\n d1 = numpy.max(cython_tap_array_len)\n d0 = len(self.tap_array)\n cython_tap_array = numpy.zeros((d0, d1), dtype='int32')\n for _d0 in xrange(d0):\n for _d1 in xrange(cython_tap_array_len[_d0]):\n cython_tap_array[_d0, _d1] = self.tap_array[_d0][_d1]\n cython_mit_mot_out_nslices = \\\n numpy.asarray([len(x) for x in self.mit_mot_out_slices],\n dtype='int32')\n if len(self.mit_mot_out_slices) == 0:\n d1 = 0\n else:\n d1 = numpy.max(cython_mit_mot_out_nslices)\n d0 = len(self.mit_mot_out_slices)\n cython_mit_mot_out_slices = numpy.zeros((d0, d1),\n dtype='int32')\n for _d0 in xrange(d0):\n for _d1 in xrange(cython_mit_mot_out_nslices[_d0]):\n cython_mit_mot_out_slices[_d0, _d1] = \\\n self.mit_mot_out_slices[_d0][_d1]\n\n cython_vector_seqs = numpy.asarray(self.vector_seqs,\n dtype='int32')\n cython_vector_outs = numpy.asarray(self.vector_outs,\n dtype='int32')\n\n if hasattr(self, 'destroy_map'):\n cython_destroy_map = [x in self.destroy_map\n for x in xrange(len(node.outputs))]\n else:\n cython_destroy_map = [0 for x in xrange(len(node.outputs))]\n cython_destroy_map = numpy.asarray(cython_destroy_map,\n dtype='int32')\n from . import scan_perform_ext\n p = lambda node, args, outs:\\\n scan_perform_ext.perform(\n self.n_shared_outs,\n self.n_mit_mot_outs,\n self.n_seqs,\n self.n_mit_mot,\n self.n_mit_sot,\n self.n_sit_sot,\n self.n_nit_sot,\n args[0],\n self.as_while,\n cython_mintaps,\n cython_tap_array,\n cython_tap_array_len,\n cython_vector_seqs,\n cython_vector_outs,\n cython_mit_mot_out_slices,\n cython_mit_mot_out_nslices,\n self.fn.fn,\n self.fn,\n cython_destroy_map,\n args,\n outs,\n self, node)\n except (ImportError, theano.gof.cmodule.MissingGXX):\n p = self.execute\n # default arguments are stored in the closure of `rval`\n\n # Big ugly hack since we can't get the real value of allow_gc\n # for the englobing function.\n allow_gc = config.allow_gc and not self.allow_gc\n\n def rval(p=p, i=node_input_storage, o=node_output_storage, n=node,\n allow_gc=allow_gc):\n r = p(n, [x[0] for x in i], o)\n for o in node.outputs:\n compute_map[o][0] = True\n if allow_gc:\n self.fn.free()\n return r\n rval.inputs = node_input_storage\n rval.outputs = node_output_storage\n rval.perform = p\n rval.lazy = False\n return rval\n\n def inner_seqs(self, list_inputs):\n # Given the list of inner inputs this function grabs those\n # corresponding to sequences\n return list_inputs[:self.n_seqs]\n\n def outer_seqs(self, list_inputs):\n if isinstance(list_inputs, Apply):\n list_inputs = list_inputs.inputs\n # Given the list of outter inputs this function grabs those\n # corresponding to sequences\n return list_inputs[1:1 + self.n_seqs]\n\n def inner_mitmot(self, list_inputs):\n n_taps = sum(len(x) for x in self.tap_array[:self.n_mit_mot])\n return list_inputs[self.n_seqs: self.n_seqs + n_taps]\n\n def outer_mitmot(self, list_inputs):\n if isinstance(list_inputs, Apply):\n list_inputs = list_inputs.inputs\n return list_inputs[1 + self.n_seqs:1 + self.n_seqs + self.n_mit_mot]\n\n def inner_mitmot_outs(self, list_outputs):\n n_taps = sum(len(x) for x in self.mit_mot_out_slices)\n return list_outputs[:n_taps]\n\n def outer_mitmot_outs(self, list_outputs):\n if isinstance(list_outputs, Apply):\n list_outputs = list_outputs.ouputs\n return list_outputs[:self.n_mit_mot]\n\n def mitmot_taps(self):\n return self.tap_array[:self.n_mit_mot]\n\n def mitmot_out_taps(self):\n return self.mit_mot_out_slices[:self.n_mit_mot]\n\n def inner_mitsot(self, list_inputs):\n n_mitmot_taps = sum(len(x) for x in self.tap_array[:self.n_mit_mot])\n ntaps_upto_sit_sot = sum(len(x) for x in\n self.tap_array[:(self.n_mit_mot +\n self.n_mit_sot)])\n return list_inputs[self.n_seqs + n_mitmot_taps:\n self.n_seqs + ntaps_upto_sit_sot]\n\n def outer_mitsot(self, list_inputs):\n if isinstance(list_inputs, Apply):\n list_inputs = list_inputs.inputs\n offset = 1 + self.n_seqs + self.n_mit_mot\n return list_inputs[offset:offset + self.n_mit_sot]\n\n def inner_mitsot_outs(self, list_outputs):\n n_taps = sum(len(x) for x in self.mit_mot_out_slices)\n return list_outputs[n_taps:n_taps + self.n_mit_sot]\n\n def outer_mitsot_outs(self, list_outputs):\n if isinstance(list_outputs, Apply):\n list_outputs = list_outputs.outputs\n return list_outputs[self.n_mit_mot:\n self.n_mit_mot + self.n_mit_sot]\n\n def mitsot_taps(self):\n return self.tap_array[self.n_mit_mot:\n self.n_mit_mot + self.n_mit_sot]\n\n def inner_sitsot(self, list_inputs):\n n_taps_upto_sit_sot = sum(len(x) for x in\n self.tap_array[:(self.n_mit_mot +\n self.n_mit_sot)])\n offset = self.n_seqs + n_taps_upto_sit_sot\n return list_inputs[offset:offset + self.n_sit_sot]\n\n def outer_sitsot(self, list_inputs):\n if isinstance(list_inputs, Apply):\n list_inputs = list_inputs.inputs\n offset = 1 + self.n_seqs + self.n_mit_mot + self.n_mit_sot\n return list_inputs[offset:offset + self.n_sit_sot]\n\n def inner_sitsot_outs(self, list_outputs):\n n_taps = sum(len(x) for x in self.mit_mot_out_slices)\n offset = self.n_mit_sot + n_taps\n return list_outputs[offset:offset + self.n_sit_sot]\n\n def outer_sitsot_outs(self, list_outputs):\n if isinstance(list_outputs, Apply):\n list_outputs = list_outputs.outputs\n offset = self.n_mit_mot + self.n_mit_sot\n return list_outputs[offset:offset + self.n_sit_sot]\n\n def outer_nitsot(self, list_inputs):\n if isinstance(list_inputs, Apply):\n list_inputs = list_inputs.inputs\n offset = (1 + self.n_seqs + self.n_mit_mot + self.n_mit_sot +\n self.n_sit_sot + self.n_shared_outs)\n return list_inputs[offset:offset + self.n_nit_sot]\n\n def inner_nitsot_outs(self, list_outputs):\n n_taps = sum(len(x) for x in self.mit_mot_out_slices)\n offset = self.n_mit_sot + n_taps + self.n_sit_sot\n return list_outputs[offset:offset + self.n_nit_sot]\n\n def outer_nitsot_outs(self, list_outputs):\n if isinstance(list_outputs, Apply):\n list_outputs = list_outputs.outputs\n offset = (self.n_mit_mot + self.n_mit_sot + self.n_sit_sot)\n return list_outputs[offset:offset + self.n_nit_sot]\n\n def inner_shared(self, list_inputs):\n n_taps_upto_sit_sot = sum(len(x) for x in\n self.tap_array[:(self.n_mit_mot +\n self.n_mit_sot)])\n offset = self.n_seqs + n_taps_upto_sit_sot + self.n_sit_sot\n return list_inputs[offset:offset + self.n_shared_outs]\n\n def outer_shared(self, list_inputs):\n if isinstance(list_inputs, Apply):\n list_inputs = list_inputs.inputs\n offset = (1 + self.n_seqs + self.n_mit_mot + self.n_mit_sot +\n self.n_sit_sot)\n return list_inputs[offset:offset + self.n_shared_outs]\n\n def inner_shared_outs(self, list_outputs):\n n_taps = sum(len(x) for x in self.mit_mot_out_slices)\n offset = self.n_mit_sot + n_taps + self.n_sit_sot + self.n_nit_sot\n return list_outputs[offset:offset + self.n_shared_outs]\n\n def outer_shared_outs(self, list_outputs):\n if isinstance(list_outputs, Apply):\n list_outputs = list_outputs.outputs\n offset = (self.n_mit_mot + self.n_mit_sot + self.n_sit_sot +\n self.n_nit_sot)\n return list_outputs[offset:offset + self.n_shared_outs]\n\n def inner_non_seqs(self, list_inputs):\n n_taps_upto_sit_sot = sum(len(x) for x in\n self.tap_array[:(self.n_mit_mot +\n self.n_mit_sot)])\n offset = (self.n_seqs + n_taps_upto_sit_sot + self.n_sit_sot +\n self.n_shared_outs)\n return list_inputs[offset:]\n\n def outer_non_seqs(self, list_inputs):\n if isinstance(list_inputs, Apply):\n list_inputs = list_inputs.inputs\n offset = (1 + self.n_seqs + self.n_mit_mot + self.n_mit_sot +\n self.n_sit_sot + self.n_nit_sot + self.n_shared_outs)\n return list_inputs[offset:]\n\n def execute(self, node, args, outs):\n \"\"\"\n The args are packed like this:\n\n n_steps\n\n X sequence inputs x_1, x_2, ... x_<self.n_seqs>\n\n Y initial states (u_1, u_2, ... u_<self.n_outs>) for our\n outputs. Each must have appropriate length (T_1, T_2, ..., T_Y).\n\n W other inputs w_1, w_2, ... w_W\n\n There are at least 1 + self.n_seqs + self.n_outs inputs, and the\n ones above this number are passed to the scanned function as\n non-sequential inputs.\n\n The outputs are more straightforward:\n\n Y sequence outputs y_1, y_2, ... y_<self.n_outs>\n\n \"\"\"\n # 1. Unzip the number of steps and sequences. If number of steps is\n # negative flip sequences around, and make n_steps positive\n t0_call = time.time()\n t_fn = 0\n n_steps = args[0]\n seqs = []\n if n_steps < 0:\n # History, in the past, this was used for backward\n # scan. Now we reverse the inputs outside of scan.\n raise IndexError(\n \"Scan was asked to run for negative number of step %d\" %\n n_steps)\n elif n_steps == 0:\n raise NotImplementedError(\n \"We didn't implemented yet the case where scan do 0 iteration\")\n else:\n for idx, seq in enumerate(args[1:self.seqs_arg_offset]):\n if seq.shape[0] < n_steps:\n raise ValueError(('Sequence is shorter then the required '\n 'number of steps : (n_steps, seq, '\n 'seq.shape):'), n_steps,\n node.inputs[1 + idx],\n seq.shape)\n seqs.append(seq)\n\n # 2. Allocate memory for the outputs. Construct the list:\n # store_steps -- map containting the length of each output\n # pos -- map containing the current position of each\n # output\n\n store_steps = [arg.shape[0] for arg\n in args[self.seqs_arg_offset:\n self.shared_arg_offset]]\n store_steps += [arg for arg in\n args[self.nit_sot_arg_offset:\n self.nit_sot_arg_offset + self.n_nit_sot]\n ]\n\n pos = [(-self.mintaps[idx]) % store_steps[idx] for idx\n in xrange(self.n_outs + self.n_nit_sot)]\n if not getattr(self, 'destroy_map', None):\n self.destroy_map = OrderedDict()\n # 2.1 Create storage space for outputs\n for idx in xrange(self.n_outs):\n if idx in self.destroy_map:\n # ^ Case 1. Outputs should be computed inplace of their\n # initial state\n outs[idx][0] = args[self.seqs_arg_offset + idx]\n elif (outs[idx][0] is not None and\n outs[idx][0].shape[1:] == args[self.seqs_arg_offset +\n idx].shape[1:]\n and outs[idx][0].shape[0] >= store_steps[idx]):\n # Put in the values of the initial state\n outs[idx][0] = outs[idx][0][:store_steps[idx]]\n if idx > self.n_mit_mot:\n l = - self.mintaps[idx]\n outs[idx][0][:l] = args[self.seqs_arg_offset + idx][:l]\n else:\n outs[idx][0][:] = args[self.seqs_arg_offset + idx]\n else:\n outs[idx][0] = args[self.seqs_arg_offset + idx].copy()\n\n offset = self.nit_sot_arg_offset + self.n_nit_sot\n other_args = args[offset:]\n input_storage = self.fn.input_storage\n output_storage = self.fn.output_storage\n old_output_storage = [None] * len(output_storage)\n old_output_data = [None] * len(output_storage)\n output_reused = [None] * len(output_storage)\n fn = self.fn.fn\n offset = (self.n_seqs + sum(map(len, self.tap_array[:self.n_outs])) +\n self.n_shared_outs)\n for idx in xrange(len(other_args)):\n input_storage[idx + offset].storage[0] = other_args[idx]\n\n i = 0\n cond = True\n ############## THE MAIN LOOP #########################\n # for i in xrange(n_steps):\n while (i < n_steps) and cond:\n # sequences over which scan iterates\n # 3. collect input slices\n for idx in xrange(self.n_seqs):\n if self.vector_seqs[idx]:\n input_storage[idx].storage[0] = \\\n seqs[idx][i:i + 1].reshape(())\n else:\n input_storage[idx].storage[0] = seqs[idx][i]\n\n offset = self.n_seqs\n for idx in xrange(self.n_outs):\n if self.vector_outs[idx]:\n for tap in self.tap_array[idx]:\n _idx = (pos[idx] + tap) % store_steps[idx]\n input_storage[offset].storage[0] =\\\n outs[idx][0][_idx:_idx + 1].reshape(())\n offset += 1\n else:\n for tap in self.tap_array[idx]:\n _idx = (pos[idx] + tap) % store_steps[idx]\n input_storage[offset].storage[0] = outs[idx][0][_idx]\n offset += 1\n\n a_offset = self.shared_arg_offset\n o_offset = self.n_outs + self.n_nit_sot\n if i == 0:\n for j in xrange(self.n_shared_outs):\n input_storage[offset].storage[0] = args[a_offset + j]\n offset += 1\n else:\n for j in xrange(self.n_shared_outs):\n input_storage[offset].storage[0] = outs[o_offset + j][0]\n offset += 1\n\n # 4. collecting slices where the output should be stored\n\n # 4.1. Collect slices for mitmots\n for idx in xrange(self.n_mit_mot_outs):\n output_storage[idx].storage[0] = None\n\n # 4.2. Collect slices for mitsots, sitsots and nitsots\n offset = self.n_mit_mot_outs\n if i != 0:\n for idx in xrange(self.n_outs + self.n_nit_sot -\n self.n_mit_mot):\n if (store_steps[idx + self.n_mit_mot] == 1 or\n self.vector_outs[idx + self.n_mit_mot]):\n output_storage[idx + offset].storage[0] = None\n else:\n _pos0 = idx + self.n_mit_mot\n output_storage[idx + offset].storage[0] =\\\n outs[_pos0][0][pos[_pos0]]\n else:\n for idx in xrange(self.n_outs + self.n_nit_sot -\n self.n_mit_mot):\n output_storage[idx + offset].storage[0] = None\n\n # 4.3. Collect slices for shared outputs\n offset += self.n_outs + self.n_nit_sot - self.n_mit_mot\n for idx in xrange(self.n_shared_outs):\n output_storage[idx + offset].storage[0] = None\n\n # 4.4. If there is a condition add it to the mix\n if self.as_while:\n pdx = offset + self.n_shared_outs\n output_storage[pdx].storage[0] = None\n\n # 4.5. Keep a reference to the variables (ndarrays, CudaNdarrays,\n # etc) currently in the output_storage to be able to compare them\n # with the actual outputs of the inner function after its\n # execution. Also keep pointers to their data to be able to detect\n # cases where outputs reused the allocated object but alter the\n # memory region they refer to.\n for idx in xrange(len(output_storage)):\n\n var = output_storage[idx].storage[0]\n old_output_storage[idx] = var\n\n if hasattr(var, 'gpudata'):\n old_output_data[idx] = var.gpudata\n elif hasattr(var, 'data'):\n old_output_data[idx] = var.data\n else:\n old_output_data[idx] = None\n\n # 5. compute outputs\n t0_fn = time.time()\n\n try:\n fn()\n except Exception:\n if hasattr(fn, 'position_of_error'):\n # this is a new vm-provided function or c linker\n # they need this because the exception manipulation\n # done by raise_with_op is not implemented in C.\n if hasattr(fn, 'thunks'):\n # For the CVM\n gof.link.raise_with_op(fn.nodes[fn.position_of_error],\n fn.thunks[fn.position_of_error])\n else:\n # For the c linker\n # We don't have access from python to all the\n # temps values So for now, we just don't print\n # the extra shapes/strides info\n gof.vm.raise_with_op(fn.nodes[fn.position_of_error])\n else:\n # old-style linkers raise their own exceptions\n raise\n\n dt_fn = time.time() - t0_fn\n if self.as_while:\n pdx = offset + self.n_shared_outs\n cond = output_storage[pdx].storage[0] == 0\n\n # Check which of the pre-allocated outputs (if applicable) have\n # been reused by the inner function\n for idx in xrange(len(output_storage)):\n # If the storage map does not contain the same object, then\n # the pre-allocated output has not been reused\n new_var = output_storage[idx].storage[0]\n if old_output_storage[idx] is new_var:\n\n # The pre-allocated output is only considered as having\n # been reused if it still points to the same data as it\n # did before the execution of the inner function\n if old_output_data[idx] is None:\n output_reused[idx] = False\n else:\n if hasattr(new_var, 'gpudata'):\n output_reused[idx] = (new_var.gpudata ==\n old_output_data[idx])\n elif hasattr(new_var, 'data'):\n output_reused[idx] = (new_var.data ==\n old_output_data[idx])\n else:\n output_reused[idx] = False\n\n t_fn += dt_fn\n offset_out = 0\n # 5.1 Copy over the values for mit_mot outputs\n for j in xrange(self.n_mit_mot):\n for k in self.mit_mot_out_slices[j]:\n outs[j][0][k + pos[j]] = \\\n output_storage[offset_out].storage[0]\n offset_out += 1\n\n # 5.2 Copy over the values for mit_sot/sit_sot outputs\n begin = self.n_mit_mot\n end = self.n_outs\n offset_out -= self.n_mit_mot\n\n for j in xrange(begin, end):\n if (store_steps[j] == 1 or self.vector_outs[j] or\n not output_reused[offset_out + j]):\n outs[j][0][pos[j]] = \\\n output_storage[offset_out + j].storage[0]\n\n # 5.3 Copy over the values for nit_sot outputs\n begin = end\n end += self.n_nit_sot\n for j in xrange(begin, end):\n if i == 0:\n jout = j + offset_out\n shape = (store_steps[j],) + \\\n output_storage[jout].storage[0].shape\n if len(output_storage[jout].storage[0].shape) == 0:\n self.vector_outs[j] = True\n dtype = output_storage[jout].storage[0].dtype\n if (outs[j][0] is None or\n outs[j][0].shape[0] < store_steps[j] or\n outs[j][0].shape[1:] != shape[1:] or\n outs[j][0].dtype != dtype):\n outs[j][0] = node.outputs[j].type.value_zeros(shape)\n elif outs[j][0].shape[0] != store_steps[j]:\n outs[j][0] = outs[j][0][:store_steps[j]]\n outs[j][0][pos[j]] = output_storage[jout].storage[0]\n elif (store_steps[j] == 1 or self.vector_outs[j] or\n not output_reused[offset_out + j]):\n outs[j][0][pos[j]] = \\\n output_storage[j + offset_out].storage[0]\n\n # 5.4 Copy over the values for outputs corresponding to shared\n # variables\n begin = end\n end += self.n_shared_outs\n for j in xrange(begin, end):\n jout = j + offset_out\n outs[j][0] = output_storage[jout].storage[0]\n\n pos = [(idx + 1) % store for idx, store in\n izip(pos, store_steps)]\n i = i + 1\n\n # 6. Check if you need to re-order output buffers\n begin = self.n_mit_mot\n end = self.n_outs + self.n_nit_sot\n for idx in xrange(begin, end):\n if (store_steps[idx] < i - self.mintaps[idx] and\n pos[idx] < store_steps[idx]):\n\n pdx = pos[idx]\n if pdx >= store_steps[idx] // 2:\n # It seems inefficient to copy the bigger part of the\n # array over, and back, but it is the only way that\n # there is no overlap in the areas of out[idx][0] that\n # are read and written.\n # This way, there will be no information overwritten\n # before it is read (as it used to happen).\n shape = (pdx,) + outs[idx][0].shape[1:]\n tmp = node.outputs[idx].type.value_zeros(shape)\n tmp[:] = outs[idx][0][:pdx]\n outs[idx][0][:store_steps[idx] - pdx] = outs[idx][0][pdx:]\n outs[idx][0][store_steps[idx] - pdx:] = tmp\n del tmp\n else:\n shape = (store_steps[idx] - pdx,) + outs[idx][0].shape[1:]\n tmp = node.outputs[idx].type.value_zeros(shape)\n tmp[:] = outs[idx][0][pdx:]\n outs[idx][0][store_steps[idx] - pdx:] = outs[idx][0][:pdx]\n outs[idx][0][:store_steps[idx] - pdx] = tmp\n del tmp\n # This would normally happen only when doing truncated\n # backpropagation through time. In such a scenarion Scan is\n # expected to return 0 for all entries for which the gradient is\n # not actually computed\n elif store_steps[idx] > i - self.mintaps[idx]:\n outs[idx][0][i - self.mintaps[idx]:] = 0\n # This is a fix for a bug introduced by while. If you say\n # you want to loop up to a condition, you expect the output\n # to have that length ( and not the maximal length possible)\n #\n # Without this the behaviour of a scan op is not consistent\n # if optimization gets applied compared to when optimization\n # do not get applied\n if i < n_steps:\n # The reason I don't use out[idx][0][:i] is because for\n # certain outputs (those with multiple taps),\n # outs[idx][0] has more than n_steps entries, with the\n # initial state at the begining. When indexing in it I\n # usually have to do something like\n # outs[idx][0][i+offset]. To do something similar here,\n # I would have first to compute the maximal tap for\n # every output and then do outs[0][:i+maximal_tap],\n # which implies I think more computations then this\n # little trick that I used\n outs[idx][0] = outs[idx][0][:-(n_steps - i)]\n\n # We never reuse the input or output storage of the\n # inner function so we clear it.\n for i_s in input_storage:\n i_s.storage[0] = None\n for o_s in output_storage:\n o_s.storage[0] = None\n\n t_call = time.time() - t0_call\n # NOTE: make this match what's in function_module.Function\n # and this little string helps us to find this spot:\n # \"PROFILE_CODE\"\n\n if hasattr(self.fn.maker, 'profile') and self.fn.maker.profile:\n profile = self.fn.maker.profile\n profile.callcount += 1\n profile.nbsteps += n_steps\n profile.call_time += t_call\n profile.vm_call_time += t_fn\n if hasattr(self.fn.fn, 'update_profile'):\n self.fn.fn.update_profile(profile)\n\n #/* Old ProfileMode\n # if hasattr(self.fn.maker.mode,'fct_call_time'):\n # self.fn.maker.mode.fct_call_time[self.fn] += t_fn\n # self.fn.maker.mode.fct_call[self.fn] += n_steps\n\n #self.fn.maker.mode.call_time += t_fn\n #self.fn.maker.mode.fn_time += t_fn\n # Old Profile Mode */\n self.t_call = t_call\n self.t_fn = t_fn\n\n # Infer Shape\n def infer_shape(self, node, input_shapes):\n # input_shapes correspond to the shapes of node.inputs\n # Here, we build a list inner_ins_shape, such that inner_ins_shape[i]\n # is the shape of self.inputs[i]\n\n for inp, inp_shp in izip(node.inputs, input_shapes):\n assert inp_shp is None or len(inp_shp) == inp.type.ndim\n\n # sequences\n # We skip iputs_shapes[0] as it is the total or current number\n # of iterations.\n seqs_shape = [x[1:] for x in input_shapes[1:1 + self.n_seqs]]\n\n # mit_mot, mit_sot, sit_sot\n n_outs = self.n_mit_mot + self.n_mit_sot + self.n_sit_sot\n outs_shape = []\n for idx in xrange(n_outs):\n for k in self.tap_array[idx]:\n outs_shape += [input_shapes[idx + self.n_seqs + 1][1:]]\n\n # shared_outs\n offset = 1 + self.n_seqs + n_outs\n for idx in xrange(self.n_shared_outs):\n outs_shape += [input_shapes[idx + offset]]\n\n # non_sequences\n offset += self.n_nit_sot + self.n_shared_outs\n inner_ins_shapes = seqs_shape + outs_shape + input_shapes[offset:]\n assert len(inner_ins_shapes) == len(self.inputs)\n\n # Non-sequences have a direct equivalent from self.inputs in\n # node.inputs\n inner_non_sequences = self.inputs[len(seqs_shape) + len(outs_shape):]\n out_equivalent = OrderedDict()\n for in_ns, out_ns in izip(inner_non_sequences, node.inputs[offset:]):\n out_equivalent[in_ns] = out_ns\n if self.as_while:\n self_outs = self.outputs[:-1]\n else:\n self_outs = self.outputs\n outs_shape = scan_utils.infer_shape(\n outs=self_outs,\n inputs=self.inputs,\n input_shapes=inner_ins_shapes)\n # Will be used to check if outs_shape can be expressed without using\n # variables in self.inputs.\n # The shapes of node.inputs are valid.\n validator = scan_utils.Validator(\n valid=input_shapes,\n invalid=self.inputs,\n valid_equivalent=out_equivalent)\n\n offset = 1 + self.n_seqs\n scan_outs = [x for x in input_shapes[offset:offset + n_outs]]\n offset += n_outs\n outs_shape_n = self.n_mit_mot_outs + self.n_mit_sot + self.n_sit_sot\n for x in xrange(self.n_nit_sot):\n out_shape_x = outs_shape[outs_shape_n + x]\n if out_shape_x is None:\n # This output is not a tensor, and has no shape\n scan_outs.append(None)\n else:\n # We need to make sure that we can compute the shapes from\n # node.inputs, and constants, without using the variables\n # in the inner function.\n r = node.outputs[n_outs + x]\n assert r.ndim == 1 + len(out_shape_x)\n shp = [node.inputs[offset + self.n_shared_outs + x]]\n for i, shp_i in izip(xrange(1, r.ndim), out_shape_x):\n # Validate shp_i. v_shape_i is either None (if invalid),\n # or a (variable, Boolean) tuple. The Boolean indicates\n # whether variable is shp_i (if True), or an valid\n # equivalent (if False). Here, we only need the variable.\n v_shp_i = validator.check(shp_i)\n if v_shp_i is None:\n if hasattr(r, 'broadcastable') and r.broadcastable[i]:\n shp.append(1)\n else:\n shp.append(Shape_i(i)(r))\n else:\n # It can (or at least, an equivalent variable can)\n shp.append(v_shp_i[0])\n scan_outs.append(tuple(shp))\n\n scan_outs += [x for x in\n input_shapes[offset:offset + self.n_shared_outs]]\n # if we are dealing with a repeat-until, then we do not know the\n # leading dimension so we replace it for every entry with Shape_i\n if self.as_while:\n scan_outs_init = scan_outs\n scan_outs = []\n for o, x in izip(node.outputs, scan_outs_init):\n if x is None:\n scan_outs.append(None)\n else:\n scan_outs.append((Shape_i(0)(o),) + x[1:])\n return scan_outs\n\n def connection_pattern(self, node):\n\n # We cache the result of this function because, with a previous\n # implementation that repeatedly called grad, there were cases\n # where calls to theano.grad() took as much as 4h for functions\n # containing many nested scans.\n if hasattr(node.tag, 'connection_pattern'):\n return node.tag.connection_pattern\n\n # Obtain the connection pattern of the inner function.\n inner_connect_pattern = io_connection_pattern(self.inputs, self.outputs)\n\n # Initially assume no outer input is connected to any outer output\n connection_pattern = [[False for output in node.outputs]\n for x in node.inputs]\n\n # For every possible pair of outer input and outer output, iterate\n # over every possible pairing of their corresponding inner inputs\n # and inner outputs and, if one such pair of inner variables is\n # connected than the pair of outer variables is connected.\n for outer_oidx in xrange(len(node.outputs)):\n inner_oidxs = self.var_mappings['inner_out_from_outer_out'][outer_oidx]\n\n for outer_iidx in xrange(len(node.inputs)):\n inner_iidxs = self.var_mappings['inner_inp_from_outer_inp'][outer_iidx]\n\n for inner_oidx in inner_oidxs:\n for inner_iidx in inner_iidxs:\n\n if inner_connect_pattern[inner_iidx][inner_oidx]:\n connection_pattern[outer_iidx][outer_oidx] = True\n break\n\n if connection_pattern[outer_iidx][outer_oidx]:\n break\n\n # Applying Floyd-Warshall to find all paths connecting inputs to\n # outputs. Note that if `x` is an input to `y_t` and `y_tm1` is an\n # input to `z_t` then `x` is an input to `z_t`.\n\n n_outs = len(node.outputs)\n\n for steps in xrange(n_outs):\n for iidx in xrange(n_outs):\n for jidx in xrange(n_outs):\n\n # Get the idx of the outer input corresponding to that\n # outer output\n j_inp_idx = self.var_mappings[\"outer_inp_from_outer_out\"][jidx]\n\n if j_inp_idx != -1:\n if connection_pattern[j_inp_idx][iidx] == True:\n for k in xrange(len(connection_pattern)):\n if connection_pattern[k][jidx]:\n connection_pattern[k][iidx] = True\n\n node.tag.connection_pattern = connection_pattern\n return connection_pattern\n\n def get_oinp_iinp_iout_oout_mappings(self):\n \"\"\" Compute and return dictionary mappings between the inputs and\n outputs of the inner function and the inputs and outputs of the Scan\n node in the outer graph.\n\n The return value is a dictionary in which the keys are the names of\n the individual mappings and the values are the mapping dictionaries\n themselves. In dictionaries representing mappings to outer variables,\n the values are individual integer indices. In dictionaries\n representing mappings to inner variables, the values are sequences of\n indices because multiple inner variables can be associated with the\n same state\n \"\"\"\n # Lists for outer variables contain individual indices, lists for\n # inner variables contain sequences of indices because many inner\n # variables can be associated with the same outer variable. The list\n # and indices are initialized already containing the data associated\n # with the timestep index, the first outer input.\n outer_input_indices = [0]\n inner_input_indices = [[]]\n inner_output_indices = [[]]\n outer_output_indices = [-1]\n\n outer_iidx = 1\n inner_iidx = 0\n inner_oidx = 0\n outer_oidx = 0\n\n # Handle sequences inputs\n for i in xrange(self.info['n_seqs']):\n outer_input_indices.append(outer_iidx)\n inner_input_indices.append([inner_iidx])\n inner_output_indices.append([])\n outer_output_indices.append(-1)\n\n outer_iidx += 1\n inner_iidx += 1\n inner_oidx += 0\n outer_oidx += 0\n\n # Handle mitmots, mitsots and sitsots variables\n for i in xrange(len(self.info['tap_array'])):\n nb_input_taps = len(self.info['tap_array'][i])\n\n if i < self.n_mit_mot:\n nb_output_taps = len(self.mit_mot_out_slices[i])\n else:\n nb_output_taps = 1\n\n outer_input_indices.append(outer_iidx)\n inner_input_indices.append(list(range(inner_iidx,\n inner_iidx + nb_input_taps)))\n inner_output_indices.append(list(range(inner_oidx,\n inner_oidx + nb_output_taps)))\n outer_output_indices.append(outer_oidx)\n\n outer_iidx += 1\n inner_iidx += nb_input_taps\n inner_oidx += nb_output_taps\n outer_oidx += 1\n\n # This is needed because, for outer inputs (and for outer inputs only)\n # nitsots come *after* shared variables.\n outer_iidx += self.info['n_shared_outs']\n\n # Handle nitsots variables\n for i in xrange(self.n_nit_sot):\n outer_input_indices.append(outer_iidx)\n inner_input_indices.append([])\n inner_output_indices.append([inner_oidx])\n outer_output_indices.append(outer_oidx)\n\n outer_iidx += 1\n inner_iidx += 0\n inner_oidx += 1\n outer_oidx += 1\n\n # This is needed because, for outer inputs (and for outer inputs only)\n # nitsots come *after* shared variables.\n outer_iidx -= (self.info['n_shared_outs'] + self.n_nit_sot)\n\n # Handle shared states\n for i in xrange(self.info['n_shared_outs']):\n outer_input_indices.append(outer_iidx)\n inner_input_indices.append([inner_iidx])\n inner_output_indices.append([inner_oidx])\n outer_output_indices.append(outer_oidx)\n\n outer_iidx += 1\n inner_iidx += 1\n inner_oidx += 1\n outer_oidx += 1\n\n # This is needed because, for outer inputs (and for outer inputs only)\n # nitsots come *after* shared variables.\n outer_iidx += self.n_nit_sot\n\n # Handle non-sequence inputs\n # Note : the number of non-sequence inputs is not stored in self.info\n # so it has to be inferred from the number of inner inputs that remain\n # to be handled\n for i in xrange(len(self.inputs) - inner_iidx):\n outer_input_indices.append(outer_iidx)\n inner_input_indices.append([inner_iidx])\n inner_output_indices.append([])\n outer_output_indices.append(-1)\n\n outer_iidx += 1\n inner_iidx += 1\n inner_oidx += 0\n outer_oidx += 0\n\n # With the global mapping inferred, the individual mappings\n # can be produced\n mappings = {\"outer_inp_from_outer_out\" : {},\n \"inner_inp_from_outer_out\" : {},\n \"inner_out_from_outer_out\" : {},\n \"inner_inp_from_outer_inp\" : {},\n \"inner_out_from_outer_inp\" : {},\n \"outer_out_from_outer_inp\" : {},\n \"outer_inp_from_inner_inp\" : {},\n \"inner_out_from_inner_inp\" : {},\n \"outer_out_from_inner_inp\" : {},\n \"outer_inp_from_inner_out\" : {},\n \"inner_inp_from_inner_out\" : {},\n \"outer_out_from_inner_out\" : {}}\n\n for (oinp, iinp, iout, oout) in izip(outer_input_indices,\n inner_input_indices,\n inner_output_indices,\n outer_output_indices):\n\n if oout != -1:\n mappings[\"outer_inp_from_outer_out\"][oout] = oinp\n mappings[\"inner_inp_from_outer_out\"][oout] = iinp\n mappings[\"inner_out_from_outer_out\"][oout] = iout\n\n if oinp != -1:\n mappings[\"inner_inp_from_outer_inp\"][oinp] = iinp\n mappings[\"inner_out_from_outer_inp\"][oinp] = iout\n mappings[\"outer_out_from_outer_inp\"][oinp] = oout\n\n for idx in iinp:\n mappings[\"outer_inp_from_inner_inp\"][idx] = oinp\n mappings[\"inner_out_from_inner_inp\"][idx] = iout\n mappings[\"outer_out_from_inner_inp\"][idx] = oout\n\n for idx in iout:\n mappings[\"outer_inp_from_inner_out\"][idx] = oinp\n mappings[\"inner_inp_from_inner_out\"][idx] = iinp\n mappings[\"outer_out_from_inner_out\"][idx] = oout\n\n return mappings\n\n # GRAD FUNCTION\n def grad(self, inputs, dC_douts):\n outs = self(*inputs)\n if not isinstance(outs, (list, tuple)):\n outs = [outs]\n # `grad_step` equals the number of steps the original scan node has\n # done (if the original scan is a while loop than this number is the\n # length of the output sequence)\n # We do not know what kind of outputs the original scan has, so we\n # try first to see if it has a nit_sot output, then a sit_sot and\n # then a mit_sot\n if self.n_nit_sot > 0:\n grad_steps = self.outer_nitsot_outs(outs)[0].shape[0]\n elif self.n_sit_sot > 0:\n grad_steps = self.outer_sitsot_outs(outs)[0].shape[0] - 1\n elif self.n_mit_sot > 0:\n grad_steps = self.outer_mitsot_outs(outs)[0].shape[0] +\\\n self.mintaps[self.n_mit_mot]\n else:\n grad_steps = inputs[0]\n\n # Restrict the number of grad steps according to\n # self.truncate_gradient\n if self.truncate_gradient != -1:\n grad_steps = tensor.minimum(grad_steps, self.truncate_gradient)\n\n rval = scan_utils.reconstruct_graph(self.inputs,\n self.outputs)\n self_inputs = rval[0]\n self_outputs = rval[1]\n # differentiable inputs\n diff_inputs = (self.inner_seqs(self_inputs) +\n self.inner_mitmot(self_inputs) +\n self.inner_mitsot(self_inputs) +\n self.inner_sitsot(self_inputs) +\n self.inner_non_seqs(self_inputs))\n diff_outputs = (self.inner_mitmot_outs(self_outputs) +\n self.inner_mitsot_outs(self_outputs) +\n self.inner_sitsot_outs(self_outputs) +\n self.inner_nitsot_outs(self_outputs))\n scan_node = outs[0].owner\n connection_pattern = self.connection_pattern(scan_node)\n\n def get_inp_idx(iidx):\n if iidx < self.n_seqs:\n return 1 + iidx\n oidx = 1 + self.n_seqs\n iidx = iidx - self.n_seqs\n for taps in self.mitmot_taps():\n if len(taps) > iidx:\n return oidx\n else:\n oidx += 1\n iidx -= len(taps)\n for taps in self.mitsot_taps():\n if len(taps) > iidx:\n return oidx\n else:\n oidx += 1\n iidx -= len(taps)\n\n if iidx < self.info['n_sit_sot']:\n return oidx + iidx\n else:\n return oidx + iidx + self.info['n_nit_sot']\n\n def get_out_idx(iidx):\n oidx = 0\n for taps in self.mitmot_out_taps():\n if len(taps) > iidx:\n return oidx\n else:\n oidx += 1\n iidx -= len(taps)\n return oidx + iidx\n\n def compute_gradient(y, g_y):\n if 'int' in str(g_y.dtype):\n raise TypeError(\"Gradients may never be integers but g_y \"\n \"has type \" + str(g_y.type))\n\n odx = get_out_idx(self_outputs.index(y))\n wrt = [x for x in theano.gof.graph.inputs([y])\n if (x in diff_inputs) and\n (connection_pattern[\n get_inp_idx(self_inputs.index(x))][odx])]\n gmp = OrderedDict()\n\n for x in wrt:\n try:\n gmp[x] = gradient.grad(\n cost=None,\n known_grads={y: g_y},\n wrt=x,\n consider_constant=wrt,\n disconnected_inputs='ignore',\n return_disconnected='None')\n except gradient.NullTypeGradError as e:\n # The gradient wrt that particular input is undefined.\n # This is not necessarily an issue, because maybe that\n # particular input is not in the path between the\n # \"cost\" and \"wrt\" of the external, initial call to grad().\n # We simply return a Null gradient, forwarding the message.\n gmp[x] = NullType((\n \"This variable is Null because the grad method on the \"\n \"inner graph of the Scan node %s returned Null for \"\n \"the corresponding inner input variable. The original \"\n \"message was: %s\"\n % (str(self), exc_message(e))))()\n\n rval = [gmp.get(p, None) for p in diff_inputs]\n return rval\n\n dC_dinps_t = [None for inp in diff_inputs]\n disconnected_dC_dinps_t = [True for inp in diff_inputs]\n dC_dXts = []\n Xts = []\n for idx, Xt in enumerate(diff_outputs):\n\n # We are looking for x[t-1] for a given x[t]\n if idx >= self.n_mit_mot_outs:\n Xt_placeholder = safe_new(Xt)\n Xts.append(Xt_placeholder)\n\n # Different processing based on whether Xt is a nitsot output\n # or not. NOTE : This cannot be done by using\n # \"if Xt not in self.inner_nitsot_outs(self_outputs)\" because\n # the exact same variable can be used as multiple outputs.\n idx_nitsot_start = (self.info['n_mit_mot'] +\n self.info['n_mit_sot'] +\n self.info['n_sit_sot'])\n idx_nitsot_end = idx_nitsot_start + self.info['n_nit_sot']\n if idx < idx_nitsot_start or idx >= idx_nitsot_end:\n # What we do here is loop through dC_douts and collect all\n # those that are connected to the specific one and do an\n # upcast on all of their dtypes to get the dtype for this\n # specific output. Deciding if the gradient with this\n # specific previous step is defined or not is done somewhere\n # else.\n dtypes = []\n states = (self.inner_mitmot(self_inputs) +\n self.inner_mitsot(self_inputs) +\n self.inner_sitsot(self_inputs))\n\n for pos, inp in enumerate(states):\n if inp in theano.gof.graph.inputs([Xt]):\n # Get the index of the outer output that to which\n # the state variable 'inp' corresponds.\n outer_oidx = self.var_mappings['outer_out_from_inner_inp'][self.n_seqs +\n pos]\n\n if not isinstance(dC_douts[outer_oidx].type,\n DisconnectedType):\n dtypes.append(dC_douts[outer_oidx].dtype)\n if dtypes:\n new_dtype = theano.scalar.upcast(*dtypes)\n else:\n new_dtype = theano.config.floatX\n dC_dXt = safe_new(Xt, dtype=new_dtype)\n else:\n if isinstance(dC_douts[idx].type, DisconnectedType):\n continue\n dC_dXt = safe_new(dC_douts[idx][0])\n dC_dXts.append(dC_dXt)\n _dC_dinps_t = compute_gradient(Xt, dC_dXt)\n for jdx in xrange(len(_dC_dinps_t)):\n if dC_dinps_t[jdx] is None:\n dC_dinps_t[jdx] = _dC_dinps_t[jdx]\n elif isinstance(dC_dinps_t[jdx].type, NullType):\n # The accumulated gradient is undefined\n pass\n elif _dC_dinps_t[jdx]:\n if isinstance(_dC_dinps_t[jdx].type, NullType):\n # The accumulated gradient is defined, but the new\n # term is undefined. The whole thing has to be undefined.\n dC_dinps_t[jdx] = _dC_dinps_t[jdx]\n else:\n dC_dinps_t[jdx] += _dC_dinps_t[jdx]\n\n # mask inputs that get no gradients\n for dx in xrange(len(dC_dinps_t)):\n if not dC_dinps_t[dx]:\n dC_dinps_t[dx] = tensor.zeros_like(diff_inputs[dx])\n else:\n disconnected_dC_dinps_t[dx] = False\n for Xt, Xt_placeholder in zip(\n diff_outputs[self.n_mit_mot_outs:],\n Xts):\n tmp = forced_replace(\n dC_dinps_t[dx],\n Xt,\n Xt_placeholder)\n dC_dinps_t[dx] = tmp\n\n # construct dX_dtm1\n dC_dXtm1s = []\n for pos, x in enumerate(dC_dinps_t[self.n_seqs:]):\n\n # Get the index of the first inner input corresponding to the\n # pos-ieth inner input state\n idxs = self.var_mappings['inner_out_from_inner_inp'][self.n_seqs +\n pos]\n\n # Check if the pos-th input is associated with one of the\n # recurrent states\n x_is_state = pos < sum([len(t) for t in self.tap_array])\n\n if x_is_state and len(idxs) > 0:\n opos = idxs[0]\n dC_dXtm1s.append(safe_new(dC_dXts[opos]))\n if hasattr(x, 'dtype') and x.dtype != dC_dXts[opos].dtype:\n dC_dinps_t[pos + self.n_seqs] = \\\n x.astype(dC_dXts[opos].dtype)\n else:\n dC_dXtm1s.append(safe_new(x))\n\n for dx, dC_dXtm1 in enumerate(dC_dXtm1s):\n if isinstance(dC_dinps_t[dx + self.n_seqs].type, NullType):\n # The accumulated gradient is undefined\n pass\n elif isinstance(dC_dXtm1.type, NullType):\n # The new gradient is undefined, this makes the accumulated\n # gradient undefined as weell\n dC_dinps_t[dx + self.n_seqs] = dC_dXtm1\n else:\n dC_dinps_t[dx + self.n_seqs] += dC_dXtm1\n # Construct scan op\n # Seqs\n outer_inp_seqs = [x[::-1] for x in inputs[1:1 + self.n_seqs]]\n for idx in xrange(self.n_mit_mot + self.n_mit_sot):\n mintap = numpy.min(self.tap_array[idx])\n maxtap = numpy.max(self.tap_array[idx])\n if idx < self.n_mit_mot:\n outmaxtap = numpy.max(self.mitmot_out_taps()[idx])\n else:\n outmaxtap = 0\n seq = outs[idx]\n for k in self.tap_array[idx]:\n if outmaxtap - k != 0:\n nw_seq = seq[k - mintap: -(outmaxtap-k)][::-1]\n else:\n nw_seq = seq[k - mintap:][::-1]\n outer_inp_seqs.append(nw_seq)\n outer_inp_seqs += [\n x[:-1][::-1] for x in self.outer_sitsot_outs(outs)]\n for x in self.outer_nitsot_outs(dC_douts):\n if not isinstance(x.type, DisconnectedType):\n outer_inp_seqs.append(x[::-1])\n\n if hasattr(inputs[0].tag, 'test_value'):\n # Here we tests that the new scan input sequence all have\n # the same shape[0]. This is a properties that the scan()\n # fct add and we want to keep it for all Scan op. This is\n # used in T_Scan.test_grad_multiple_outs_taps to test\n # that.\n for taps, x in zip(self.mitsot_taps(),\n self.outer_mitsot_outs(outs)):\n mintap = numpy.min(taps)\n if hasattr(x[::-1][:mintap], 'test_value'):\n assert (x[::-1][:mintap].tag.test_value.shape[0] ==\n inputs[0].tag.test_value)\n for x in self.outer_sitsot_outs(outs):\n if hasattr(x[::-1][:-1].tag, 'test_value'):\n assert (x[::-1][:-1].tag.test_value.shape[0] ==\n inputs[0].tag.test_value)\n for x in self.outer_nitsot_outs(outs):\n if hasattr(x[::-1].tag, 'test_value'):\n assert (x[::-1].tag.test_value.shape[0] ==\n inputs[0].tag.test_value)\n outer_inp_seqs += [x[::-1][:numpy.min(taps)]\n for taps, x in zip(self.mitsot_taps(),\n self.outer_mitsot_outs(outs))]\n outer_inp_seqs += [x[::-1][:-1] for x in self.outer_sitsot_outs(outs)]\n outer_inp_seqs += [x[::-1] for x in self.outer_nitsot_outs(outs)]\n\n # Restrict the length of the outer sequences to the number of grad\n # steps\n outer_inp_seqs = [seq[:grad_steps] for seq in outer_inp_seqs]\n\n inner_inp_seqs = self.inner_seqs(self_inputs)\n inner_inp_seqs += self.inner_mitmot(self_inputs)\n inner_inp_seqs += self.inner_mitsot(self_inputs)\n inner_inp_seqs += self.inner_sitsot(self_inputs)\n inner_inp_seqs += self.inner_nitsot_outs(dC_dXts)\n inner_inp_seqs += Xts\n # mitmot\n outer_inp_mitmot = []\n outer_out_mitmot = []\n inner_inp_mitmot = []\n inner_out_mitmot = []\n mitmot_inp_taps = []\n mitmot_out_taps = []\n type_outs = []\n out_pos = 0\n ins_pos = self.n_seqs\n n_mitmot_outs = 0\n n_mitmot_inps = 0\n\n for idx in xrange(self.n_mit_mot):\n if isinstance(dC_douts[idx].type, DisconnectedType):\n out = outs[idx]\n outer_inp_mitmot.append(tensor.zeros_like(out))\n else:\n outer_inp_mitmot.append(dC_douts[idx][::-1])\n mitmot_inp_taps.append([])\n mitmot_out_taps.append([])\n undefined_msg = None\n through_shared = False\n disconnected = True\n for jdx in xrange(len(self.mit_mot_out_slices[idx])):\n inner_inp_mitmot.append(dC_dXts[out_pos])\n mitmot_inp_taps[idx].append(-self.mit_mot_out_slices[idx][jdx])\n n_mitmot_inps += 1\n out_pos += 1\n\n for jdx in xrange(len(self.tap_array[idx])):\n inner_inp_mitmot.append(dC_dXtm1s[ins_pos - self.n_seqs])\n if isinstance(dC_dinps_t[ins_pos].type, NullType):\n # We cannot use Null in the inner graph, so we\n # use a zero tensor of the appropriate shape instead.\n inner_out_mitmot.append(\n tensor.zeros(diff_inputs[ins_pos].shape,\n dtype=theano.config.floatX))\n undefined_msg = dC_dinps_t[ins_pos].type.why_null\n else:\n inner_out_mitmot.append(dC_dinps_t[ins_pos])\n\n if not disconnected_dC_dinps_t[ins_pos]:\n disconnected = False\n\n for _sh in self.inner_shared(self_inputs):\n if _sh in gof.graph.inputs([dC_dinps_t[ins_pos]]):\n through_shared = True\n\n n_mitmot_inps += 1\n ins_pos += 1\n n_mitmot_outs += 1\n mitmot_inp_taps[idx].append(-self.tap_array[idx][jdx])\n mitmot_out_taps[idx].append(-self.tap_array[idx][jdx])\n\n if undefined_msg:\n type_outs.append(undefined_msg)\n elif through_shared:\n type_outs.append('through_shared')\n elif disconnected:\n type_outs.append('disconnected')\n else:\n type_outs.append('connected')\n\n offset = self.n_mit_mot\n for idx in xrange(self.n_mit_sot):\n if isinstance(dC_douts[idx + offset].type, DisconnectedType):\n outer_inp_mitmot.append(outs[idx + offset].zeros_like())\n else:\n outer_inp_mitmot.append(dC_douts[idx + offset][::-1])\n mitmot_inp_taps.append([])\n mitmot_out_taps.append([])\n idx_tap = idx + self.n_mit_mot\n inner_inp_mitmot.append(dC_dXts[out_pos])\n out_pos += 1\n n_mitmot_inps += 1\n undefined_msg = None\n through_shared = False\n disconnected = True\n mitmot_inp_taps[idx + offset].append(0)\n for jdx in xrange(len(self.tap_array[idx_tap])):\n inner_inp_mitmot.append(dC_dXtm1s[ins_pos - self.n_seqs])\n\n if isinstance(dC_dinps_t[ins_pos].type, NullType):\n # We cannot use Null in the inner graph, so we\n # use a zero tensor of the appropriate shape instead.\n inner_out_mitmot.append(\n tensor.zeros(diff_inputs[ins_pos].shape,\n dtype=theano.config.floatX))\n undefined_msg = dC_dinps_t[ins_pos].type.why_null\n else:\n inner_out_mitmot.append(dC_dinps_t[ins_pos])\n\n mitmot_inp_taps[idx + offset].append(\n -self.tap_array[idx_tap][jdx])\n mitmot_out_taps[idx].append(\n -self.tap_array[idx_tap][jdx])\n if not disconnected_dC_dinps_t[ins_pos]:\n disconnected = False\n for _sh in self.inner_shared(self_inputs):\n if _sh in gof.graph.inputs([dC_dinps_t[ins_pos]]):\n through_shared = True\n\n n_mitmot_inps += 1\n ins_pos += 1\n n_mitmot_outs += 1\n\n if undefined_msg:\n type_outs.append(undefined_msg)\n elif through_shared:\n type_outs.append('through_shared')\n elif disconnected:\n type_outs.append('disconnected')\n else:\n type_outs.append('connected')\n\n offset += self.n_mit_sot\n for idx in xrange(self.n_sit_sot):\n mitmot_inp_taps.append([0, 1])\n mitmot_out_taps.append([1])\n through_shared = False\n if not isinstance(dC_douts[idx + offset].type, DisconnectedType):\n outer_inp_mitmot.append(dC_douts[idx + offset][::-1])\n else:\n if isinstance(dC_dinps_t[ins_pos].type, NullType):\n # Cannot use dC_dinps_t[ins_pos].dtype, so we use\n # floatX instead, as it is a dummy value that will not\n # be used anyway.\n outer_inp_mitmot.append(\n tensor.zeros(outs[idx + offset].shape,\n dtype=theano.config.floatX))\n else:\n outer_inp_mitmot.append(\n tensor.zeros(outs[idx + offset].shape,\n dtype=dC_dinps_t[ins_pos].dtype))\n\n if isinstance(dC_dinps_t[ins_pos].type, NullType):\n # We cannot use Null in the inner graph, so we\n # use a zero tensor of the appropriate shape instead.\n inner_out_mitmot.append(\n tensor.zeros(diff_inputs[ins_pos].shape,\n dtype=theano.config.floatX))\n else:\n inner_out_mitmot.append(dC_dinps_t[ins_pos])\n\n for _sh in self.inner_shared(self_inputs):\n if _sh in gof.graph.inputs([dC_dinps_t[ins_pos]]):\n through_shared = True\n\n if isinstance(dC_dinps_t[ins_pos].type, NullType):\n type_outs.append(dC_dinps_t[ins_pos].type.why_null)\n elif through_shared:\n type_outs.append('through_shared')\n elif disconnected_dC_dinps_t[ins_pos]:\n type_outs.append('disconnected')\n else:\n type_outs.append('connected')\n\n inner_inp_mitmot += [dC_dXts[out_pos],\n dC_dXtm1s[ins_pos - self.n_seqs]]\n n_mitmot_outs += 1\n out_pos += 1\n ins_pos += 1\n n_mitmot_inps += 2\n\n n_nit_sot = self.n_seqs\n inner_out_nitsot = dC_dinps_t[:self.n_seqs]\n inner_out_sitsot = dC_dinps_t[ins_pos:]\n for _p, vl in enumerate(inner_out_sitsot):\n through_shared = False\n for _sh in self.inner_shared(self_inputs):\n if _sh in gof.graph.inputs([vl]):\n through_shared = True\n if isinstance(vl.type, NullType):\n type_outs.append(vl.type.why_null)\n # Replace the inner output with a zero tensor of\n # the right shape\n inner_out_sitsot[_p] = tensor.zeros(\n diff_inputs[ins_pos + _p].shape,\n dtype=theano.config.floatX)\n elif through_shared:\n type_outs.append('through_shared')\n elif disconnected_dC_dinps_t[_p + ins_pos]:\n type_outs.append('disconnected')\n else:\n type_outs.append('connected')\n\n for _p, vl in enumerate(inner_out_nitsot):\n through_shared = False\n for _sh in self.inner_shared(self_inputs):\n if _sh in gof.graph.inputs([vl]):\n through_shared = True\n if isinstance(vl.type, NullType):\n type_outs.append(vl.type.why_null)\n # Replace the inner output with a zero tensor of\n # the right shape\n inner_out_nitsot[_p] = tensor.zeros(\n diff_inputs[_p].shape,\n dtype=theano.config.floatX)\n\n if through_shared:\n type_outs.append('through_shared')\n elif disconnected_dC_dinps_t[_p]:\n type_outs.append('disconnected')\n else:\n type_outs.append('connected')\n\n inner_inp_sitsot = dC_dXtm1s[ins_pos - self.n_seqs:]\n outer_inp_sitsot = []\n for _idx, y in enumerate(inner_inp_sitsot):\n x = self.outer_non_seqs(inputs)[_idx]\n if isinstance(y.type, NullType):\n # Cannot use dC_dXtm1s.dtype, so we use floatX instead.\n outer_inp_sitsot.append(\n tensor.zeros([grad_steps + 1] +\n [x.shape[i] for i in xrange(x.ndim)],\n dtype=theano.config.floatX))\n # replace y by a zero tensor of the right shape\n inner_inp_sitsot[_idx] = tensor.zeros(\n diff_inputs[ins_pos + _idx].shape,\n dtype=theano.config.floatX)\n\n else:\n outer_inp_sitsot.append(\n tensor.zeros([grad_steps + 1] +\n [x.shape[i] for i in xrange(x.ndim)],\n dtype=y.dtype))\n\n n_sitsot_outs = len(outer_inp_sitsot)\n new_tap_array = mitmot_inp_taps + [[-1] for k in\n xrange(n_sitsot_outs)]\n\n info = OrderedDict()\n info['n_seqs'] = len(outer_inp_seqs)\n info['n_mit_sot'] = 0\n info['tap_array'] = new_tap_array\n info['gpu'] = False\n info['n_mit_mot'] = len(outer_inp_mitmot)\n info['n_mit_mot_outs'] = n_mitmot_outs\n info['mit_mot_out_slices'] = mitmot_out_taps\n info['truncate_gradient'] = self.truncate_gradient\n info['n_sit_sot'] = n_sitsot_outs\n info['n_shared_outs'] = 0\n info['n_nit_sot'] = n_nit_sot\n info['as_while'] = False\n info['profile'] = self.profile\n info['destroy_map'] = OrderedDict()\n if self.name:\n info['name'] = 'grad_of_' + self.name\n else:\n info['name'] = None\n info['mode'] = self.mode\n info['allow_gc'] = self.allow_gc\n\n outer_inputs = ([grad_steps] +\n outer_inp_seqs +\n outer_inp_mitmot +\n outer_inp_sitsot +\n [inputs[0] for x in xrange(n_nit_sot)] +\n self.outer_shared(inputs) +\n self.outer_non_seqs(inputs))\n\n inner_other_args = self_inputs[offset:]\n inner_gfn_ins = (inner_inp_seqs +\n inner_inp_mitmot +\n inner_inp_sitsot +\n self.inner_shared(self_inputs) +\n self.inner_non_seqs(self_inputs))\n inner_gfn_outs = (inner_out_mitmot +\n inner_out_sitsot +\n inner_out_nitsot)\n\n local_op = Scan(inner_gfn_ins, inner_gfn_outs, info)\n outputs = local_op(*outer_inputs)\n if type(outputs) not in (list, tuple):\n outputs = [outputs]\n # Re-order the gradients correctly\n gradients = [DisconnectedType()()]\n\n offset = (self.n_mit_mot +\n self.n_mit_sot +\n self.n_sit_sot +\n n_sitsot_outs)\n for p, (x, t) in enumerate(\n zip(outputs[offset:offset + self.n_seqs],\n type_outs[offset:offset + self.n_seqs])):\n if t == 'connected':\n gradients.append(x[::-1])\n elif t == 'disconnected':\n gradients.append(DisconnectedType()())\n elif t == 'through_shared':\n gradients.append(\n grad_undefined(self,\n p + 1,\n inputs[p + 1],\n 'Depends on a shared variable'))\n else:\n # t contains the \"why_null\" string of a NullType\n gradients.append(NullType(t)())\n\n end = self.n_mit_mot + self.n_mit_sot + self.n_sit_sot\n for p, (x, t) in enumerate(\n zip(outputs[:end], type_outs[:end])):\n if t == 'connected':\n gradients.append(x[::-1])\n elif t == 'disconnected':\n gradients.append(DisconnectedType()())\n elif t == 'through_shared':\n gradients.append(\n grad_undefined(self,\n p + 1 + self.n_seqs,\n inputs[p + 1 + self.n_seqs],\n 'Depends on a shared variable'))\n else:\n # t contains the \"why_null\" string of a NullType\n gradients.append(NullType(t)())\n\n start = len(gradients)\n node = outs[0].owner\n for idx in xrange(self.n_shared_outs):\n disconnected = True\n connected_flags = self.connection_pattern(node)[idx + start]\n for dC_dout, connected in zip(dC_douts, connected_flags):\n if (not isinstance(dC_dout.type, DisconnectedType) and\n connected):\n disconnected = False\n if disconnected:\n gradients.append(DisconnectedType()())\n else:\n gradients.append(grad_undefined(\n self, idx, inputs[idx],\n 'Shared Variable with update'))\n\n start = len(gradients)\n gradients += [DisconnectedType()()\n for x in xrange(self.n_nit_sot)]\n begin = end\n\n end = begin + n_sitsot_outs\n for p, (x, t) in enumerate(\n zip(outputs[begin:end], type_outs[begin:end])):\n if t == 'connected':\n gradients.append(x[-1])\n elif t == 'disconnected':\n gradients.append(DisconnectedType()())\n elif t == 'through_shared':\n gradients.append(\n grad_undefined(self,\n p + begin + 1,\n inputs[p + begin + 1],\n 'Depends on a shared variable'))\n else:\n # t contains the \"why_null\" string of a NullType\n gradients.append(NullType(t)())\n\n # Mask disconnected gradients\n # Ideally we would want to assert that the gradients we are\n # replacing do indeed evaluate to 0, though that is not practical\n # from a computational point of view\n # The gradients of scan are computed replacing Disconnected with 0,\n # because through the recurrence they can become nonzero\n for idx in xrange(len(gradients)):\n disconnected = True\n for kdx in xrange(len(node.outputs)):\n if connection_pattern[idx][kdx] and \\\n not isinstance(dC_douts[kdx].type, DisconnectedType):\n disconnected = False\n if disconnected:\n gradients[idx] = DisconnectedType()()\n return gradients\n\n def R_op(self, inputs, eval_points):\n # Step 0. Don't work on the orignal tensor variables\n rval = scan_utils.reconstruct_graph(self.inputs,\n self.outputs, '_rop')\n self_inputs = rval[0]\n rop_of_inputs = rval[0][:self.n_seqs + self.n_outs] + \\\n rval[0][self.n_seqs + self.n_outs + self.n_shared_outs:]\n self_outputs = rval[1]\n # Step 1. Compute the R_op of the inner function\n inner_eval_points = [scan_utils.safe_new(x, '_evalpoint')\n for x in rop_of_inputs]\n if self.as_while:\n rop_self_outputs = self_outputs[:-1]\n else:\n rop_self_outputs = self_outputs\n if self.info['n_shared_outs'] > 0:\n rop_self_outputs = rop_self_outputs[:-self.info['n_shared_outs']]\n rop_outs = tensor.Rop(rop_self_outputs, rop_of_inputs,\n inner_eval_points)\n if type(rop_outs) not in (list, tuple):\n rop_outs = [rop_outs]\n # Step 2. Figure out what corresponds to what in the scan\n\n # When doing the R-op of scan, you end up having double of each type of\n # input, because for each sequence you need also its eval point, for\n # each mit_mot, mit_sot, sit_sot or other type of inputs the same.\n # Interestingly enough, all these types of eval points behave the same\n # way as the input to which they correspond\n # The only exception is the eval point for the number of sequences, and\n # evan point for the number of nit_sot which I think should just be\n # ignored (?)\n info = OrderedDict()\n info['n_seqs'] = self.n_seqs * 2\n info['n_mit_sot'] = self.n_mit_sot * 2\n info['n_sit_sot'] = self.n_sit_sot * 2\n info['n_mit_mot'] = self.n_mit_mot * 2\n info['n_nit_sot'] = self.n_nit_sot * 2\n info['n_shared_outs'] = self.n_shared_outs\n info['gpu'] = False\n info['as_while'] = self.as_while\n info['profile'] = self.profile\n info['truncate_gradient'] = self.truncate_gradient\n if self.name:\n info['name'] = 'rop_of_' + self.name\n else:\n info['name'] = None\n info['mode'] = self.mode\n info['allow_gc'] = self.allow_gc\n info['mit_mot_out_slices'] = self.mit_mot_out_slices * 2\n info['destroy_map'] = OrderedDict()\n new_tap_array = []\n b = 0\n e = self.n_mit_mot\n new_tap_array += self.tap_array[b:e] * 2\n b = e\n e += self.n_mit_sot\n new_tap_array += self.tap_array[b:e] * 2\n b = e\n e += self.n_sit_sot\n new_tap_array += self.tap_array[b:e] * 2\n info['tap_array'] = new_tap_array\n\n # Sequences ...\n b = 1\n ib = 0\n e = 1 + self.n_seqs\n ie = self.n_seqs\n clean_eval_points = []\n for inp, evp in zip(inputs[b:e], eval_points[b:e]):\n if evp is not None:\n clean_eval_points.append(evp)\n else:\n clean_eval_points.append(inp.zeros_like())\n\n scan_seqs = inputs[b:e] + clean_eval_points\n inner_seqs = self_inputs[ib:ie] + inner_eval_points[ib:ie]\n\n # MIT_MOT sequences ...\n b = e\n e = e + self.n_mit_mot\n ib = ie\n ie = ie + int(numpy.sum([len(x) for x in\n self.tap_array[:self.n_mit_mot]]))\n clean_eval_points = []\n for inp, evp in zip(inputs[b:e], eval_points[b:e]):\n if evp is not None:\n clean_eval_points.append(evp)\n else:\n clean_eval_points.append(inp.zeros_like())\n\n scan_mit_mot = inputs[b:e] + clean_eval_points\n inner_mit_mot = self_inputs[ib:ie] + inner_eval_points[ib:ie]\n\n # MIT_SOT sequences ...\n b = e\n e = e + self.n_mit_sot\n ib = ie\n ie = ie + int(numpy.sum([len(x) for x in\n self.tap_array[self.n_mit_mot:\\\n self.n_mit_mot + self.n_mit_sot]]))\n clean_eval_points = []\n for inp, evp in zip(inputs[b:e], eval_points[b:e]):\n if evp is not None:\n clean_eval_points.append(evp)\n else:\n clean_eval_points.append(inp.zeros_like())\n\n scan_mit_sot = inputs[b:e] + eval_points[b:e]\n inner_mit_sot = self_inputs[ib:ie] + inner_eval_points[ib:ie]\n\n # SIT_SOT sequences ...\n b = e\n e = e + self.n_sit_sot\n ib = ie\n ie = ie + self.n_sit_sot\n clean_eval_points = []\n for inp, evp in zip(inputs[b:e], eval_points[b:e]):\n if evp is not None:\n clean_eval_points.append(evp)\n else:\n clean_eval_points.append(inp.zeros_like())\n\n scan_sit_sot = inputs[b:e] + clean_eval_points\n inner_sit_sot = self_inputs[ib:ie] + inner_eval_points[ib:ie]\n\n # Shared outs ...\n b = e\n e = e + self.n_shared_outs\n ib = ie\n ie = ie + self.n_shared_outs\n scan_shared = inputs[b:e]\n inner_shared = self_inputs[ib:ie]\n\n # NIT_SOT sequences\n b = e\n e = e + self.n_nit_sot\n scan_nit_sot = inputs[b:e] * 2\n\n # All other arguments\n clean_eval_points = []\n for inp, evp in zip(inputs[e:], eval_points[e:]):\n if evp is not None:\n clean_eval_points.append(evp)\n else:\n clean_eval_points.append(inp.zeros_like())\n scan_other = inputs[e:] + clean_eval_points\n # inner_eval_points do not have entries for shared variables\n inner_other = self_inputs[ie:] + inner_eval_points[ib:]\n\n # Outputs\n n_mit_mot_outs = int(numpy.sum([len(x) for x in\n self.mit_mot_out_slices]))\n info['n_mit_mot_outs'] = n_mit_mot_outs * 2\n b = 0\n e = n_mit_mot_outs\n inner_out_mit_mot = self_outputs[b:e] + rop_outs[b:e]\n b = e\n e = e + self.n_mit_sot\n inner_out_mit_sot = self_outputs[b:e] + rop_outs[b:e]\n b = e\n e = e + self.n_sit_sot\n inner_out_sit_sot = self_outputs[b:e] + rop_outs[b:e]\n b = e\n e = e + self.n_nit_sot\n inner_out_nit_sot = self_outputs[b:e] + rop_outs[b:e]\n b = e\n e = e + self.n_shared_outs\n inner_out_shared = self_outputs[b:e]\n\n inner_ins = (inner_seqs +\n inner_mit_mot +\n inner_mit_sot +\n inner_sit_sot +\n inner_shared +\n inner_other)\n inner_outs = (inner_out_mit_mot +\n inner_out_mit_sot +\n inner_out_sit_sot +\n inner_out_nit_sot +\n inner_out_shared)\n\n if self.as_while:\n inner_outs += [self_outputs[-1]]\n scan_inputs = ([inputs[0]] +\n scan_seqs +\n scan_mit_mot +\n scan_mit_sot +\n scan_sit_sot +\n scan_shared +\n scan_nit_sot +\n scan_other)\n\n local_op = Scan(inner_ins, inner_outs, info)\n outputs = local_op(*scan_inputs)\n if type(outputs) not in (list, tuple):\n outputs = [outputs]\n # Select only the result of the R_op results\n final_outs = []\n b = self.n_mit_mot\n e = self.n_mit_mot * 2\n final_outs += outputs[b:e]\n b = e + self.n_mit_sot\n e = e + self.n_mit_sot * 2\n final_outs += outputs[b:e]\n b = e + self.n_sit_sot\n e = e + self.n_sit_sot * 2\n final_outs += outputs[b:e]\n b = e + self.n_nit_sot\n e = e + self.n_nit_sot * 2\n final_outs += outputs[b:e]\n final_outs += [None] * self.n_shared_outs\n\n return final_outs\n\n\n# Since Scan is an op that contains a Theano compiled function, it is\n# useful to let DebugMode know about it.\ngof.ops_with_inner_function[Scan] = 'fn'\n\n\[email protected]_profiler_printer\ndef profile_printer(fct_name, compile_time, fct_call_time, fct_call,\n apply_time, apply_cimpl, message, outputs_size,\n other_time):\n # Scan overhead profile\n if any([isinstance(node.op, Scan) and v > 0 for (_, node), v in\n apply_time.items()]):\n print()\n print('Scan overhead:')\n print ('<Scan op time(s)> <sub scan fct time(s)> <sub scan op '\n 'time(s)> <sub scan fct time(% scan op time)> <sub scan '\n 'op time(% scan op time)> <node>')\n total_super_scan_time = 0\n total_scan_fct_time = 0\n total_scan_op_time = 0\n for (_, node), v in iteritems(apply_time):\n if isinstance(node.op, Scan):\n if v > 0:\n scan_fct_time = node.op.mode_instance.fn_time\n scan_op_time = node.op.mode_instance.local_time\n total_super_scan_time += v\n total_scan_fct_time += scan_fct_time\n total_scan_op_time += scan_op_time\n print(' %5.1fs %5.1fs %5.1fs %5.1f%% %5.1f%%' % (\n v,\n scan_fct_time,\n scan_op_time,\n scan_fct_time / v * 100,\n scan_op_time / v * 100), node)\n else:\n print((' The node took 0s, so we can not '\n 'compute the overhead'), node)\n print(' total %5.1fs %5.1fs %5.1fs %5.1f%% %5.1f%%' % (\n total_super_scan_time,\n total_scan_fct_time,\n total_scan_op_time,\n total_scan_fct_time / total_super_scan_time * 100,\n total_scan_op_time / total_super_scan_time * 100))\n",
"\"\"\"\nThis module provides the Scan Op\n\nScanning is a general form of recurrence, which can be used for looping.\nThe idea is that you *scan* a function along some input sequence, producing\nan output at each time-step that can be seen (but not modified) by the\nfunction at the next time-step. (Technically, the function can see the\nprevious K time-steps of your outputs and L time steps (from past and\nfuture) of your inputs.\n\nSo for example, ``sum()`` could be computed by scanning the ``z+x_i``\nfunction over a list, given an initial state of ``z=0``.\n\nSpecial cases:\n\n* A *reduce* operation can be performed by using only the last\n output of a ``scan``.\n* A *map* operation can be performed by applying a function that\n ignores previous steps of the outputs.\n\nOften a for-loop or while-loop can be expressed as a ``scan()`` operation,\nand ``scan`` is the closest that theano comes to looping. The advantages\nof using ``scan`` over `for` loops in python (amongs other) are:\n\n* it allows the number of iterations to be part of the symbolic graph\n* it allows computing gradients through the for loop\n* there exist a bunch of optimizations that help re-write your loop\nsuch that less memory is used and that it runs faster\n* it ensures that data is not copied from host to gpu and gpu to\nhost at each step\n\nThe Scan Op should typically be used by calling any of the following\nfunctions: ``scan()``, ``map()``, ``reduce()``, ``foldl()``,\n``foldr()``.\n\"\"\"\n__docformat__ = 'restructedtext en'\n__authors__ = (\"Razvan Pascanu \"\n \"Frederic Bastien \"\n \"James Bergstra \"\n \"Pascal Lamblin \")\n__copyright__ = \"(c) 2010, Universite de Montreal\"\n__contact__ = \"Razvan Pascanu <r.pascanu@gmail>\"\n\n\nimport logging\nimport numpy\nfrom six.moves import xrange\n\nfrom theano import gof\nfrom theano.compat import izip\nfrom theano.tensor import opt, TensorVariable\nfrom theano.tensor.sharedvar import TensorSharedVariable\nfrom theano import tensor\nfrom theano.scalar.sharedvar import shared as scalar_shared\nfrom theano.compile.pfunc import rebuild_collect_shared\n\nfrom . import scan_op\nfrom . import scan_utils\n\n# Logging function for sending warning or info\n_logger = logging.getLogger('theano.scan_module.scan')\n\n\ndef scan(fn,\n sequences=None,\n outputs_info=None,\n non_sequences=None,\n n_steps=None,\n truncate_gradient=-1,\n go_backwards=False,\n mode=None,\n name=None,\n options=None,\n profile=False):\n \"\"\"\n This function constructs and applies a Scan op to the provided\n arguments.\n\n :param fn:\n ``fn`` is a function that describes the operations involved in one\n step of ``scan``. ``fn`` should construct variables describing the\n output of one iteration step. It should expect as input theano\n variables representing all the slices of the input sequences\n and previous values of the outputs, as well as all other arguments\n given to scan as ``non_sequences``. The order in which scan passes\n these variables to ``fn`` is the following :\n\n * all time slices of the first sequence\n * all time slices of the second sequence\n * ...\n * all time slices of the last sequence\n * all past slices of the first output\n * all past slices of the second otuput\n * ...\n * all past slices of the last output\n * all other arguments (the list given as `non_sequences` to\n scan)\n\n The order of the sequences is the same as the one in the list\n `sequences` given to scan. The order of the outputs is the same\n as the order of ``outputs_info``. For any sequence or output the\n order of the time slices is the same as the one in which they have\n been given as taps. For example if one writes the following :\n\n .. code-block:: python\n\n scan(fn, sequences = [ dict(input= Sequence1, taps = [-3,2,-1])\n , Sequence2\n , dict(input = Sequence3, taps = 3) ]\n , outputs_info = [ dict(initial = Output1, taps = [-3,-5])\n , dict(initial = Output2, taps = None)\n , Output3 ]\n , non_sequences = [ Argument1, Argument 2])\n\n ``fn`` should expect the following arguments in this given order:\n\n #. ``Sequence1[t-3]``\n #. ``Sequence1[t+2]``\n #. ``Sequence1[t-1]``\n #. ``Sequence2[t]``\n #. ``Sequence3[t+3]``\n #. ``Output1[t-3]``\n #. ``Output1[t-5]``\n #. ``Output3[t-1]``\n #. ``Argument1``\n #. ``Argument2``\n\n The list of ``non_sequences`` can also contain shared variables\n used in the function, though ``scan`` is able to figure those\n out on its own so they can be skipped. For the clarity of the\n code we recommend though to provide them to scan. To some extend\n ``scan`` can also figure out other ``non sequences`` (not shared)\n even if not passed to scan (but used by `fn`). A simple example of\n this would be :\n\n .. code-block:: python\n\n import theano.tensor as TT\n W = TT.matrix()\n W_2 = W**2\n def f(x):\n return TT.dot(x,W_2)\n\n The function is expected to return two things. One is a list of\n outputs ordered in the same order as ``outputs_info``, with the\n difference that there should be only one output variable per\n output initial state (even if no tap value is used). Secondly\n `fn` should return an update dictionary (that tells how to\n update any shared variable after each iteration step). The\n dictionary can optionally be given as a list of tuples. There is\n no constraint on the order of these two list, ``fn`` can return\n either ``(outputs_list, update_dictionary)`` or\n ``(update_dictionary, outputs_list)`` or just one of the two (in\n case the other is empty).\n\n To use ``scan`` as a while loop, the user needs to change the\n function ``fn`` such that also a stopping condition is returned.\n To do so, he/she needs to wrap the condition in an ``until`` class.\n The condition should be returned as a third element, for example:\n\n .. code-block:: python\n\n ...\n return [y1_t, y2_t], {x:x+1}, theano.scan_module.until(x < 50)\n\n Note that a number of steps (considered in here as the maximum\n number of steps ) is still required even though a condition is\n passed (and it is used to allocate memory if needed). = {}):\n\n :param sequences:\n ``sequences`` is the list of Theano variables or dictionaries\n describing the sequences ``scan`` has to iterate over. If a\n sequence is given as wrapped in a dictionary, then a set of optional\n information can be provided about the sequence. The dictionary\n should have the following keys:\n\n * ``input`` (*mandatory*) -- Theano variable representing the\n sequence.\n\n * ``taps`` -- Temporal taps of the sequence required by ``fn``.\n They are provided as a list of integers, where a value ``k``\n impiles that at iteration step ``t`` scan will pass to ``fn``\n the slice ``t+k``. Default value is ``[0]``\n\n Any Theano variable in the list ``sequences`` is automatically\n wrapped into a dictionary where ``taps`` is set to ``[0]``\n\n\n :param outputs_info:\n ``outputs_info`` is the list of Theano variables or dictionaries\n describing the initial state of the outputs computed\n recurrently. When this initial states are given as dictionary\n optional information can be provided about the output corresponding\n to these initial states. The dictionary should have the following\n keys:\n\n * ``initial`` -- Theano variable that represents the initial\n state of a given output. In case the output is not computed\n recursively (think of a map) and does not require a initial\n state this field can be skiped. Given that only the previous\n time step of the output is used by ``fn`` the initial state\n should have the same shape as the output. If multiple time\n taps are used, the initial state should have one extra\n dimension that should cover all the possible taps. For example\n if we use ``-5``, ``-2`` and ``-1`` as past taps, at step 0,\n ``fn`` will require (by an abuse of notation) ``output[-5]``,\n ``output[-2]`` and ``output[-1]``. This will be given by\n the initial state, which in this case should have the shape\n (5,)+output.shape. If this variable containing the initial\n state is called ``init_y`` then ``init_y[0]`` *corresponds to*\n ``output[-5]``. ``init_y[1]`` *correponds to* ``output[-4]``,\n ``init_y[2]`` corresponds to ``output[-3]``, ``init_y[3]``\n coresponds to ``output[-2]``, ``init_y[4]`` corresponds to\n ``output[-1]``. While this order might seem strange, it comes\n natural from splitting an array at a given point. Assume that\n we have a array ``x``, and we choose ``k`` to be time step\n ``0``. Then our initial state would be ``x[:k]``, while the\n output will be ``x[k:]``. Looking at this split, elements in\n ``x[:k]`` are ordered exactly like those in ``init_y``.\n * ``taps`` -- Temporal taps of the output that will be pass to\n ``fn``. They are provided as a list of *negative* integers,\n where a value ``k`` implies that at iteration step ``t`` scan\n will pass to ``fn`` the slice ``t+k``.\n\n ``scan`` will follow this logic if partial information is given:\n\n * If an output is not wrapped in a dictionary, ``scan`` will wrap\n it in one assuming that you use only the last step of the output\n (i.e. it makes your tap value list equal to [-1]).\n * If you wrap an output in a dictionary and you do not provide any\n taps but you provide an initial state it will assume that you are\n using only a tap value of -1.\n * If you wrap an output in a dictionary but you do not provide any\n initial state, it assumes that you are not using any form of\n taps.\n * If you provide a ``None`` instead of a variable or a empty\n dictionary ``scan`` assumes that you will not use any taps for\n this output (like for example in case of a map)\n\n If ``outputs_info`` is an empty list or None, ``scan`` assumes\n that no tap is used for any of the outputs. If information is\n provided just for a subset of the outputs an exception is\n raised (because there is no convention on how scan should map\n the provided information to the outputs of ``fn``)\n\n\n :param non_sequences:\n ``non_sequences`` is the list of arguments that are passed to\n ``fn`` at each steps. One can opt to exclude variable\n used in ``fn`` from this list as long as they are part of the\n computational graph, though for clarity we encourage not to do so.\n\n\n :param n_steps:\n ``n_steps`` is the number of steps to iterate given as an int\n or Theano scalar. If any of the input sequences do not have\n enough elements, scan will raise an error. If the *value is 0* the\n outputs will have *0 rows*. If the value is negative, ``scan``\n will run backwards in time. If the ``go_backwards`` flag is already\n set and also ``n_steps`` is negative, ``scan`` will run forward\n in time. If n stpes is not provided, ``scan`` will figure\n out the amount of steps it should run given its input sequences.\n\n\n :param truncate_gradient:\n ``truncate_gradient`` is the number of steps to use in truncated\n BPTT. If you compute gradients through a scan op, they are\n computed using backpropagation through time. By providing a\n different value then -1, you choose to use truncated BPTT instead\n of classical BPTT, where you go for only ``truncate_gradient``\n number of steps back in time.\n\n\n :param go_backwards:\n ``go_backwards`` is a flag indicating if ``scan`` should go\n backwards through the sequences. If you think of each sequence\n as indexed by time, making this flag True would mean that\n ``scan`` goes back in time, namely that for any sequence it\n starts from the end and goes towards 0.\n\n\n :param name:\n When profiling ``scan``, it is crucial to provide a name for any\n instance of ``scan``. The profiler will produce an overall\n profile of your code as well as profiles for the computation of\n one step of each instance of ``scan``. The ``name`` of the instance\n appears in those profiles and can greatly help to disambiguate\n information.\n\n :param mode:\n It is recommended to leave this argument to None, especially\n when profiling ``scan`` (otherwise the results are not going to\n be accurate). If you prefer the computations of one step of\n ``scan`` to be done differently then the entire function, you\n can use this parameter to describe how the computations in this\n loop are done (see ``theano.function`` for details about\n possible values and their meaning).\n\n :param profile:\n Flag or string. If true, or different from the empty string, a\n profile object will be created and attached to the inner graph of\n scan. In case ``profile`` is True, the profile object will have the\n name of the scan instance, otherwise it will have the passed string.\n Profile object collect (and print) information only when running the\n inner graph with the new cvm linker ( with default modes,\n other linkers this argument is useless)\n\n :rtype: tuple\n :return: tuple of the form (outputs, updates); ``outputs`` is either a\n Theano variable or a list of Theano variables representing the\n outputs of ``scan`` (in the same order as in\n ``outputs_info``). ``updates`` is a subclass of dictionary\n specifying the\n update rules for all shared variables used in scan\n This dictionary should be passed to ``theano.function`` when\n you compile your function. The change compared to a normal\n dictionary is that we validate that keys are SharedVariable\n and addition of those dictionary are validated to be consistent.\n \"\"\"\n # Note : see the internal documentation of the scan op for naming\n # conventions and all other details\n if options is None:\n options = {}\n rvals = scan_utils.canonical_arguments(sequences,\n outputs_info,\n non_sequences,\n go_backwards,\n n_steps)\n inputs, states_and_outputs_info, parameters, T = rvals\n # If we provided a known number of steps ( before compilation)\n # and if that number is 1 or -1, then we can skip the Scan Op,\n # and just apply the inner function once\n # To do that we check here to see the nature of n_steps\n T_value = None\n if isinstance(n_steps, (float, int)):\n T_value = int(n_steps)\n else:\n try:\n T_value = opt.get_scalar_constant_value(n_steps)\n except (TypeError, AttributeError):\n T_value = None\n\n if T_value in (1, -1):\n return one_step_scan(fn,\n inputs,\n states_and_outputs_info,\n parameters,\n truncate_gradient)\n\n # 1. Variable representing the current time step\n t = scalar_shared(numpy.int64(0), name='t')\n\n # 2. Allocate memory for the states of scan.\n mintaps = []\n lengths = []\n for pos, arg_info in enumerate(states_and_outputs_info):\n if arg_info.get('taps', None) == [-1]:\n mintaps.append(1)\n lengths.append(scalar_shared(numpy.int64(0),\n name='l%d' % pos))\n arg_info['initial'] = scan_utils.expand(tensor.unbroadcast(\n tensor.shape_padleft(arg_info['initial']), 0), T)\n elif arg_info.get('taps', None):\n if numpy.any(numpy.array(arg_info.get('taps', [])) > 0):\n # Make sure we do not have requests for future values of a\n # sequence we can not provide such values\n raise ValueError('Can not use future taps of outputs',\n arg_info)\n mintap = abs(numpy.min(arg_info['taps']))\n lengths.append(scalar_shared(numpy.int64(0),\n name='l%d' % pos))\n mintaps.append(mintap)\n arg_info['initial'] = scan_utils.expand(\n arg_info['initial'][:mintap], T)\n else:\n mintaps.append(0)\n lengths.append(scalar_shared(numpy.int64(0),\n name='l%d' % pos))\n\n # 3. Generate arguments for the function passed to scan. This will\n # function will return the outputs that need to be computed at every\n # timesteps\n inputs_slices = [input[t] for input in inputs]\n states_slices = []\n for n, state in enumerate(states_and_outputs_info):\n # Check if it is actually a state and not an output\n if mintaps[n] != 0:\n for k in state['taps']:\n states_slices.append(\n state['initial'][(t + mintaps[n] + k) % lengths[n]])\n\n # 4. Construct outputs that are to be computed by the inner\n # function of scan\n args = inputs_slices + states_slices + parameters\n cond, states_and_outputs, updates = \\\n scan_utils.get_updates_and_outputs(fn(*args))\n\n # User is allowed to provide no information if it only behaves like a\n # map\n if (len(states_and_outputs) != len(states_and_outputs_info) and\n len(states_and_outputs_info) == 0):\n mintaps = [0] * len(states_and_outputs)\n\n # 5. Construct the scan op\n # 5.1 Construct list of shared variables with updates (those that\n # can be treated as states (i.e. of TensorType) and those that can not\n # (like Random States)\n\n if cond is not None:\n _cond = [cond]\n else:\n _cond = []\n rvals = rebuild_collect_shared(\n states_and_outputs + _cond,\n updates=updates,\n rebuild_strict=True,\n copy_inputs_over=True,\n no_default_updates=False)\n\n # extracting the arguments\n input_variables, cloned_outputs, other_rval = rvals\n clone_d, update_d, update_expr, shared_inputs = other_rval\n additional_input_states = []\n additional_output_states = []\n additional_lengths = []\n additional_mintaps = []\n original_numeric_shared_variables = []\n\n non_numeric_input_states = []\n non_numeric_output_states = []\n original_non_numeric_shared_variables = []\n pos = len(lengths)\n for sv in shared_inputs:\n if sv in update_d:\n if isinstance(sv, (TensorVariable, TensorSharedVariable)):\n # We can treat it as a sit sot\n nw_state = scan_utils.expand(\n tensor.unbroadcast(tensor.shape_padleft(sv), 0), T)\n additional_lengths.append(scalar_shared(numpy.int64(0),\n name='l%d' % pos))\n pos = pos + 1\n additional_mintaps.append(1)\n additional_input_states.append(nw_state)\n additional_output_states.append(\n scan_utils.clone(tensor.set_subtensor(\n nw_state[(t + 1) % additional_lengths[-1]],\n update_d[sv])))\n original_numeric_shared_variables.append(sv)\n else:\n non_numeric_input_states.append(sv)\n non_numeric_output_states.append(update_d[sv])\n original_non_numeric_shared_variables.append(sv)\n\n # Replace shared variables in the update\n _additional_output_states = []\n replace = {}\n for sv, buf in zip(original_numeric_shared_variables,\n additional_input_states):\n replace[sv] = buf[t]\n for out in additional_output_states:\n _additional_output_states.append(\n scan_utils.clone(out, replace=replace))\n additional_output_states = _additional_output_states\n\n # 5.2 Collect inputs/outputs of the inner function\n inputs = []\n outputs = []\n for n, mintap in enumerate(mintaps):\n if mintap != 0:\n input_state = states_and_outputs_info[n]['initial']\n inputs.append(input_state)\n outputs.append(\n tensor.set_subtensor(\n input_state[(t + mintap) % lengths[n]],\n states_and_outputs[n]))\n else:\n mem_buffer = scan_utils.allocate_memory(\n T, states_and_outputs_info[n], states_and_outputs[n])\n inputs.append(output)\n outputs.append(\n tensor.set_subtensor(output[t % lengths[n]],\n states_and_outputs[n]))\n inputs.extend(additional_input_states)\n outputs.extend(additional_output_states)\n lengths.extend(additional_lengths)\n mintaps.extend(additional_mintaps)\n inputs.extend(non_numeric_input_states)\n outputs.extend(non_numeric_output_states)\n all_other_inputs = gof.graph.inputs(outputs)\n parameters = [x for x in all_other_inputs\n if (x not in inputs and x not in lengths and x is not t\n and isinstance(x, gof.Variable) and\n not isinstance(x, gof.Constant))]\n inputs.extend(parameters)\n # 5.3 Construct the the options dictionary\n options['name'] = name\n options['profile'] = profile\n options['mode'] = mode\n options['inplace'] = False\n options['gpu'] = False\n options['truncate_gradient'] = truncate_gradient\n options['hash_inner_graph'] = 0\n # 5.4 Construct the ScanOp instance\n local_op = scan_op.ScanOp(inputs=inputs,\n outputs=outputs,\n lengths=lengths,\n switches=[],\n mintaps=mintaps,\n index=t,\n options=options,\n as_repeatUntil=cond)\n # Note that we get here all the outputs followed by the update rules to\n # the shared variables we had in our scan\n # we know that we have (in this given order):\n # * len(states_and_outputs) real outputs\n # * len(additional_input_states) updates for numeric shared variable\n # * len(non_numeric_input_states) updates for non numeric shared\n # variables\n scan_inputs = [T] + inputs\n scan_outputs_update_rules = scan_utils.to_list(local_op(*scan_inputs))\n # 5.5 Collect outputs and add permutation object\n scan_outputs = []\n for pos in xrange(len(states_and_outputs)):\n out = scan_utils.ScanPermutation(mintaps[pos])(\n scan_outputs_update_rules[pos], t)\n scan_outputs.append(out[mintaps[pos]:])\n # 5.6 Construct updates dictionary\n update_rules = scan_outputs_update_rules[len(states_and_outputs):]\n updates = {}\n for v, u in izip(original_numeric_shared_variables,\n update_rules[:len(additional_input_states)]):\n updates[v] = u[-1]\n for v, u in izip(original_non_numeric_shared_variables,\n update_rules[len(additional_input_states):]):\n updates[v] = u\n # Step 5.7 We are done and can return everything back to the user\n return scan_outputs, updates\n\n\ndef one_step_scan(fn,\n inputs,\n states_and_outputs_info,\n parameters,\n truncate_gradient):\n \"\"\"\n This function is evaluated if `n_steps` evaluates to either 1 or -1.\n \"\"\"\n # 1. Grab slices of sequences\n inputs_slices = [input[0] for input in inputs]\n\n # 2. Grab slices of states\n states_slices = []\n for n, arg_info in enumerate(states_and_outputs_info):\n if arg_info.get('taps', None) == [-1]:\n states_slices.append(arg_info['initial'])\n elif arg_info.get('taps', None):\n if numpy.any(numpy.array(arg_info.get('taps', [])) > 0):\n # Make sure we do not have requests for future values of a\n # sequence we can not provide such values\n raise ValueError('Can not use future taps of outputs',\n arg_info)\n # go through the taps\n mintap = abs(numpy.min(arg_info['taps']))\n states_slices.extend(\n [arg_info['initial'][k + mintap] for k in arg_info['taps']])\n\n # Re-order args\n args = (inputs_slices + states_slices + parameters)\n cond, states_and_outputs, updates = \\\n scan_utils.get_updates_and_outputs(fn(*args))\n\n # We do not need to use the scan op anymore, so we can just return\n # the outputs and updates we have\n if cond is not None:\n _logger.warning(('When the number of steps is fixed and equal '\n 'to 1, the provided stopping condition, ',\n str(cond), ' is ignored'))\n states_and_outputs = [tensor.unbroadcast(\n tensor.shape_padleft(arg), 0) for arg in states_and_outputs]\n if len(states_and_outputs) == 1:\n states_and_outputs = states_and_outputs[0]\n\n return (states_and_outputs, updates)\n",
"\"\"\"WARNING: This code is not recommanded. It is not finished, it is\nslower then the version in sandbox/neighbours.py, and it do not work\non the GPU.\n\nWe only keep this version here as it is a little bit more generic, so\nit cover more cases. But thoses cases aren't needed frequently, so you\nprobably don't want to use this version, go see neighbours.py!!!!!!!\n\n\"\"\"\nimport numpy\nfrom six.moves import xrange\nimport six.moves.builtins as builtins\n\nimport theano\nfrom theano import gof, Op\n\n\nclass NeighbourhoodsFromImages(Op):\n\n __props__ = (\"n_dims_before\", \"dims_neighbourhoods\", \"strides\",\n \"ignore_border\", \"inverse\")\n\n def __init__(self, n_dims_before, dims_neighbourhoods,\n strides=None, ignore_border=False, inverse=False):\n \"\"\"\n This extracts neighbourhoods from \"images\", but in a\n dimension-generic manner.\n\n In the 2D case, this is similar to downsampling, but instead of reducing\n a group of 2x2 pixels (for example) to a single new pixel in the output,\n you place those 4 pixels in a row.\n\n For example, say you have this 2x4 image::\n\n [ [ 0.5, 0.6, 0.7, 0.8 ],\n [ 0.1, 0.2, 0.3, 0.4 ] ]\n\n and you want to extract 2x2 neighbourhoods. This op would then produce::\n\n [ [ [ 0.5, 0.6, 0.1, 0.2 ] ], # the first 2x2 group of pixels\n [ [ 0.7, 0.8, 0.3, 0.4 ] ] ] # the second one\n\n so think of a 2D downsampling where each pixel of the resulting array\n is replaced by an array containing the (flattened) pixels of the\n corresponding neighbourhood.\n\n If you provide a stack of 2D image, or multiple stacks, each image\n will be treated independently, and the first dimensions of the array\n will be preserved as such.\n\n This also makes sense in the 1D or 3D case. Below I'll still be calling\n those \"images\", by analogy.\n\n In the 1D case, you're\n extracting subsequences from the original sequence. In the 3D case,\n you're extracting cuboids. If you ever find a 4D use, tell me! It\n should be possible, anyhow.\n\n Parameters\n ----------\n n_dims_before : int\n Number of dimensions preceding the \"images\".\n dims_neighbourhoods : tuple of ints\n Exact shape of windows to be extracted (e.g. (2,2) in the case above).\n n_dims_before + len(dims_neighbourhoods) should be equal to the\n number of dimensions in the input given to the op.\n strides : tuple of int\n Number of elements to skip when moving to the next neighbourhood,\n for each dimension of dims_neighbourhoods. There can be overlap\n between neighbourhoods, or gaps.\n ignore_border : bool\n If the dimensions of the neighbourhoods don't exactly divide the\n dimensions of the \"images\", you can either fill the last\n neighbourhood with zeros (False) or drop it entirely (True).\n inverse : bool\n You shouldn't have to use this. Only used by child class\n ImagesFromNeighbourhoods which simply reverses the assignment.\n \"\"\"\n self.n_dims_before = n_dims_before\n self.dims_neighbourhoods = dims_neighbourhoods\n if strides is not None:\n self.strides = strides\n else:\n self.strides = dims_neighbourhoods\n self.ignore_border = ignore_border\n\n self.inverse = inverse\n\n self.code_string, self.code = self.make_py_code()\n\n def __str__(self):\n return '%s{%s,%s,%s,%s}' % (self.__class__.__name__,\n self.n_dims_before,\n self.dims_neighbourhoods,\n self.strides,\n self.ignore_border)\n\n def out_shape(self, input_shape):\n dims = list(input_shape[:self.n_dims_before])\n num_strides = [0 for i in xrange(len(self.strides))]\n neigh_flattened_dim = 1\n for i, ds in enumerate(self.dims_neighbourhoods):\n cur_stride = self.strides[i]\n input_dim = input_shape[i + self.n_dims_before]\n target_dim = input_dim // cur_stride\n if not self.ignore_border and (input_dim % cur_stride) != 0:\n target_dim += 1\n num_strides[i] = target_dim\n dims.append(target_dim)\n neigh_flattened_dim *= ds\n\n dims.append(neigh_flattened_dim)\n\n return dims, num_strides\n\n # for inverse mode\n # \"output\" here actually referes to the Op's input shape (but it's inverse mode)\n def in_shape(self, output_shape):\n out_dims = list(output_shape[:self.n_dims_before])\n num_strides = []\n\n # in the inverse case we don't worry about borders:\n # they either have been filled with zeros, or have been cropped\n for i, ds in enumerate(self.dims_neighbourhoods):\n # the number of strides performed by NeighFromImg is\n # directly given by this shape\n num_strides.append(output_shape[self.n_dims_before + i])\n\n # our Op's output image must be at least this wide\n at_least_width = num_strides[i] * self.strides[i]\n\n # ... which gives us this number of neighbourhoods\n num_neigh = at_least_width // ds\n if at_least_width % ds != 0:\n num_neigh += 1\n\n # making the final Op's output dimension this wide\n out_dims.append(num_neigh * ds)\n\n return out_dims, num_strides\n\n def make_node(self, x):\n x = theano.tensor.as_tensor_variable(x)\n if self.inverse:\n # +1 in the inverse case\n if x.type.ndim != (self.n_dims_before +\n len(self.dims_neighbourhoods) + 1):\n raise TypeError()\n else:\n if x.type.ndim != (self.n_dims_before +\n len(self.dims_neighbourhoods)):\n raise TypeError()\n return gof.Apply(self, [x], [x.type()])\n\n def perform(self, node, inp, out):\n x, = inp\n z, = out\n if self.inverse:\n # +1 in the inverse case\n if len(x.shape) != (self.n_dims_before +\n len(self.dims_neighbourhoods) + 1):\n raise ValueError(\"Images passed as input don't match the \"\n \"dimensions passed when this (inversed) \"\n \"Apply node was created\")\n prod = 1\n for dim in self.dims_neighbourhoods:\n prod *= dim\n if x.shape[-1] != prod:\n raise ValueError(\"Last dimension of neighbourhoods (%s) is not\"\n \" the product of the neighbourhoods dimensions\"\n \" (%s)\" % (str(x.shape[-1]), str(prod)))\n else:\n if len(x.shape) != (self.n_dims_before +\n len(self.dims_neighbourhoods)):\n raise ValueError(\"Images passed as input don't match the \"\n \"dimensions passed when this Apply node \"\n \"was created\")\n\n if self.inverse:\n input_shape, num_strides = self.in_shape(x.shape)\n out_shape, dummy = self.out_shape(input_shape)\n else:\n input_shape = x.shape\n out_shape, num_strides = self.out_shape(input_shape)\n\n if z[0] is None:\n if self.inverse:\n z[0] = numpy.zeros(input_shape)\n else:\n z[0] = numpy.zeros(out_shape)\n z[0] = theano._asarray(z[0], dtype=x.dtype)\n\n exec(self.code)\n\n def make_py_code(self):\n code = self._py_outerloops()\n for i in xrange(len(self.strides)):\n code += self._py_innerloop(i)\n code += self._py_assignment()\n return code, builtins.compile(code, '<string>', 'exec')\n\n def _py_outerloops(self):\n code_before = \"\"\n for dim_idx in xrange(self.n_dims_before):\n code_before += ('\\t' * (dim_idx)) + \\\n \"for outer_idx_%d in xrange(input_shape[%d]):\\n\" % \\\n (dim_idx, dim_idx)\n return code_before\n\n def _py_innerloop(self, inner_dim_no):\n base_indent = ('\\t' * (self.n_dims_before + inner_dim_no * 2))\n code_before = base_indent + \\\n \"for stride_idx_%d in xrange(num_strides[%d]):\\n\" % \\\n (inner_dim_no, inner_dim_no)\n base_indent += '\\t'\n code_before += base_indent + \\\n \"dim_%d_offset = stride_idx_%d * self.strides[%d]\\n\" %\\\n (inner_dim_no, inner_dim_no, inner_dim_no)\n code_before += base_indent + \\\n \"max_neigh_idx_%d = input_shape[%d] - dim_%d_offset\\n\" % \\\n (inner_dim_no, self.n_dims_before + inner_dim_no, inner_dim_no)\n code_before += base_indent + \\\n (\"for neigh_idx_%d in xrange(min(max_neigh_idx_%d,\"\n \" self.dims_neighbourhoods[%d])):\\n\") %\\\n (inner_dim_no, inner_dim_no, inner_dim_no)\n\n return code_before\n\n def _py_flattened_idx(self):\n return \"+\".join([\"neigh_strides[%d]*neigh_idx_%d\" % (i, i)\n for i in xrange(len(self.strides))])\n\n def _py_assignment(self):\n input_idx = \"\".join([\"outer_idx_%d,\" % (i,)\n for i in xrange(self.n_dims_before)])\n input_idx += \"\".join([\"dim_%d_offset+neigh_idx_%d,\" %\n (i, i) for i in xrange(len(self.strides))])\n out_idx = \"\".join(\n [\"outer_idx_%d,\" % (i,) for i in xrange(self.n_dims_before)] +\n [\"stride_idx_%d,\" % (i,) for i in xrange(len(self.strides))])\n out_idx += self._py_flattened_idx()\n\n # return_val = '\\t' * (self.n_dims_before + len(self.strides)*2)\n # return_val += \"print \"+input_idx+\"'\\\\n',\"+out_idx+\"\\n\"\n\n return_val = '\\t' * (self.n_dims_before + len(self.strides) * 2)\n\n if self.inverse:\n # remember z and x are inversed:\n # z is the Op's output, but has input_shape\n # x is the Op's input, but has out_shape\n return_val += \"z[0][%s] = x[%s]\\n\" % (input_idx, out_idx)\n else:\n return_val += \"z[0][%s] = x[%s]\\n\" % (out_idx, input_idx)\n\n return return_val\n\n\nclass ImagesFromNeighbourhoods(NeighbourhoodsFromImages):\n def __init__(self, n_dims_before, dims_neighbourhoods,\n strides=None, ignore_border=False):\n NeighbourhoodsFromImages.__init__(self, n_dims_before,\n dims_neighbourhoods,\n strides=strides,\n ignore_border=ignore_border,\n inverse=True)\n # and that's all there is to it\n",
"\"\"\"This file contains auxiliary Ops, used during the compilation phase\nand Ops building class (:class:`FromFunctionOp`) and decorator\n(:func:`as_op`) that help make new Ops more rapidly.\n\n\"\"\"\nimport copy\nimport six.moves.cPickle as pickle\nimport warnings\n\nimport theano\nfrom theano import gof\nfrom six import iteritems\nfrom six.moves import xrange\n\n\nimport numpy\n\n\ndef register_view_op_c_code(type, code, version=()):\n \"\"\" Tell ViewOp how to generate C code for a Theano Type\n\n :param type: A Theano type. It must be the Theano class itself and not an\n instance of the class.\n :param code: C code that returns a view for the Theano type 'type'.\n Use %(iname)s and %(oname)s for the input and output C\n variable names respectively.\n :param version: A number indicating the version of the code, for cache.\n \"\"\"\n ViewOp.c_code_and_version[type] = (code, version)\n\n\nclass ViewOp(gof.Op):\n \"\"\"\n Returns an inplace view of the input. Used internally by Theano.\n \"\"\"\n view_map = {0: [0]}\n # Mapping from Type to C code (and version) to use.\n # In the C code, the name of the input variable is %(iname)s,\n # the output variable is %(oname)s.\n c_code_and_version = {}\n\n def make_node(self, x):\n return gof.Apply(self, [x], [x.type()])\n\n def __eq__(self, other):\n return type(self) == type(other)\n\n def __hash__(self):\n return hash(type(self))\n\n def perform(self, node, inp, out):\n x, = inp\n z, = out\n z[0] = x\n\n def __str__(self):\n return '%s' % self.__class__.__name__\n\n def c_code(self, node, nodename, inp, out, sub):\n iname, = inp\n oname, = out\n fail = sub['fail']\n\n itype = node.inputs[0].type.__class__\n if itype in self.c_code_and_version:\n code, version = self.c_code_and_version[itype]\n return code % locals()\n\n # Else, no C code\n return super(ViewOp, self).c_code(node, nodename, inp, out, sub)\n\n def c_code_cache_version(self):\n version = []\n # If any of the c code is unversionned, we have to return ()\n # Else, we will return a list of (type name, version) pairs.\n for t, (c, v) in sorted(iteritems(self.c_code_and_version),\n key=lambda pair: str(pair[0])):\n if not v:\n warnings.warn(\"Type %s has C code for ViewOp, but it has no \"\n \"version. You should add a 'version' keyword \"\n \"arg when calling register_view_op_c_code.\" % t,\n stacklevel=2)\n return ()\n version.append((str(t), v))\n\n return tuple(version)\n\n def infer_shape(self, node, input_shapes):\n return input_shapes\n\n def grad(self, args, g_outs):\n return g_outs\n\nview_op = ViewOp()\n\n\nclass OutputGuard(ViewOp):\n \"\"\"\n This op is used only internally by Theano.\n\n Only the AddDestroyHandler optimizer tries to insert them in the graph.\n\n This Op is declared as destructive while it is not destroying\n anything. It returns a view. This is used to prevent destruction of\n the output variables of a Theano function.\n\n There is a mechanism in Theano that should prevent this, but the use\n of OutputGuard adds a safeguard: it may be possible for some optimization\n run before the add_destroy_handler phase to bypass this mechanism, by\n making in-place optimizations.\n\n TODO: find a current full explanation.\n \"\"\"\n destroy_map = {0: [0]}\n\n check_input = False\n\n_output_guard = OutputGuard()\n\n\ndef register_deep_copy_op_c_code(typ, code, version=()):\n \"\"\" Tell DeepCopyOp how to generate C code for a Theano Type\n\n :param typ: A Theano type. It must be the Theano class itself and not an\n instance of the class.\n :param code: C code that deep copies the Theano type 'typ'.\n Use %(iname)s and %(oname)s for the input and output C\n variable names respectively.\n :param version: A number indicating the version of the code, for cache.\n \"\"\"\n DeepCopyOp.c_code_and_version[typ] = (code, version)\n\n\nclass DeepCopyOp(gof.Op):\n # Mapping from Type to C code (and version) to use.\n # In the C code, the name of the input variable is %(iname)s,\n # the output variable is %(oname)s.\n c_code_and_version = {}\n\n check_input = False\n\n def __init__(self):\n pass\n\n def __str__(self):\n return self.__class__.__name__\n\n def __hash__(self):\n return hash(type(self))\n\n def __eq__(self, other):\n return type(self) == type(other)\n\n def make_node(self, x):\n return gof.Apply(self, [x], [x.type()])\n\n def perform(self, node, args, outs):\n if hasattr(args[0], 'copy'):\n # when args[0] is a an ndarray of 0 dimensions,\n # this return a numpy.dtype and not an ndarray\n # So when the args have a copy attribute we use it\n # as this don't have this problem\n outs[0][0] = args[0].copy()\n else:\n outs[0][0] = copy.deepcopy(args[0])\n\n def c_code_cache_version(self):\n version = []\n # If any of the c code is unversionned, we have to return ()\n # Else, we will return a list of (type name, version) pairs.\n for t, (c, v) in sorted(iteritems(self.c_code_and_version),\n key=lambda pair: str(pair[0])):\n if not v:\n warnings.warn(\"Type %s has C code for DeepCopyOp, but it has \"\n \"no version. You should add a 'version' keyword\"\n \" arg when calling \"\n \"register_deep_copy_op_c_code.\" % t,\n stacklevel=2)\n return ()\n version.append((str(t), v))\n\n if version:\n version.append(1)\n return tuple(version)\n\n def c_code(self, node, name, inames, onames, sub):\n iname, = inames\n oname, = onames\n fail = sub['fail']\n\n itype = node.inputs[0].type.__class__\n if itype in self.c_code_and_version:\n code, version = self.c_code_and_version[itype]\n return code % locals()\n\n # Else, no C code\n return super(DeepCopyOp, self).c_code(node, name, inames, onames, sub)\n\n\ndeep_copy_op = DeepCopyOp()\n\n\ndef register_shape_c_code(type, code, version=()):\n \"\"\" Tell Shape Op how to generate C code for a Theano Type\n\n :param typ: A Theano type. It must be the Theano class itself and not an\n instance of the class.\n :param code: C code that return a vector representing the shape\n for the Theano type 'typ'.\n Use %(iname)s and %(oname)s for the input and output C\n variable names respectively.\n :param version: A number indicating the version of the code, for cache.\n \"\"\"\n Shape.c_code_and_version[type] = (code, version)\n\n\nclass Shape(gof.Op):\n \"\"\"\n L{Op} to return the shape of a matrix.\n\n @note: Non-differentiable.\n \"\"\"\n _f16_ok = True\n\n # Mapping from Type to C code (and version) to use.\n # In the C code, the name of the input variable is %(iname)s,\n # the output variable is %(oname)s.\n c_code_and_version = {}\n\n check_input = False\n\n def __hash__(self):\n return hash(type(self))\n\n def __eq__(self, other):\n return type(self) == type(other)\n\n def __str__(self):\n return self.__class__.__name__\n\n def make_node(self, x):\n # Must work for all type that have a shape attribute.\n # This will fail at execution time.\n if not isinstance(x, theano.Variable):\n x = theano.tensor.as_tensor_variable(x)\n return gof.Apply(self, [x], [theano.tensor.lvector()])\n\n def perform(self, node, inp, out_):\n x, = inp\n out, = out_\n out[0] = theano._asarray(x.shape, dtype='int64')\n\n def infer_shape(self, node, in_shapes):\n return [[len(in_shapes[0])]]\n\n def connection_pattern(self, node):\n # the grad returns the gradient with respect to the\n # elements of a tensor variable\n # the elements of the tensor variable do not participate\n # in the computation of the shape, so they are not really\n # part of the graph\n return [[False]]\n\n def grad(self, inp, grads):\n # the grad returns the gradient with respect to the\n # elements of a tensor variable\n # the elements of the tensor variable do not participate\n # in the computation of the shape, so they are not really\n # part of the graph\n return [theano.gradient.DisconnectedType()()]\n\n def R_op(self, inputs, eval_points):\n return [None]\n\n def c_code(self, node, name, inames, onames, sub):\n iname, = inames\n oname, = onames\n fail = sub['fail']\n\n itype = node.inputs[0].type.__class__\n if itype in self.c_code_and_version:\n code, version = self.c_code_and_version[itype]\n return code % locals()\n\n # Else, no C code\n return super(Shape, self).c_code(node, name, inames, onames, sub)\n\n def c_code_cache_version(self):\n version = []\n # If any of the c code is unversionned, we have to return ()\n # Else, we will return a list of (type name, version) pairs.\n for t, (c, v) in sorted(iteritems(self.c_code_and_version),\n key=lambda pair: str(pair[0])):\n if not v:\n warnings.warn(\"Type %s has C code for Shape, but it has no \"\n \"version. You should add a 'version' keyword \"\n \"arg when calling register_shape_c_code.\" % t,\n stacklevel=2)\n return ()\n version.append((str(t), v))\n\n if version:\n version.append(1)\n\n return tuple(version)\n\n\nshape = Shape()\n_shape = shape # was used in the past, now use shape directly.\n\n\nclass Shape_i(gof.Op):\n \"\"\"\n L{Op} to return the shape of a matrix.\n\n @note: Non-differentiable.\n \"\"\"\n _f16_ok = True\n\n # Mapping from Type to C code (and version) to use.\n # In the C code, the name of the input variable is %(iname)s,\n # the output variable is %(oname)s.\n c_code_and_version = {}\n\n check_input = False\n\n __props__ = (\"i\",)\n\n def __init__(self, i):\n # As i will be used in the hash and that ndarray are not hashable,\n # we need to convert it to an int as it is hashable.\n if isinstance(i, numpy.ndarray):\n assert \"int\" in str(i.dtype)\n assert i == int(i)\n i = int(i)\n self.i = i\n\n def __str__(self):\n return '%s{%i}' % (self.__class__.__name__, self.i)\n\n def make_node(self, x):\n # x could be one of a number of types\n # the only thing we require is that the variable have a .ndim,\n # and that the value have a .shape\n if not isinstance(x, theano.Variable):\n raise TypeError('x must be Variable with ndim attribute', x)\n if x.ndim <= self.i:\n raise TypeError('x has too few dimensions for Shape_i',\n (x, self.i))\n return theano.Apply(self, [x], [theano.tensor.lscalar()])\n\n def perform(self, node, inp, out_):\n x, = inp\n out, = out_\n if out[0] is None:\n out[0] = theano._asarray(x.shape[self.i], dtype='int64')\n else:\n out[0][...] = x.shape[self.i]\n\n def c_code_cache_version(self):\n version = []\n # If any of the c code is unversionned, we have to return ()\n # Else, we will return a list of (type name, version) pairs.\n for t, (c, ci, v) in sorted(iteritems(self.c_code_and_version),\n key=lambda pair: str(pair[0])):\n if not v:\n warnings.warn(\"Type %s has C code for Shape_i, but it has \"\n \"no version. You should add a 'version' keyword \"\n \"arg when calling register_shape_i_c_code.\" % t,\n stacklevel=2)\n return ()\n version.append((str(t), v))\n\n if version:\n version.append(1)\n\n return tuple(version)\n\n def c_code(self, node, name, inames, onames, sub):\n iname, = inames\n oname, = onames\n fail = sub['fail']\n i = self.i\n\n itype = node.inputs[0].type.__class__\n if itype in self.c_code_and_version:\n code, check_input, version = self.c_code_and_version[itype]\n return (check_input + code) % locals()\n\n # Else, no C code\n return super(Shape_i, self).c_code(node, name, inames, onames, sub)\n\n def infer_shape(self, node, input_shapes):\n return [()]\n\n def grad(self, inp, grads):\n return [theano.gradient.grad_not_implemented(\n op=self, x_pos=0, x=inp[0],\n comment=(\"No gradient for the shape of a matrix \"\n \"is implemented.\"))]\n\n\ndef shape_i(var, i, fgraph=None):\n \"\"\"Equivalent of var.shape[i], but apply if possible the shape\n feature optimization\n\n This is useful in optimization that need to get the shape. This\n remove the need of the following shape_feature optimization that\n convert it. So this speed up optimization and remove Equilibrium\n max iteration problems.\n\n :param var: the variable we want to take the shape of\n :param i: The shape dimensions we want\n :param fgraph: optional. If var.fgraph do not exist, the fgraph that\n have the shape_feature to introduce var in to get the optimized shape.\n\n \"\"\"\n if fgraph is None and hasattr(var, 'fgraph'):\n fgraph = var.fgraph\n if fgraph and hasattr(fgraph, 'shape_feature'):\n shape_feature = fgraph.shape_feature\n shape_of = shape_feature.shape_of\n\n def recur(node):\n if not hasattr(node.outputs[0], 'fgraph'):\n for inp in node.inputs:\n if inp.owner:\n recur(inp.owner)\n # If the output var isn't marked as being in the graph,\n # we need to att it in the ShapeFeature.\n shape_feature.on_import(fgraph, node,\n 'gof.ops.shape_i')\n if var not in shape_of:\n recur(var.owner)\n return shape_of[var][i]\n\n # If we are not able to use the shape feature, we should not put\n # Shape_i in the graph. Otherwise, the shape feature optimization\n # won't get applied.\n return var.shape[i]\n\n\ndef register_shape_i_c_code(typ, code, check_input, version=()):\n \"\"\" Tell Shape_i how to generate C code for a Theano Type\n\n :param typ: A Theano type. It must be the Theano class itself and not\n an instance of the class.\n :param code: C code that gets the shape of dimensions %(i)s for the\n Theano type 'typ'.\n Use %(iname)s and %(oname)s for the input and output C\n variable names respectively.\n :param version: A number indicating the version of the code, for cache.\n \"\"\"\n Shape_i.c_code_and_version[typ] = (code, check_input, version)\n\n\n# List of Theano Types that one can add an extra dimension and for which\n# Scan can deal with.\nexpandable_types = ()\n\n\ndef load_back(mod, name):\n __import__(mod)\n import sys\n module = sys.modules[mod]\n obj = getattr(module, name)\n return obj\n\n\nclass FromFunctionOp(gof.Op):\n \"\"\"\n Build a basic Theano Op around a function.\n\n Since the resulting Op is very basic and is missing most of the\n optional functionalities, some optimizations may not apply. If you\n want to help, you can supply an infer_shape function that computes\n the shapes of the output given the shapes of the inputs.\n\n Also the gradient is undefined in the resulting op and Theano will\n raise an error if you attempt to get the gradient of a graph\n containing this op.\n \"\"\"\n def __init__(self, fn, itypes, otypes, infer_shape):\n self.__fn = fn\n self.itypes = itypes\n self.otypes = otypes\n self.__infer_shape = infer_shape\n if self.__infer_shape is not None:\n self.infer_shape = self._infer_shape\n\n def __eq__(self, other):\n return (type(self) == type(other) and\n self.__fn == other.__fn)\n\n def __hash__(self):\n return hash(type(self)) ^ hash(self.__fn)\n\n def __str__(self):\n return 'FromFunctionOp{%s}' % self.__fn.__name__\n\n def make_node(self, *inputs):\n if len(inputs) != len(self.itypes):\n raise ValueError(\"We expected %d inputs but got %d.\" %\n (len(self.itypes), len(inputs)))\n if not all(inp.type == it for inp, it in zip(inputs, self.itypes)):\n raise TypeError(\n \"We expected inputs of types '%s' but got types '%s' \" %\n (str([inp.type for inp in inputs]), str(self.itypes)))\n return theano.Apply(self, inputs, [o() for o in self.otypes])\n\n def perform(self, node, inputs, outputs):\n outs = self.__fn(*inputs)\n if not isinstance(outs, (list, tuple)):\n outs = (outs,)\n assert len(outs) == len(outputs)\n for i in range(len(outs)):\n outputs[i][0] = outs[i]\n\n def __reduce__(self):\n mod = self.__fn.__module__\n name = self.__fn.__name__\n try:\n obj = load_back(mod, name)\n except (ImportError, KeyError, AttributeError):\n raise pickle.PicklingError(\n \"Can't pickle as_op(), not found as %s.%s\" %\n (mod, name))\n else:\n if obj is not self:\n raise pickle.PicklingError(\n \"Can't pickle as_op(), not the object \"\n \"at %s.%s\" % (mod, name))\n return load_back, (mod, name)\n\n def _infer_shape(self, node, input_shapes):\n return self.__infer_shape(node, input_shapes)\n\n\ndef as_op(itypes, otypes, infer_shape=None):\n \"\"\"\n Decorator that converts a function into a basic Theano op that\n will call the supplied function as its implementation.\n\n It takes an optional infer_shape parameter that should be a\n callable with this signature:\n\n def infer_shape(node, input_shapes):\n ...\n return output_shapes\n\n Here `input_shapes` and `output_shapes` are lists of tuples that\n represent the shape of the corresponding inputs/outputs.\n\n This should not be used when performance is a concern since the\n very basic nature of the resulting Op may interfere with certain\n graph optimizations.\n\n Example usage:\n\n @as_op(itypes=[theano.tensor.fmatrix, theano.tensor.fmatrix],\n otypes=[theano.tensor.fmatrix])\n def numpy_dot(a, b):\n return numpy.dot(a, b)\n \"\"\"\n if not isinstance(itypes, (list, tuple)):\n itypes = [itypes]\n if any(not isinstance(t, theano.Type) for t in itypes):\n raise TypeError(\"itypes has to be a list of Theano types\")\n if not isinstance(otypes, (list, tuple)):\n otypes = [otypes]\n if any(not isinstance(t, theano.Type) for t in otypes):\n raise TypeError(\"otypes has to be a list of Theano types\")\n\n # make sure they are lists and not tuples\n itypes = list(itypes)\n otypes = list(otypes)\n\n if infer_shape is not None and not callable(infer_shape):\n raise TypeError(\"infer_shape needs to be a callable\")\n\n def make_op(fn):\n return FromFunctionOp(fn, itypes, otypes, infer_shape)\n return make_op\n\n\ndef register_rebroadcast_c_code(typ, code, version=()):\n \"\"\"Tell Rebroadcast how to generate C code for a Theano Type\n\n :param typ: A Theano type. It must be the Theano class itself and not an\n instance of the class.\n\n :param code: C code that checks if the dimension %(axis)s is of\n shape 1 for the Theano type 'typ'. Use %(iname)s and\n %(oname)s for the input and output C variable names\n respectively, and %(axis)s for the axis that we need to\n check. This code is put in a loop for all axes.\n\n :param version: A number indicating the version of the code, for cache.\n \"\"\"\n Rebroadcast.c_code_and_version[typ] = (code, version)\n\n\nclass Rebroadcast(gof.Op):\n \"\"\"\n Change the input's broadcastable fields in some predetermined way.\n\n :code:`Rebroadcast((0, True), (1, False))(x)` would make :code:`x`\n broadcastable in axis 0 and not broadcastable in axis 1\n\n .. seealso::\n\n :func:`unbroadcast <theano.tensor.unbroadcast>`\n :func:`addbroadcast <theano.tensor.addbroadcast>`\n :func:`patternbroadcast <theano.tensor.patternbroadcast>`\n\n ..note: works inplace and works for CudaNdarrayType\n \"\"\"\n view_map = {0: [0]}\n _f16_ok = True\n # Mapping from Type to C code (and version) to use.\n # In the C code, the name of the input variable is %(iname)s,\n # the output variable is %(oname)s.\n c_code_and_version = {}\n\n check_input = False\n\n def __init__(self, *axis):\n self.axis = dict(axis)\n for axis, broad in iteritems(self.axis):\n assert isinstance(axis, (numpy.integer, int)), (\n \"Rebroadcast needs integer axes. Got \", axis)\n\n def __eq__(self, other):\n return type(self) == type(other) and self.axis == other.axis\n\n def __hash__(self):\n # no ambiguity because each item key is unique\n items = sorted(iteritems(self.axis))\n return hash((type(self), tuple(items)))\n\n def __str__(self):\n if len(self.axis) == 0:\n broadcast_pattern = []\n else:\n broadcast_pattern = ['?' for i\n in xrange(1 + max(self.axis.keys()))]\n for k, v in iteritems(self.axis):\n broadcast_pattern[k] = str(int(v))\n return '%s{%s}' % (self.__class__.__name__,\n ','.join(broadcast_pattern))\n\n def make_node(self, x):\n if self.axis.keys() and (x.ndim <= max(self.axis.keys())):\n raise ValueError('Trying to rebroadcast non-existent dimension')\n t = x.type.clone(\n broadcastable=[self.axis.get(i, b)\n for i, b in enumerate(x.type.broadcastable)])\n return gof.Apply(self, [x], [t()])\n\n def perform(self, node, inp, out_):\n x, = inp\n out, = out_\n for axis, value in iteritems(self.axis):\n if value and x.shape[axis] != 1:\n raise ValueError('Dimension %s in Rebroadcast\\'s input was'\n ' supposed to be 1 (got %s instead)' %\n (axis, x.shape[axis]))\n out[0] = x\n\n def grad(self, inp, grads):\n x, = inp\n gz, = grads\n # restore the broadcasting pattern of the input\n return Rebroadcast(*[(axis, x.type.broadcastable[axis])\n for axis, value in iteritems(self.axis)])(gz),\n\n def infer_shape(self, node, ishapes):\n assert len(ishapes) == 1\n l = []\n one = theano.tensor.basic.constant(1)\n for ax in xrange(len(ishapes[0])):\n if self.axis.get(ax, False):\n l.append(one)\n else:\n l.append(ishapes[0][ax])\n\n return [tuple(l)]\n\n def R_op(self, inputs, eval_points):\n if eval_points[0] is None:\n return [None]\n return self(*eval_points, **dict(return_list=True))\n\n def c_code(self, node, nodename, inp, out, sub):\n iname, = inp\n oname, = out\n fail = sub['fail']\n\n itype = node.inputs[0].type.__class__\n if itype in self.c_code_and_version:\n code, version = self.c_code_and_version[itype]\n final_code = \"\"\n for axis, value in iteritems(self.axis):\n if value:\n final_code += code % locals()\n return final_code + \"\"\"\n Py_XDECREF(%(oname)s);\n %(oname)s = %(iname)s;\n Py_XINCREF(%(oname)s);\n \"\"\" % locals()\n return super(Rebroadcast, self).c_code(node, nodename, inp, out, sub)\n\n def c_code_cache_version(self):\n version = []\n # If any of the c code is unversionned, we have to return ()\n # Else, we will return a list of (type name, version) pairs.\n for t, (c, v) in sorted(iteritems(self.c_code_and_version),\n key=lambda pair: str(pair[0])):\n if not v:\n warnings.warn(\"Type %s has C code for Rebroadcast, but it \"\n \"has no version. You should add a 'version' \"\n \"keyword arg when calling \"\n \"register_rebroadcast_c_code.\" % t,\n stacklevel=2)\n return ()\n version.append((str(t), v))\n\n if version:\n version.append(1)\n return tuple(version)\n\n\ndef register_specify_shape_c_code(typ, code, version=(),\n c_support_code_apply=None):\n \"\"\" Tell SpecifyShape how to generate C code for a Theano Type\n\n :param typ: A Theano type. It must be the Theano class itself and\n not an instance of the class.\n :param code: C code that checks the shape and returns a view for\n the Theano type 'typ'. Use %(iname)s and %(oname)s\n for the input and output C variable names\n respectively. %(shape)s is the vector of shape of\n %(iname)s. Check that its length is good.\n :param version: A number indicating the version of the code, for cache.\n :param c_support_code_apply: extra code.\n \"\"\"\n SpecifyShape.c_code_and_version[typ] = (code, version,\n c_support_code_apply)\n\n\nclass SpecifyShape(gof.Op):\n \"\"\"\n L{Op} that puts into the graph the user-provided shape.\n\n In the case where this op stays in the final graph, we assert the shape.\n For this the output of this op must be used in the graph. This is not\n the case most of the time if we only take the shape of the output.\n Maybe there are other optimizations that will mess with this.\n\n @note: Maybe in the future we will never do the assert!\n @note: We currently don't support specifying partial shape information.\n\n @todo: test this op with sparse and cuda ndarray.\n Do C code for them too.\n \"\"\"\n view_map = {0: [0]}\n # Mapping from Type to C code (and version) to use.\n # In the C code, the name of the input variable is %(iname)s,\n # the output variable is %(oname)s.\n c_code_and_version = {}\n\n def __hash__(self):\n return hash(type(self))\n\n def __eq__(self, other):\n return type(self) == type(other)\n\n def __str__(self):\n return self.__class__.__name__\n\n def make_node(self, x, shape):\n if not isinstance(x, gof.Variable):\n x = theano.tensor.as_tensor_variable(x)\n shape = theano.tensor.as_tensor_variable(shape)\n assert shape.ndim == 1\n assert \"int\" in shape.dtype\n if isinstance(shape, theano.tensor.TensorConstant):\n assert shape.data.size == x.ndim\n return gof.Apply(self, [x, shape], [x.type()])\n\n def perform(self, node, inp, out_):\n x, shape = inp\n out, = out_\n assert x.ndim == shape.size\n assert numpy.all(x.shape == shape), (\"got shape\", x.shape,\n \"expected\", shape)\n out[0] = x\n\n def infer_shape(self, node, shapes):\n xshape, sshape = shapes\n new_shape = []\n for dim in xrange(node.inputs[0].ndim):\n try:\n s = theano.tensor.get_scalar_constant_value(\n node.inputs[1][dim])\n s = theano.tensor.as_tensor_variable(s)\n new_shape.append(s)\n except theano.tensor.NotScalarConstantError:\n new_shape.append(node.inputs[1][dim])\n\n assert len(new_shape) == len(xshape)\n return [new_shape]\n\n def connection_pattern(self, node):\n return [[True], [False]]\n\n def grad(self, inp, grads):\n x, s = inp\n gz, = grads\n # Should I set an SpecifyShape on gz? I think so\n # But I don't do it now as we need to make an optimization\n # to remove that op from the graph to don't block other optimization\n # Should I do an optimizer that will remove the SpecifyShape?\n # I think Yes\n return [gz, theano.gradient.DisconnectedType()()]\n return [specify_shape(gz, s), theano.gradient.DisconnectedType()()]\n\n def R_op(self, inputs, eval_points):\n if eval_points[0] is None:\n # It means that the this op sits on top of a non-differentiable\n # path\n return [None]\n return self.make_node(eval_points[0], *inputs[1:]).outputs\n\n def c_support_code_apply(self, node, name):\n itype = node.inputs[0].type.__class__\n if itype in self.c_code_and_version:\n _, _, support_code = self.c_code_and_version[itype]\n if support_code:\n return support_code\n return super(SpecifyShape, self).c_support_code_apply(node, name)\n\n def c_code(self, node, name, inames, onames, sub):\n iname, shape = inames\n oname, = onames\n fail = sub['fail']\n\n itype = node.inputs[0].type.__class__\n if itype in self.c_code_and_version:\n code, version, _ = self.c_code_and_version[itype]\n return code % locals()\n\n return super(SpecifyShape, self).c_code(node, node, inames,\n onames, sub)\n\n def c_code_cache_version(self):\n version = []\n # If any of the c code is unversionned, we have to return ()\n # Else, we will return a list of (type name, version) pairs.\n for t, (c, v, _) in sorted(iteritems(self.c_code_and_version),\n key=lambda pair: str(pair[0])):\n if not v:\n warnings.warn(\"Type %s has C code for SpecifyShape, but it \"\n \"has no version. You should add a 'version' \"\n \"keyword arg when calling \"\n \"register_specify_shape_c_code.\" % t,\n stacklevel=2)\n return ()\n version.append((str(t), v))\n\n return tuple(version)\n\n\nspecify_shape = SpecifyShape()\n",
"import theano\nimport numpy\nfrom . import scan\n\n\ndef test_001():\n x0 = theano.tensor.fvector('x0')\n state = theano.tensor.unbroadcast(\n theano.tensor.shape_padleft(x0), 0)\n out, _ = scan.scan(lambda x: x+numpy.float32(1),\n states=state,\n n_steps=5)\n fn = theano.function([x0], out[0])\n val_x0 = numpy.float32([1, 2, 3])\n assert numpy.all(fn(val_x0) == val_x0 + 5)\n\n\ndef test_002():\n x0 = theano.tensor.fvector('x0')\n state = theano.tensor.alloc(\n theano.tensor.constant(numpy.float32(0)),\n 6,\n x0.shape[0])\n state = theano.tensor.set_subtensor(state[0], x0)\n\n out, _ = scan.scan(lambda x: x+numpy.float32(1),\n states=state,\n n_steps=5)\n fn = theano.function([x0], out)\n val_x0 = numpy.float32([1, 2, 3])\n assert numpy.all(fn(val_x0)[-1] == val_x0 + 5)\n assert numpy.all(fn(val_x0)[0] == val_x0)\n\n\ndef test_003():\n x0 = theano.tensor.fvector('x0')\n sq = theano.tensor.fvector('sq')\n state = theano.tensor.alloc(\n theano.tensor.constant(numpy.float32(0)),\n 6,\n x0.shape[0])\n state = theano.tensor.set_subtensor(state[0], x0)\n\n out, _ = scan.scan(lambda s, x: x+s,\n sequences=sq,\n states=state,\n n_steps=5)\n fn = theano.function([sq, x0], out)\n val_x0 = numpy.float32([1, 2, 3])\n val_sq = numpy.float32([1, 2, 3, 4, 5])\n assert numpy.all(fn(val_sq, val_x0)[-1] == val_x0 + 15)\n assert numpy.all(fn(val_sq, val_x0)[0] == val_x0)\n\n\ndef test_004():\n sq = theano.tensor.fvector('sq')\n nst = theano.tensor.iscalar('nst')\n out, _ = scan.scan(lambda s: s+numpy.float32(1),\n sequences=sq,\n states=[],\n n_steps=nst)\n fn = theano.function([sq, nst], out)\n val_sq = numpy.float32([1, 2, 3, 4, 5])\n assert numpy.all(fn(val_sq, 5) == val_sq + 1)\n\n\ndef test_005():\n sq = theano.tensor.fvector('sq')\n nst = theano.tensor.iscalar('nst')\n out, _ = scan.scan(lambda s: s+numpy.float32(1),\n sequences=sq,\n states=[None],\n n_steps=nst)\n fn = theano.function([sq, nst], out)\n val_sq = numpy.float32([1, 2, 3, 4, 5])\n assert numpy.all(fn(val_sq, 5) == val_sq + 1)\n\n\nif __name__ == '__main__':\n test_001()\n test_002()\n test_003()\n test_004()\n test_005()\n\n"
] | [
[
"numpy.asarray",
"numpy.max",
"numpy.zeros",
"numpy.min"
],
[
"numpy.int64",
"numpy.min"
],
[
"numpy.zeros"
],
[
"numpy.all"
],
[
"numpy.float32"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
opengridcc/opengrid_dev | [
"cc6dc9d615197e4901a8d213fe81fc71bcd602c4"
] | [
"opengrid_dev/library/houseprint/houseprint.py"
] | [
"__author__ = 'Jan Pecinovsky'\n\nfrom opengrid_dev.config import Config\n\nconfig = Config()\n\nimport os\nimport sys\nimport json\nimport jsonpickle\nimport datetime as dt\nimport pandas as pd\nfrom requests.exceptions import HTTPError\nimport warnings\nfrom tqdm import tqdm\n\n# compatibility with py3\nif sys.version_info.major >= 3:\n import pickle\nelse:\n import cPickle as pickle\n\nimport tmpo\n\n# compatibility with py3\nif sys.version_info.major >= 3:\n from .site import Site\n from .device import Device, Fluksometer\n from .sensor import Sensor, Fluksosensor\nelse:\n from site import Site\n from device import Device, Fluksometer\n from sensor import Sensor, Fluksosensor\n\n\"\"\"\nThe Houseprint is a Singleton object which contains all metadata for sites, devices and sensors.\nIt can be pickled, saved and passed around\n\"\"\"\n\n\nclass Houseprint(object):\n def __init__(self,\n gjson=None,\n spreadsheet=\"Opengrid houseprint (Responses)\",\n empty_init=False\n ):\n \"\"\"\n Parameters\n ---------\n gjson: Path to authentication json\n spreadsheet: String, name of the spreadsheet containing the metadata\n \"\"\"\n\n self.sites = []\n self.timestamp = dt.datetime.utcnow() # Add a timestamp upon creation\n\n if not empty_init:\n if gjson is None:\n gjson = config.get('houseprint', 'json')\n self.gjson = gjson\n self.spreadsheet = spreadsheet\n self._parse_sheet()\n\n def reset(self):\n \"\"\"\n Connect to the Google Spreadsheet again and re-parse the data\n \"\"\"\n self.__init__(gjson=self.gjson, spreadsheet=self.spreadsheet)\n if hasattr(self, '_tmpos'):\n self._add_sensors_to_tmpos() \n\n def __repr__(self):\n return \"\"\"\n Houseprint\n Created on {} (UTC)\n {} sites\n {} devices\n {} sensors\n \"\"\".format(self.timestamp,\n len(self.sites),\n sum([len(site.devices) for site in self.sites]),\n sum([len(site.sensors) for site in self.sites])\n )\n\n def _parse_sheet(self):\n \"\"\"\n Connects to Google, fetches the spreadsheet and parses the content\n \"\"\"\n\n import gspread\n from oauth2client.client import SignedJwtAssertionCredentials\n\n print('Opening connection to Houseprint sheet')\n # fetch credentials\n json_key = json.load(open(self.gjson))\n scope = ['https://spreadsheets.google.com/feeds']\n credentials = SignedJwtAssertionCredentials(\n json_key['client_email'],\n json_key['private_key'].encode('ascii'),\n scope\n )\n\n # authorize and login\n gc = gspread.authorize(credentials)\n gc.login()\n\n # open sheets\n print(\"Opening spreadsheets\")\n sheet = gc.open(self.spreadsheet)\n sites_sheet = sheet.worksheet('Accounts')\n devices_sheet = sheet.worksheet('Devices')\n sensors_sheet = sheet.worksheet('Sensors')\n\n print('Parsing spreadsheets')\n # 3 sub-methods that parse the different sheets\n self._parse_sites(sites_sheet)\n self._parse_devices(devices_sheet)\n self._parse_sensors(sensors_sheet)\n\n print('Houseprint parsing complete')\n\n def _parse_sites(self, sheet):\n \"\"\"\n Sub method of _parse_sheet() that parses only the 'sites' sheet\n\n Parameters\n ----------\n sheet: GSpread worksheet\n sheet containing metadata about sites\n \"\"\"\n\n records = sheet.get_all_records()\n\n for r in records:\n if r['Key'] == '':\n continue\n new_site = Site(hp=self,\n key=r['Key'],\n size=r['House size'],\n inhabitants=r['Number of inhabitants'],\n postcode=r['postcode'],\n construction_year=r['construction year'],\n k_level=r['K-level'],\n e_level=r['E-level'],\n epc_cert=r['EPC certificate'])\n self.sites.append(new_site)\n\n print('{} Sites created'.format(len(self.sites)))\n\n def _parse_devices(self, sheet):\n \"\"\"\n Sub method of _parse_sheet() that parses only the 'devices' sheet\n\n Parameters\n ----------\n sheet: GSpread worksheet\n sheet containing metadata about devices\n \"\"\"\n\n records = sheet.get_all_records()\n\n for r in records:\n if r['Key'] == '':\n continue\n\n # find parent site and check if it exists\n site = self.find_site(r['Parent site'])\n if site is None:\n raise ValueError('Device {} was given an invalid site key {}'.format(r['Key'], r['Parent site']))\n\n # create a new device according to its manufacturer\n if r['manufacturer'] == 'Flukso':\n new_device = Fluksometer(site=site, key=r['Key'])\n else:\n raise NotImplementedError('Devices from {} are not supported'.format(r['manufacturer']))\n\n # add new device to parent site\n site.devices.append(new_device)\n\n print('{} Devices created'.format(sum([len(site.devices) for site in self.sites])))\n\n def _parse_sensors(self, sheet):\n \"\"\"\n Sub method of _parse_sheet() that parses only the 'sensors' sheet\n\n Parameters\n ----------\n sheet: GSpread worksheet\n sheet containing metadata about sensors\n \"\"\"\n\n records = sheet.get_all_records()\n\n for r in records:\n if r['Sensor_id'] == '': continue\n\n # find parent. If a parent device is specified, us that, otherwise use a parent site directly\n if r['parent device'] != '':\n device = self.find_device(r['parent device'])\n if device is None:\n raise ValueError(\n 'Sensor {} was given an invalid device key {}. \\\n Leave the device field empty if you want to add a sensor without a device'.format(\n r['Sensor_id'], r['parent device']))\n else:\n site = self.find_site(r['parent site'])\n if site is None:\n raise ValueError(\n 'Sensor {} was given an invalid site key {}'.format(r['Sensor_id'], r['parent site']))\n\n # create new sensor according to its manufacturer\n if r['manufacturer'] == 'Flukso':\n new_sensor = Fluksosensor(\n device=device,\n key=r['Sensor_id'],\n token=r['token'],\n type=r['sensor type'],\n description=r['name by user'],\n system=r['system'],\n quantity=r['quantity'],\n unit=r['unit'],\n direction=r['direction'],\n tariff=r['tariff'],\n cumulative=None # will be determined based on type\n )\n else:\n raise NotImplementedError('Sensors from {} are not supported'.format(r['manufacturer']))\n\n new_sensor.device.sensors.append(new_sensor)\n\n print('{} sensors created'.format(sum([len(site.sensors) for site in self.sites])))\n\n def get_sensors(self, sensortype=None):\n \"\"\"\n Return a list with all sensors\n\n Parameters\n ----------\n sensortype: gas, water, electricity: optional\n\n Returns\n -------\n list of sensors\n \"\"\"\n res = []\n for site in self.sites:\n for sensor in site.get_sensors(sensortype=sensortype):\n res.append(sensor)\n return res\n\n def get_fluksosensors(self, **kwargs):\n \"\"\"\n Same thing as get_sensors, but only for fluksosensors\n\n Parameters\n ----------\n kwargs\n\n Returns\n -------\n [Fluksosensor]\n \"\"\"\n return [sensor for sensor in self.get_sensors(**kwargs) if isinstance(\n sensor, Fluksosensor)]\n\n def get_devices(self):\n \"\"\"\n Return a list with all devices\n\n Returns\n -------\n list of devices\n \"\"\"\n res = []\n for site in self.sites:\n for device in site.devices:\n res.append(device)\n return res\n\n def search_sites(self, **kwargs):\n \"\"\"\n Parameters\n ----------\n kwargs: any keyword argument, like key=mykey\n\n Returns\n -------\n List of sites satisfying the search criterion or empty list if no\n variable found.\n \"\"\"\n\n result = []\n for site in self.sites:\n for keyword, value in kwargs.items():\n if getattr(site, keyword) == value:\n continue\n else:\n break\n else:\n result.append(site)\n\n return result\n\n def search_sensors(self, **kwargs):\n \"\"\"\n Parameters\n ----------\n kwargs: any keyword argument, like key=mykey\n\n Returns\n -------\n List of sensors satisfying the search criterion or empty list if no\n variable found.\n \"\"\"\n\n result = []\n for sensor in self.get_sensors():\n for keyword, value in kwargs.items():\n if value in getattr(sensor, keyword):\n continue\n else:\n break\n else:\n result.append(sensor)\n\n return result\n\n def find_site(self, key):\n \"\"\"\n Parameters\n ----------\n key: string\n\n Returns\n -------\n Site\n \"\"\"\n\n for site in self.sites:\n if site.key == key:\n return site\n return None\n\n def find_device(self, key):\n \"\"\"\n Parameters\n ----------\n key: string\n\n Returns\n -------\n Device\n \"\"\"\n for device in self.get_devices():\n if device.key.lower() == key.lower():\n return device\n return None\n\n def find_sensor(self, key):\n \"\"\"\n Parameters\n ----------\n key: string\n\n Returns\n -------\n Sensor\n \"\"\"\n for sensor in self.get_sensors():\n if sensor.key.lower() == key.lower():\n return sensor\n return None\n\n def save(self, filename, pickle_format='jsonpickle'):\n \"\"\"\n Save the houseprint object\n\n Parameters\n ----------\n * filename : str\n Filename, if relative path or just filename, it is appended to the\n current working directory\n pickle_format : str\n 'jsonpickle' or 'pickle'\n pickle may be more robust, but jsonpickle should be compatible\n across python versions\n\n \"\"\"\n # temporarily delete tmpo session\n try:\n tmpos_tmp = self._tmpos\n delattr(self, '_tmpos')\n except:\n pass\n\n abspath = os.path.join(os.getcwd(), filename)\n\n if pickle_format == 'jsonpickle':\n with open(abspath, 'w') as f:\n frozen = jsonpickle.encode(self)\n f.write(frozen)\n elif pickle_format == 'pickle':\n with open(abspath, 'wb') as f:\n pickle.dump(self, file=f)\n else:\n raise NotImplementedError(\"Pickle format '{}' is not supported\".format(pickle_format))\n\n print(\"Saved houseprint to {}\".format(abspath))\n\n # restore tmposession if needed\n try:\n setattr(self, '_tmpos', tmpos_tmp)\n except:\n pass\n\n def init_tmpo(self, tmpos=None, path_to_tmpo_data=None):\n \"\"\"\n Flukso sensors need a tmpo session to obtain data.\n It is overkill to have each flukso sensor make its own session, syncing would\n take too long and be overly redundant.\n Passing a tmpo session to the get_data function is also bad form because \n we might add new types of sensors that don't use tmpo in the future.\n This is why the session is initialised here.\n\n A tmpo session as parameter is optional. If passed, no additional sensors are added.\n \n If no session is passed, a new one will be created using the location in the config file.\n It will then be populated with the flukso sensors known to the houseprint object\n\n Parameters\n ----------\n\n tmpos : tmpo session\n path_to_tmpo_data : str\n \"\"\"\n\n if tmpos is not None:\n self._tmpos = tmpos\n else:\n try:\n path_to_tmpo_data = config.get('tmpo', 'data')\n except:\n path_to_tmpo_data = None\n\n self._tmpos = tmpo.Session(path_to_tmpo_data)\n self._add_sensors_to_tmpos()\n\n print(\"Using tmpo database from {}\".format(self._tmpos.db))\n\n def _add_sensors_to_tmpos(self):\n \"\"\"\n Add all flukso sensors in the houseprint to the tmpo session\n \"\"\"\n\n for sensor in self.get_fluksosensors():\n self._tmpos.add(sensor.key, sensor.token)\n\n def get_tmpos(self):\n \"\"\"\n Returns\n -------\n TMPO session\n \"\"\"\n if hasattr(self, '_tmpos'):\n return self._tmpos\n else:\n self.init_tmpo()\n return self._tmpos\n\n @property\n def tmpos(self):\n return self.get_tmpos()\n\n def sync_tmpos(self, http_errors='warn'):\n \"\"\"\n Add all Flukso sensors to the TMPO session and sync\n\n Parameters\n ----------\n http_errors : 'raise' | 'warn' | 'ignore'\n default 'warn'\n define what should be done with TMPO Http-errors\n \"\"\"\n\n tmpos = self.get_tmpos()\n for sensor in tqdm(self.get_fluksosensors()):\n try:\n warnings.simplefilter('ignore')\n tmpos.sync(sensor.key)\n warnings.simplefilter('default')\n except HTTPError as e:\n warnings.simplefilter('default')\n if http_errors == 'ignore':\n continue\n elif http_errors == 'warn':\n warnings.warn(message='Error for SensorID: ' + sensor.key\n + str(e))\n else:\n print('Error for SensorID: ' + sensor.key)\n raise e\n\n def get_data(self, sensors=None, sensortype=None, head=None, tail=None, diff='default', resample='min',\n unit='default'):\n \"\"\"\n Return a Pandas Dataframe with joined data for the given sensors\n\n Parameters\n ----------\n sensors : list of Sensor objects\n If None, use sensortype to make a selection\n sensortype : string (optional)\n gas, water, electricity. If None, and Sensors = None,\n all available sensors in the houseprint are fetched\n head, tail: timestamps,\n diff : bool or 'default'\n If True, the original data will be differentiated\n If 'default', the sensor will decide: if it has the attribute\n cumulative==True, the data will be differentiated.\n resample : str (default='min')\n Sampling rate, if any. Use 'raw' if no resampling.\n unit : str , default='default'\n String representation of the target unit, eg m**3/h, kW, ...\n \n \"\"\"\n if sensors is None:\n sensors = self.get_sensors(sensortype)\n series = [sensor.get_data(head=head, tail=tail, diff=diff, resample=resample, unit=unit) for sensor in sensors]\n\n # workaround for https://github.com/pandas-dev/pandas/issues/12985\n series = [s for s in series if not s.empty]\n\n if series:\n df = pd.concat(series, axis=1)\n else:\n df = pd.DataFrame()\n\n # Add unit as string to each series in the df. This is not persistent: the attribute unit will get\n # lost when doing operations with df, but at least it can be checked once.\n for s in series:\n try:\n df[s.name].unit = s.unit\n except:\n pass\n\n return df\n\n def get_data_dynamic(self, sensors=None, sensortype=None, head=None,\n tail=None, diff='default', resample='min',\n unit='default'):\n \"\"\"\n Yield Pandas Series for the given sensors\n\n Parameters\n ----------\n sensors : list(Sensor), optional\n If None, use sensortype to make a selection\n sensortype : str, optional\n gas, water, electricity. If None, and Sensors = None,\n all available sensors in the houseprint are fetched\n head : dt.datetime | pd.Timestamp | int, optional\n tail : dt.datetime | pd.Timestamp | int, optional\n diff : bool | str('default')\n If True, the original data will be differentiated\n If 'default', the sensor will decide: if it has the attribute\n cumulative==True, the data will be differentiated.\n resample : str\n default='min'\n Sampling rate, if any. Use 'raw' if no resampling.\n unit : str\n default='default'\n String representation of the target unit, eg m**3/h, kW, ...\n\n Yields\n ------\n Pandas.Series\n \"\"\"\n if sensors is None:\n sensors = self.get_sensors(sensortype)\n\n for sensor in sensors:\n ts = sensor.get_data(head=head, tail=tail, diff=diff,\n resample=resample, unit=unit)\n if ts.empty:\n continue\n else:\n yield ts\n\n def add_site(self, site):\n \"\"\"\n Parameters\n ----------\n site : Site\n \"\"\"\n site.hp = self\n self.sites.append(site)\n\n\ndef load_houseprint_from_file(filename, pickle_format='jsonpickle'):\n \"\"\"\n Return a static (=anonymous) houseprint object\n\n Parameters\n ----------\n filename : str\n pickle_format : str\n 'jsonpickle' or 'pickle'\n pickle may be more robust, but jsonpickle should be compatible\n across python versions\n \"\"\"\n if pickle_format == 'jsonpickle':\n with open(filename, 'r') as f:\n hp = jsonpickle.decode(f.read())\n elif pickle_format == 'pickle':\n with open(filename, 'rb') as f:\n hp = pickle.load(file=f)\n else:\n raise NotImplementedError(\"Pickle format '{}' is not supported\".format(pickle_format))\n\n return hp\n"
] | [
[
"pandas.concat",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
takeratta/chainer | [
"02686e98cd6dc8f20979a1f3a79130f076cbfc6c",
"02686e98cd6dc8f20979a1f3a79130f076cbfc6c",
"02686e98cd6dc8f20979a1f3a79130f076cbfc6c",
"02686e98cd6dc8f20979a1f3a79130f076cbfc6c",
"02686e98cd6dc8f20979a1f3a79130f076cbfc6c",
"02686e98cd6dc8f20979a1f3a79130f076cbfc6c",
"02686e98cd6dc8f20979a1f3a79130f076cbfc6c",
"02686e98cd6dc8f20979a1f3a79130f076cbfc6c",
"02686e98cd6dc8f20979a1f3a79130f076cbfc6c",
"02686e98cd6dc8f20979a1f3a79130f076cbfc6c"
] | [
"tests/chainer_tests/functions_tests/pooling_tests/test_roi_pooling_2d.py",
"tests/chainer_tests/functions_tests/activation_tests/test_relu.py",
"tests/chainer_tests/utils_tests/test_conv.py",
"examples/reinforcement_learning/dqn_cartpole.py",
"tests/chainer_tests/functions_tests/math_tests/test_scale.py",
"tests/chainer_tests/functions_tests/array_tests/test_swapaxes.py",
"examples/reinforcement_learning/ddpg_pendulum.py",
"tests/chainer_tests/functions_tests/array_tests/test_squeeze.py",
"tests/chainer_tests/links_tests/model_tests/test_vision.py",
"tests/chainer_tests/links_tests/connection_tests/test_n_step_rnn.py"
] | [
"import unittest\n\nimport numpy\n\nimport chainer\nfrom chainer import cuda\nfrom chainer import functions\nfrom chainer import gradient_check\nfrom chainer import testing\nfrom chainer.testing import attr\n\n\nclass TestROIPooling2D(unittest.TestCase):\n\n def setUp(self):\n N = 3\n n_channels = 3\n self.x = numpy.arange(\n N * n_channels * 12 * 8,\n dtype=numpy.float32).reshape((N, n_channels, 12, 8))\n numpy.random.shuffle(self.x)\n self.x = 2 * self.x / self.x.size - 1\n self.rois = numpy.array([\n [0, 1, 1, 6, 6],\n [2, 6, 2, 7, 11],\n [1, 3, 1, 5, 10],\n [0, 3, 3, 3, 3]\n ], dtype=numpy.float32)\n n_rois = self.rois.shape[0]\n self.outh, self.outw = 5, 7\n self.spatial_scale = 0.6\n self.gy = numpy.random.uniform(\n -1, 1, (n_rois, n_channels,\n self.outh, self.outw)).astype(numpy.float32)\n self.check_backward_options = {'atol': 1e-3, 'rtol': 1e-2}\n\n def check_forward(self, x_data, roi_data):\n x = chainer.Variable(x_data)\n rois = chainer.Variable(roi_data)\n y = functions.roi_pooling_2d(\n x, rois, outh=self.outh, outw=self.outw,\n spatial_scale=self.spatial_scale)\n self.assertEqual(y.data.dtype, numpy.float32)\n y_data = cuda.to_cpu(y.data)\n\n self.assertEqual(self.gy.shape, y_data.shape)\n\n def test_forward_cpu(self):\n self.check_forward(self.x, self.rois)\n\n @attr.gpu\n def test_forward_gpu(self):\n self.check_forward(cuda.to_gpu(self.x), cuda.to_gpu(self.rois))\n\n @attr.gpu\n def test_forward_cpu_gpu_equal(self):\n # cpu\n x_cpu = chainer.Variable(self.x)\n rois_cpu = chainer.Variable(self.rois)\n y_cpu = functions.roi_pooling_2d(\n x_cpu, rois_cpu, outh=self.outh, outw=self.outw,\n spatial_scale=self.spatial_scale)\n\n # gpu\n x_gpu = chainer.Variable(cuda.to_gpu(self.x))\n rois_gpu = chainer.Variable(cuda.to_gpu(self.rois))\n y_gpu = functions.roi_pooling_2d(\n x_gpu, rois_gpu, outh=self.outh, outw=self.outw,\n spatial_scale=self.spatial_scale)\n testing.assert_allclose(y_cpu.data, cuda.to_cpu(y_gpu.data))\n\n def check_backward(self, x_data, roi_data, y_grad):\n gradient_check.check_backward(\n functions.ROIPooling2D(outh=self.outh,\n outw=self.outw,\n spatial_scale=self.spatial_scale),\n (x_data, roi_data), y_grad, no_grads=[False, True],\n **self.check_backward_options)\n\n def test_backward_cpu(self):\n self.check_backward(self.x, self.rois, self.gy)\n\n @attr.gpu\n def test_backward_gpu(self):\n self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.rois),\n cuda.to_gpu(self.gy))\n\n\ntesting.run_module(__name__, __file__)\n",
"import unittest\n\nimport mock\nimport numpy\n\nimport chainer\nfrom chainer import cuda\nfrom chainer import functions\nfrom chainer import gradient_check\nfrom chainer import testing\nfrom chainer.testing import attr\n\n\[email protected](*testing.product({\n 'shape': [(3, 2), ()],\n 'dtype': [numpy.float16, numpy.float32, numpy.float64],\n}))\[email protected]_random()\nclass TestReLU(unittest.TestCase):\n\n def setUp(self):\n # Avoid unstability of numerical grad\n self.x = numpy.random.uniform(-1, 1, self.shape).astype(self.dtype)\n self.x[(-0.1 < self.x) & (self.x < 0.1)] = 0.5\n self.gy = numpy.random.uniform(-1, 1, self.shape).astype(self.dtype)\n self.ggx = numpy.random.uniform(-1, 1, self.shape).astype(self.dtype)\n self.check_backward_options = {}\n self.check_double_backward_options = {}\n if self.dtype == numpy.float16:\n self.check_double_backward_options = {'atol': 1e-3, 'rtol': 1e-2}\n\n def check_forward(self, x_data, use_cudnn='always'):\n x = chainer.Variable(x_data)\n with chainer.using_config('use_cudnn', use_cudnn):\n y = functions.relu(x)\n self.assertEqual(y.data.dtype, self.dtype)\n\n expected = self.x.copy()\n expected[expected < 0] = 0\n\n testing.assert_allclose(expected, y.data)\n\n def test_forward_cpu(self):\n self.check_forward(self.x)\n\n @attr.gpu\n def test_forward_gpu(self):\n self.check_forward(cuda.to_gpu(self.x))\n\n @attr.gpu\n def test_forward_gpu_no_cudnn(self):\n self.check_forward(cuda.to_gpu(self.x), 'never')\n\n def check_backward(self, x_data, y_grad, use_cudnn='always'):\n with chainer.using_config('use_cudnn', use_cudnn):\n gradient_check.check_backward(\n functions.relu, x_data, y_grad, dtype=numpy.float64,\n **self.check_backward_options)\n\n def test_backward_cpu(self):\n self.check_backward(self.x, self.gy)\n\n @attr.gpu\n def test_backward_gpu(self):\n self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.gy))\n\n @attr.gpu\n def test_backward_gpu_non_contiguous(self):\n self.check_backward(cuda.cupy.asfortranarray(cuda.to_gpu(self.x)),\n cuda.cupy.asfortranarray(cuda.to_gpu(self.gy)))\n\n @attr.gpu\n def test_backward_cpu_no_cudnn(self):\n self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.gy), 'never')\n\n def check_double_backward(self, x_data, y_grad, x_grad_grad,\n use_cudnn='always'):\n def f(x):\n x = functions.relu(x)\n return x * x\n\n with chainer.using_config('use_cudnn', use_cudnn):\n gradient_check.check_double_backward(\n f, x_data, y_grad, x_grad_grad, dtype=numpy.float64,\n **self.check_double_backward_options)\n\n def test_double_backward_cpu(self):\n self.check_double_backward(self.x, self.gy, self.ggx)\n\n @attr.gpu\n def test_double_backward_gpu(self):\n self.check_double_backward(cuda.to_gpu(self.x),\n cuda.to_gpu(self.gy),\n cuda.to_gpu(self.ggx))\n\n @attr.gpu\n def test_double_backward_gpu_non_contiguous(self):\n self.check_double_backward(\n cuda.cupy.asfortranarray(cuda.to_gpu(self.x)),\n cuda.cupy.asfortranarray(cuda.to_gpu(self.gy)),\n cuda.cupy.asfortranarray(cuda.to_gpu(self.ggx)))\n\n @attr.gpu\n def test_double_backward_cpu_no_cudnn(self):\n self.check_double_backward(cuda.to_gpu(self.x),\n cuda.to_gpu(self.gy),\n cuda.to_gpu(self.ggx),\n 'never')\n\n\[email protected](*testing.product({\n 'use_cudnn': ['always', 'auto', 'never'],\n 'dtype': [numpy.float16, numpy.float32, numpy.float64],\n}))\[email protected]\nclass TestReLUCudnnCall(unittest.TestCase):\n\n def setUp(self):\n self.x = cuda.cupy.random.uniform(-1, 1, (2, 3)).astype(self.dtype)\n self.gy = cuda.cupy.random.uniform(-1, 1, (2, 3)).astype(self.dtype)\n with chainer.using_config('use_cudnn', self.use_cudnn):\n self.expect = chainer.should_use_cudnn('==always')\n\n def forward(self):\n x = chainer.Variable(self.x)\n return functions.relu(x)\n\n def test_call_cudnn_forward(self):\n default_func = cuda.cupy.cudnn.activation_forward\n with chainer.using_config('use_cudnn', self.use_cudnn):\n with mock.patch('cupy.cudnn.activation_forward') as func:\n func.side_effect = default_func\n self.forward()\n self.assertEqual(func.called, self.expect)\n\n def test_call_cudnn_backward(self):\n with chainer.using_config('use_cudnn', self.use_cudnn):\n y = self.forward()\n y.grad = self.gy\n default_func = cuda.cupy.cudnn.activation_backward\n with mock.patch('cupy.cudnn.activation_backward') as func:\n func.side_effect = default_func\n y.backward()\n self.assertEqual(func.called, self.expect)\n\n\ntesting.run_module(__name__, __file__)\n",
"import unittest\n\nimport numpy\nfrom six import moves\n\nfrom chainer import cuda\nfrom chainer import testing\nfrom chainer.testing import attr\nfrom chainer.utils import conv\n\n\nclass TestConv(unittest.TestCase):\n\n def check_conv_outsize(self, size, k, s, p, d):\n # When cover_all == False, `outsize` is the maximum integer that\n # satisfies \"(outsize - 1) * s + k <= w\"\n w = size + p * 2\n dk = k + (k - 1) * (d - 1)\n outsize = conv.get_conv_outsize(size, k, s, p, cover_all=False, d=d)\n self.assertTrue((outsize - 1) * s + dk <= w < outsize * s + dk)\n\n def check_conv_outsize_cover_all(self, size, k, s, p, d):\n # When cover_all == True, `outsize` is the minimum integer that\n # satisfies \"w <= (outsize - 1) * s + k\"\n w = size + p * 2\n dk = k + (k - 1) * (d - 1)\n outsize = conv.get_conv_outsize(size, k, s, p, cover_all=True, d=d)\n self.assertTrue((outsize - 2) * s + dk < w <= (outsize - 1) * s + dk)\n\n def test_conv_outsize1(self):\n self.check_conv_outsize(10, 4, 3, 2, 1)\n\n def test_conv_outsize2(self):\n self.check_conv_outsize(10, 4, 4, 2, 1)\n\n def test_conv_outsize3(self):\n self.check_conv_outsize(10, 4, 3, 2, 2)\n\n def test_conv_outsize_cover_all1(self):\n self.check_conv_outsize_cover_all(10, 4, 3, 2, 1)\n\n def test_conv_outsize_cover_all2(self):\n self.check_conv_outsize_cover_all(10, 4, 4, 2, 1)\n\n def test_conv_outsize_cover_all3(self):\n self.check_conv_outsize_cover_all(10, 4, 3, 2, 2)\n\n\[email protected](*testing.product({\n 'params': [\n (1, 1, 1, 1, 1, 1, 1, 1),\n (2, 2, 2, 2, 2, 2, 2, 2),\n (1, 2, 2, 1, 1, 2, 1, 1),\n (1, 2, 3, 4, 1, 2, 1, 1),\n (1, 2, 3, 4, 4, 5, 2, 3),\n (3, 3, 2, 2, 1, 1, 1, 1),\n ],\n}))\nclass TestIm2Col(unittest.TestCase):\n\n def setUp(self):\n self.dtype = numpy.float32\n self.w = 10\n self.h = 8\n shape = (2, 3, self.h, self.w)\n self.img = numpy.random.uniform(-1, 1, shape).astype(self.dtype)\n\n def check_im2col(self, kh, kw, sy, sx, ph, pw, dy, dx, gpu):\n if gpu:\n im2col = conv.im2col_gpu\n img = cuda.to_gpu(self.img)\n else:\n im2col = conv.im2col_cpu\n img = self.img\n\n col = im2col(img, kh, kw, sy, sx, ph, pw, dy=dy, dx=dx)\n col_h = conv.get_conv_outsize(self.h, kh, sy, ph, d=dy)\n col_w = conv.get_conv_outsize(self.w, kw, sx, pw, d=dx)\n self.assertEqual(col.shape, (2, 3, kh, kw, col_h, col_w))\n\n col = cuda.to_cpu(col)\n\n for y in moves.range(col_h):\n for x in moves.range(col_w):\n for ky in moves.range(kh):\n for kx in moves.range(kw):\n oy = y * sy - ph + ky * dy\n ox = x * sx - pw + kx * dx\n if 0 <= oy < self.h and 0 <= ox < self.w:\n testing.assert_allclose(\n col[:, :, ky, kx, y, x],\n self.img[:, :, oy, ox])\n else:\n testing.assert_allclose(\n col[:, :, ky, kx, y, x],\n numpy.zeros((2, 3), self.dtype))\n\n def test_im2col_cpu(self):\n self.check_im2col(*self.params, gpu=False)\n\n @attr.gpu\n def test_im2col_gpu(self):\n self.check_im2col(*self.params, gpu=True)\n\n\[email protected](*testing.product({\n 'params': [\n (1, 1, 1, 1, 1, 1, 1, 1),\n (2, 2, 2, 2, 2, 2, 2, 2),\n (1, 2, 2, 1, 1, 2, 1, 1),\n (1, 2, 3, 4, 1, 2, 1, 1),\n (1, 2, 3, 4, 4, 5, 2, 3),\n (3, 3, 2, 2, 1, 1, 1, 1),\n ],\n}))\nclass TestCol2Im(unittest.TestCase):\n\n def setUp(self):\n self.dtype = numpy.float32\n self.w = 10\n self.h = 8\n\n def check_col2im(self, kh, kw, sy, sx, ph, pw, dy, dx, gpu):\n col_h = conv.get_conv_outsize(self.h, kh, sy, ph, d=dy)\n col_w = conv.get_conv_outsize(self.w, kw, sx, pw, d=dx)\n shape = (2, 3, kh, kw, col_h, col_w)\n col = numpy.random.uniform(-1, 1, shape).astype(self.dtype)\n\n if gpu:\n col2im = conv.col2im_gpu\n col_data = cuda.to_gpu(col)\n else:\n col2im = conv.col2im_cpu\n col_data = col\n\n img = col2im(col_data, sy, sx, ph, pw, self.h, self.w, dy=dy, dx=dx)\n img = cuda.to_cpu(img)\n self.assertEqual(img.shape, (2, 3, self.h, self.w))\n for y in moves.range(self.h):\n for x in moves.range(self.w):\n v = numpy.zeros((2, 3), self.dtype)\n for ky in moves.range(kh):\n for kx in moves.range(kw):\n oy = (y + ph - ky * dy) // sy\n ox = (x + pw - kx * dx) // sx\n if ((y + ph - ky * dy) % sy == 0 and\n (x + pw - kx * dx) % sx == 0 and\n 0 <= oy < col_h and 0 <= ox < col_w):\n v += col[:, :, ky, kx, oy, ox]\n testing.assert_allclose(img[:, :, y, x], v)\n\n def test_col2im_cpu(self):\n self.check_col2im(*self.params, gpu=False)\n\n @attr.gpu\n def test_col2im_gpu(self):\n self.check_col2im(*self.params, gpu=True)\n\n\ntesting.run_module(__name__, __file__)\n",
"#!/usr/bin/env python\n\"\"\"Example code of DQN and DoubleDQN on OpenAI Gym environments.\n\nFor DQN, see: http://www.nature.com/articles/nature14236\nFor DoubleDQN, see: https://arxiv.org/abs/1509.06461\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import division\nimport argparse\nimport collections\nimport copy\nimport random\n\nimport gym\nimport numpy as np\n\nimport chainer\nfrom chainer import functions as F\nfrom chainer import links as L\nfrom chainer import optimizers\n\n\nclass QFunction(chainer.Chain):\n \"\"\"Q-function represented by a MLP.\"\"\"\n\n def __init__(self, obs_size, n_actions, n_units=100):\n super(QFunction, self).__init__()\n with self.init_scope():\n self.l0 = L.Linear(obs_size, n_units)\n self.l1 = L.Linear(n_units, n_units)\n self.l2 = L.Linear(n_units, n_actions)\n\n def __call__(self, x):\n \"\"\"Compute Q-values of actions for given observations.\"\"\"\n h = F.relu(self.l0(x))\n h = F.relu(self.l1(h))\n return self.l2(h)\n\n\ndef get_greedy_action(Q, obs):\n \"\"\"Get a greedy action wrt a given Q-function.\"\"\"\n obs = Q.xp.asarray(obs[None], dtype=np.float32)\n with chainer.no_backprop_mode():\n q = Q(obs).data[0]\n return int(q.argmax())\n\n\ndef mean_clipped_loss(y, t):\n return F.mean(F.huber_loss(y, t, delta=1.0, reduce='no'))\n\n\ndef update(Q, target_Q, opt, samples, gamma=0.99, target_type='double_dqn'):\n \"\"\"Update a Q-function with given samples and a target Q-function.\"\"\"\n xp = Q.xp\n obs = xp.asarray([sample[0] for sample in samples], dtype=np.float32)\n action = xp.asarray([sample[1] for sample in samples], dtype=np.int32)\n reward = xp.asarray([sample[2] for sample in samples], dtype=np.float32)\n done = xp.asarray([sample[3] for sample in samples], dtype=np.float32)\n obs_next = xp.asarray([sample[4] for sample in samples], dtype=np.float32)\n # Predicted values: Q(s,a)\n y = F.select_item(Q(obs), action)\n # Target values: r + gamma * max_b Q(s',b)\n with chainer.no_backprop_mode():\n if target_type == 'dqn':\n next_q = F.max(target_Q(obs_next), axis=1)\n elif target_type == 'double_dqn':\n next_q = F.select_item(target_Q(obs_next),\n F.argmax(Q(obs_next), axis=1))\n else:\n raise ValueError('Unsupported target_type: {}'.format(target_type))\n target = reward + gamma * (1 - done) * next_q\n loss = mean_clipped_loss(y, target)\n Q.cleargrads()\n loss.backward()\n opt.update()\n\n\ndef main():\n\n parser = argparse.ArgumentParser(description='Chainer example: DQN')\n parser.add_argument('--env', type=str, default='CartPole-v0',\n help='Name of the OpenAI Gym environment')\n parser.add_argument('--batch-size', '-b', type=int, default=64,\n help='Number of transitions in each mini-batch')\n parser.add_argument('--episodes', '-e', type=int, default=1000,\n help='Number of episodes to run')\n parser.add_argument('--gpu', '-g', type=int, default=-1,\n help='GPU ID (negative value indicates CPU)')\n parser.add_argument('--out', '-o', default='dqn_result',\n help='Directory to output the result')\n parser.add_argument('--unit', '-u', type=int, default=100,\n help='Number of units')\n parser.add_argument('--target-type', type=str, default='dqn',\n help='Target type', choices=['dqn', 'double_dqn'])\n parser.add_argument('--reward-scale', type=float, default=1e-2,\n help='Reward scale factor')\n parser.add_argument('--replay-start-size', type=int, default=500,\n help=('Number of iterations after which replay is '\n 'started'))\n parser.add_argument('--iterations-to-decay-epsilon', type=int,\n default=5000,\n help='Number of steps used to linearly decay epsilon')\n parser.add_argument('--min-epsilon', type=float, default=0.01,\n help='Minimum value of epsilon')\n parser.add_argument('--target-update-freq', type=int, default=100,\n help='Frequency of target network update')\n parser.add_argument('--record', action='store_true', default=True,\n help='Record performance')\n parser.add_argument('--no-record', action='store_false', dest='record')\n args = parser.parse_args()\n\n # Initialize an environment\n env = gym.make(args.env)\n assert isinstance(env.observation_space, gym.spaces.Box)\n assert isinstance(env.action_space, gym.spaces.Discrete)\n obs_size = env.observation_space.low.size\n n_actions = env.action_space.n\n if args.record:\n env = gym.wrappers.Monitor(env, args.out, force=True)\n reward_threshold = env.spec.reward_threshold\n if reward_threshold is not None:\n print('{} defines \"solving\" as getting average reward of {} over 100 '\n 'consecutive trials.'.format(args.env, reward_threshold))\n else:\n print('{} is an unsolved environment, which means it does not have a '\n 'specified reward threshold at which it\\'s considered '\n 'solved.'.format(args.env))\n\n # Initialize variables\n D = collections.deque(maxlen=10 ** 6) # Replay buffer\n Rs = collections.deque(maxlen=100) # History of returns\n iteration = 0\n\n # Initialize a model and its optimizer\n Q = QFunction(obs_size, n_actions, n_units=args.unit)\n if args.gpu >= 0:\n chainer.cuda.get_device_from_id(args.gpu).use()\n Q.to_gpu(args.gpu)\n target_Q = copy.deepcopy(Q)\n opt = optimizers.Adam(eps=1e-2)\n opt.setup(Q)\n\n for episode in range(args.episodes):\n\n obs = env.reset()\n done = False\n R = 0.0 # Return (sum of rewards obtained in an episode)\n timestep = 0\n\n while not done and timestep < env.spec.timestep_limit:\n\n # Epsilon is linearly decayed\n epsilon = 1.0 if len(D) < args.replay_start_size else \\\n max(args.min_epsilon,\n np.interp(\n iteration,\n [0, args.iterations_to_decay_epsilon],\n [1.0, args.min_epsilon]))\n\n # Select an action epsilon-greedily\n if np.random.rand() < epsilon:\n action = env.action_space.sample()\n else:\n action = get_greedy_action(Q, obs)\n\n # Execute an action\n new_obs, reward, done, _ = env.step(action)\n R += reward\n\n # Store a transition\n D.append((obs, action, reward * args.reward_scale, done, new_obs))\n obs = new_obs\n\n # Sample a random minibatch of transitions and replay\n if len(D) >= args.replay_start_size:\n sample_indices = random.sample(range(len(D)), args.batch_size)\n samples = [D[i] for i in sample_indices]\n update(Q, target_Q, opt, samples, target_type=args.target_type)\n\n # Update the target network\n if iteration % args.target_update_freq == 0:\n target_Q = copy.deepcopy(Q)\n\n iteration += 1\n timestep += 1\n\n Rs.append(R)\n average_R = np.mean(Rs)\n print('episode: {} iteration: {} R: {} average_R: {}'.format(\n episode, iteration, R, average_R))\n\n if reward_threshold is not None and average_R >= reward_threshold:\n print('Solved {} by getting average reward of '\n '{} >= {} over 100 consecutive episodes.'.format(\n args.env, average_R, reward_threshold))\n break\n\n\nif __name__ == '__main__':\n main()\n",
"import unittest\n\nimport numpy\n\nimport chainer\nfrom chainer import cuda\nfrom chainer import functions\nfrom chainer import gradient_check\nfrom chainer import testing\nfrom chainer.testing import attr\nfrom chainer.testing import condition\n\n\nclass TestScale(unittest.TestCase):\n\n def setUp(self):\n self.x1 = numpy.random.uniform(-1, 1, (3, 2, 3)).astype(numpy.float32)\n self.x2 = numpy.random.uniform(-1, 1, (2)).astype(numpy.float32)\n self.axis = 1\n self.y_expected = numpy.copy(self.x1)\n for i, j, k in numpy.ndindex(self.y_expected.shape):\n self.y_expected[i, j, k] *= self.x2[j]\n self.gy = numpy.random.uniform(-1, 1, (3, 2, 3)).astype(numpy.float32)\n\n def check_forward(self, x1_data, x2_data, axis, y_expected):\n x1 = chainer.Variable(x1_data)\n x2 = chainer.Variable(x2_data)\n y = functions.scale(x1, x2, axis)\n testing.assert_allclose(y_expected, y.data)\n\n def test_forward_cpu(self):\n self.check_forward(self.x1, self.x2, self.axis, self.y_expected)\n\n @attr.gpu\n def test_forward_gpu(self):\n x1 = cuda.to_gpu(self.x1)\n x2 = cuda.to_gpu(self.x2)\n self.check_forward(x1, x2, self.axis, self.y_expected)\n\n def check_backward(self, x1_data, x2_data, axis, y_grad):\n x = (x1_data, x2_data)\n gradient_check.check_backward(\n lambda x, y: functions.scale(x, y, axis),\n x, y_grad)\n\n @condition.retry(3)\n def test_backward_cpu(self):\n self.check_backward(self.x1, self.x2, self.axis, self.gy)\n\n @attr.gpu\n @condition.retry(3)\n def test_backward_gpu(self):\n x1 = cuda.to_gpu(self.x1)\n x2 = cuda.to_gpu(self.x2)\n gy = cuda.to_gpu(self.gy)\n self.check_backward(x1, x2, self.axis, gy)\n\n\nclass TestScaleInvalidShape(unittest.TestCase):\n\n def test_scale_invalid_shape(self):\n x1 = chainer.Variable(numpy.zeros((3, 2, 3), numpy.float32))\n x2 = chainer.Variable(numpy.zeros((2), numpy.float32))\n axis = 0\n with chainer.using_config('debug', True):\n with self.assertRaises(AssertionError):\n functions.scale(x1, x2, axis)\n\n\ntesting.run_module(__name__, __file__)\n",
"import unittest\n\nimport numpy\n\nimport chainer\nfrom chainer import cuda\nfrom chainer import functions\nfrom chainer import gradient_check\nfrom chainer import testing\nfrom chainer.testing import attr\n\n\[email protected](*testing.product({\n 'in_shape': [(3, 4, 2)],\n 'axis1': [0],\n 'axis2': [1],\n 'dtype': [numpy.float16, numpy.float32, numpy.float32],\n}))\nclass TestSwapaxes(unittest.TestCase):\n\n def setUp(self):\n self.x = numpy.random.uniform(\n 0.5, 1, self.in_shape).astype(self.dtype)\n self.g = numpy.random.uniform(\n 0.5, 1, self.in_shape).astype(self.dtype)\n self.g = self.g.swapaxes(self.axis1, self.axis2)\n self.gg = numpy.random.uniform(\n 0.5, 1, self.in_shape).astype(self.dtype)\n\n def check_forward(self, x_data):\n axis1, axis2 = self.axis1, self.axis2\n x = chainer.Variable(x_data)\n y = functions.swapaxes(x, axis1, axis2)\n self.assertEqual(y.data.dtype, self.dtype)\n self.assertTrue((self.x.swapaxes(axis1, axis2) ==\n cuda.to_cpu(y.data)).all())\n\n def test_forward_cpu(self):\n self.check_forward(self.x)\n\n @attr.gpu\n def test_forward_gpu(self):\n self.check_forward(cuda.to_gpu(self.x))\n\n def check_backward(self, x_data):\n x = chainer.Variable(x_data)\n y = functions.swapaxes(x, self.axis1, self.axis2)\n y.grad = y.data\n y.backward()\n testing.assert_allclose(x.data, x.grad, atol=0, rtol=0)\n\n def test_backward_cpu(self):\n self.check_backward(self.x)\n\n @attr.gpu\n def test_backward_gpu(self):\n self.check_backward(cuda.to_gpu(self.x))\n\n def check_double_backward(self, x_data, g_data, gg_data):\n def f(x):\n y = functions.swapaxes(x, self.axis1, self.axis2)\n return y * y\n\n gradient_check.check_double_backward(\n f, x_data, g_data, gg_data, dtype=numpy.float64)\n\n def test_double_backward_cpu(self):\n self.check_double_backward(self.x, self.g, self.gg)\n\n @attr.gpu\n def test_double_backward_gpu(self):\n self.check_double_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.g),\n cuda.to_gpu(self.gg))\n\n\ntesting.run_module(__name__, __file__)\n",
"#!/usr/bin/env python\n\"\"\"Example code of DDPG on OpenAI Gym environments.\n\nFor DDPG, see: https://arxiv.org/abs/1509.02971\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import division\nimport argparse\nimport collections\nimport copy\nimport random\n\nimport gym\nimport numpy as np\n\nimport chainer\nfrom chainer import functions as F\nfrom chainer import links as L\nfrom chainer import optimizers\n\n\nclass QFunction(chainer.Chain):\n \"\"\"Q-function represented by a MLP.\"\"\"\n\n def __init__(self, obs_size, action_size, n_units=100):\n super(QFunction, self).__init__()\n with self.init_scope():\n self.l0 = L.Linear(obs_size + action_size, n_units)\n self.l1 = L.Linear(n_units, n_units)\n self.l2 = L.Linear(n_units, 1,\n initialW=chainer.initializers.HeNormal(1e-3))\n\n def __call__(self, obs, action):\n \"\"\"Compute Q-values for given state-action pairs.\"\"\"\n x = F.concat((obs, action), axis=1)\n h = F.relu(self.l0(x))\n h = F.relu(self.l1(h))\n return self.l2(h)\n\n\ndef squash(x, low, high):\n \"\"\"Squash values to fit [low, high] via tanh.\"\"\"\n center = (high + low) / 2\n scale = (high - low) / 2\n return F.tanh(x) * scale + center\n\n\nclass Policy(chainer.Chain):\n \"\"\"Policy represented by a MLP.\"\"\"\n\n def __init__(self, obs_size, action_size, action_low, action_high,\n n_units=100):\n super(Policy, self).__init__()\n self.action_high = action_high\n self.action_low = action_low\n with self.init_scope():\n self.l0 = L.Linear(obs_size, n_units)\n self.l1 = L.Linear(n_units, n_units)\n self.l2 = L.Linear(n_units, action_size,\n initialW=chainer.initializers.HeNormal(1e-3))\n\n def __call__(self, x):\n \"\"\"Compute actions for given observations.\"\"\"\n h = F.relu(self.l0(x))\n h = F.relu(self.l1(h))\n return squash(self.l2(h),\n self.xp.asarray(self.action_low),\n self.xp.asarray(self.action_high))\n\n\ndef get_action(policy, obs):\n \"\"\"Get an action by evaluating a given policy.\"\"\"\n obs = policy.xp.asarray(obs[None], dtype=np.float32)\n with chainer.no_backprop_mode():\n action = policy(obs).data[0]\n return chainer.cuda.to_cpu(action)\n\n\ndef update(Q, target_Q, policy, target_policy, opt_Q, opt_policy,\n samples, gamma=0.99):\n \"\"\"Update a Q-function and a policy.\"\"\"\n xp = Q.xp\n obs = xp.asarray([sample[0] for sample in samples], dtype=np.float32)\n action = xp.asarray([sample[1] for sample in samples], dtype=np.float32)\n reward = xp.asarray([sample[2] for sample in samples], dtype=np.float32)\n done = xp.asarray([sample[3] for sample in samples], dtype=np.float32)\n obs_next = xp.asarray([sample[4] for sample in samples], dtype=np.float32)\n\n def update_Q():\n # Predicted values: Q(s,a)\n y = F.squeeze(Q(obs, action), axis=1)\n # Target values: r + gamma * Q(s,policy(s))\n with chainer.no_backprop_mode():\n next_q = F.squeeze(target_Q(obs_next, target_policy(obs_next)),\n axis=1)\n target = reward + gamma * (1 - done) * next_q\n loss = F.mean_squared_error(y, target)\n Q.cleargrads()\n loss.backward()\n opt_Q.update()\n\n def update_policy():\n # Maximize Q(s,policy(s))\n q = Q(obs, policy(obs))\n q = q[:] # Avoid https://github.com/chainer/chainer/issues/2744\n loss = - F.mean(q)\n policy.cleargrads()\n loss.backward()\n opt_policy.update()\n\n update_Q()\n update_policy()\n\n\ndef soft_copy_params(source, target, tau):\n \"\"\"Make the parameters of a link close to the ones of another link.\n\n Making tau close to 0 slows the pace of updates, and close to 1 might lead\n to faster, but more volatile updates.\n \"\"\"\n # Sort params by name\n source_params = [param for _, param in sorted(source.namedparams())]\n target_params = [param for _, param in sorted(target.namedparams())]\n for s, t in zip(source_params, target_params):\n t.data[:] += tau * (s.data - t.data)\n\n\ndef main():\n\n parser = argparse.ArgumentParser(description='Chainer example: DDPG')\n parser.add_argument('--env', type=str, default='Pendulum-v0',\n help='Name of the OpenAI Gym environment')\n parser.add_argument('--batch-size', '-b', type=int, default=64,\n help='Number of transitions in each mini-batch')\n parser.add_argument('--episodes', '-e', type=int, default=1000,\n help='Number of episodes to run')\n parser.add_argument('--gpu', '-g', type=int, default=-1,\n help='GPU ID (negative value indicates CPU)')\n parser.add_argument('--out', '-o', default='ddpg_result',\n help='Directory to output the result')\n parser.add_argument('--unit', '-u', type=int, default=100,\n help='Number of units')\n parser.add_argument('--reward-scale', type=float, default=1e-3,\n help='Reward scale factor')\n parser.add_argument('--replay-start-size', type=int, default=500,\n help=('Number of iterations after which replay is '\n 'started'))\n parser.add_argument('--tau', type=float, default=1e-2,\n help='Softness of soft target update (0, 1]')\n parser.add_argument('--noise-scale', type=float, default=0.4,\n help='Scale of additive Gaussian noises')\n parser.add_argument('--record', action='store_true', default=True,\n help='Record performance')\n parser.add_argument('--no-record', action='store_false', dest='record')\n args = parser.parse_args()\n\n # Initialize an environment\n env = gym.make(args.env)\n assert isinstance(env.observation_space, gym.spaces.Box)\n assert isinstance(env.action_space, gym.spaces.Box)\n obs_size = env.observation_space.low.size\n action_size = env.action_space.low.size\n if args.record:\n env = gym.wrappers.Monitor(env, args.out, force=True)\n reward_threshold = env.spec.reward_threshold\n if reward_threshold is not None:\n print('{} defines \"solving\" as getting average reward of {} over 100 '\n 'consecutive trials.'.format(args.env, reward_threshold))\n else:\n print('{} is an unsolved environment, which means it does not have a '\n 'specified reward threshold at which it\\'s considered '\n 'solved.'.format(args.env))\n\n # Initialize variables\n D = collections.deque(maxlen=10 ** 6) # Replay buffer\n Rs = collections.deque(maxlen=100) # History of returns\n iteration = 0\n\n # Initialize models and optimizers\n Q = QFunction(obs_size, action_size, n_units=args.unit)\n policy = Policy(obs_size, action_size,\n env.action_space.low, env.action_space.high,\n n_units=args.unit)\n if args.gpu >= 0:\n chainer.cuda.get_device_from_id(args.gpu).use()\n Q.to_gpu(args.gpu)\n policy.to_gpu(args.gpu)\n target_Q = copy.deepcopy(Q)\n target_policy = copy.deepcopy(policy)\n opt_Q = optimizers.Adam()\n opt_Q.setup(Q)\n opt_policy = optimizers.Adam(alpha=1e-4)\n opt_policy.setup(policy)\n\n for episode in range(args.episodes):\n\n obs = env.reset()\n done = False\n R = 0.0 # Return (sum of rewards obtained in an episode)\n timestep = 0\n\n while not done and timestep < env.spec.timestep_limit:\n\n # Select an action with additive noises for exploration\n action = (get_action(policy, obs) +\n np.random.normal(scale=args.noise_scale))\n\n # Execute an action\n new_obs, reward, done, _ = env.step(\n np.clip(action, env.action_space.low, env.action_space.high))\n R += reward\n\n # Store a transition\n D.append((obs, action, reward * args.reward_scale, done, new_obs))\n obs = new_obs\n\n # Sample a random minibatch of transitions and replay\n if len(D) >= args.replay_start_size:\n sample_indices = random.sample(range(len(D)), args.batch_size)\n samples = [D[i] for i in sample_indices]\n update(Q, target_Q, policy, target_policy,\n opt_Q, opt_policy, samples)\n\n # Soft update of the target networks\n soft_copy_params(Q, target_Q, args.tau)\n soft_copy_params(policy, target_policy, args.tau)\n\n iteration += 1\n timestep += 1\n\n Rs.append(R)\n average_R = np.mean(Rs)\n print('episode: {} iteration: {} R:{} average_R:{}'.format(\n episode, iteration, R, average_R))\n\n if reward_threshold is not None and average_R >= reward_threshold:\n print('Solved {} by getting average reward of '\n '{} >= {} over 100 consecutive episodes.'.format(\n args.env, average_R, reward_threshold))\n break\n\n\nif __name__ == '__main__':\n main()\n",
"import unittest\n\nimport numpy\n\nfrom chainer import cuda\nfrom chainer import functions\nfrom chainer import gradient_check\nfrom chainer import testing\nfrom chainer.testing import attr\nfrom chainer.utils import type_check\n\n\[email protected](*testing.product_dict(\n [\n {'axis': None, 'out_shape': (3,)},\n {'axis': 1, 'out_shape': (1, 3, 1)},\n {'axis': -3, 'out_shape': (1, 3, 1)},\n {'axis': (0, 1, 3), 'out_shape': (3,)},\n {'axis': (3, 1, 0), 'out_shape': (3,)},\n {'axis': (-4, -3, -1), 'out_shape': (3,)},\n {'axis': (-1, -3, -4), 'out_shape': (3,)},\n ],\n [\n {'dtype': numpy.float16},\n {'dtype': numpy.float32},\n {'dtype': numpy.float64},\n ],\n))\nclass TestSqueeze(unittest.TestCase):\n\n def setUp(self):\n self.x = numpy.random.uniform(-1, 1, (1, 1, 3, 1)).astype(self.dtype)\n self.g = numpy.random.uniform(-1, 1, self.out_shape).astype(self.dtype)\n\n self.check_forward_options = {}\n self.check_backward_options = {'dtype': numpy.float64}\n if self.dtype == numpy.float16:\n self.check_forward_options = {'atol': 5e-4, 'rtol': 5e-3}\n self.check_backward_options = {\n 'dtype': numpy.float64, 'atol': 2 ** -4, 'rtol': 2 ** -4}\n\n def check_forward(self, x_data):\n y = functions.squeeze(x_data, axis=self.axis)\n expected = numpy.squeeze(self.x, axis=self.axis)\n testing.assert_allclose(y.data, expected, **self.check_forward_options)\n\n def test_forward_cpu(self):\n self.check_forward(self.x)\n\n @attr.gpu\n def test_forward_gpu(self):\n self.check_forward(cuda.to_gpu(self.x))\n\n def check_backward(self, x_data, g_data):\n gradient_check.check_backward(\n lambda x: functions.squeeze(x, self.axis),\n x_data, g_data, **self.check_backward_options)\n\n def test_backward_cpu(self):\n self.check_backward(self.x, self.g)\n\n @attr.gpu\n def test_backward_gpu(self):\n self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.g))\n\n\[email protected](*testing.product(\n {'axis': [1, (1,)]},\n))\nclass TestSqueezeValueError(unittest.TestCase):\n\n def setUp(self):\n self.x = numpy.random.uniform(-1, 1, (1, 3, 1)).astype('f')\n\n def check_invalid_type(self, x_data):\n with self.assertRaises(ValueError):\n functions.squeeze(x_data, axis=self.axis)\n\n def test_invalid_type_cpu(self):\n self.check_invalid_type(self.x)\n\n @attr.gpu\n def test_type_error_gpu(self):\n self.check_invalid_type(cuda.to_gpu(self.x))\n\n\[email protected](*testing.product(\n {'axis': [3, -4, (3,), (-4,)]},\n))\nclass TestSqueezeInvalidType(unittest.TestCase):\n\n def setUp(self):\n self.x = numpy.random.uniform(-1, 1, (1, 3, 1)).astype('f')\n\n def check_invalid_type(self, x_data):\n with self.assertRaises(type_check.InvalidType):\n functions.squeeze(x_data, axis=self.axis)\n\n def test_invalid_type_cpu(self):\n self.check_invalid_type(self.x)\n\n @attr.gpu\n def test_type_error_gpu(self):\n self.check_invalid_type(cuda.to_gpu(self.x))\n\n\nclass TestSqueezeTypeError(unittest.TestCase):\n\n def test_invalid_axis(self):\n with self.assertRaises(TypeError):\n functions.Squeeze('a')\n\n\ntesting.run_module(__name__, __file__)\n",
"import unittest\n\nimport numpy\n\nfrom chainer import cuda\nfrom chainer.links.model.vision import googlenet\nfrom chainer.links.model.vision import resnet\nfrom chainer.links.model.vision import vgg\nfrom chainer import testing\nfrom chainer.testing import attr\nfrom chainer.variable import Variable\n\n\[email protected](*testing.product({\n 'n_layers': [50, 101, 152],\n}))\[email protected](resnet.available, 'Pillow is required')\[email protected]\nclass TestResNetLayers(unittest.TestCase):\n\n def setUp(self):\n if self.n_layers == 50:\n self.link = resnet.ResNet50Layers(pretrained_model=None)\n elif self.n_layers == 101:\n self.link = resnet.ResNet101Layers(pretrained_model=None)\n elif self.n_layers == 152:\n self.link = resnet.ResNet152Layers(pretrained_model=None)\n\n def test_available_layers(self):\n result = self.link.available_layers\n self.assertIsInstance(result, list)\n self.assertEqual(len(result), 9)\n\n def check_call(self):\n xp = self.link.xp\n\n # Suppress warning that arises from zero division in BatchNormalization\n with numpy.errstate(divide='ignore'):\n x1 = Variable(xp.asarray(numpy.random.uniform(\n -1, 1, (1, 3, 224, 224)).astype(numpy.float32)))\n y1 = cuda.to_cpu(self.link(x1)['prob'].data)\n self.assertEqual(y1.shape, (1, 1000))\n\n x2 = Variable(xp.asarray(numpy.random.uniform(\n -1, 1, (1, 3, 128, 128)).astype(numpy.float32)))\n y2 = cuda.to_cpu(self.link(x2, layers=['pool5'])['pool5'].data)\n self.assertEqual(y2.shape, (1, 2048))\n\n def test_call_cpu(self):\n self.check_call()\n\n @attr.gpu\n def test_call_gpu(self):\n self.link.to_gpu()\n self.check_call()\n\n def test_prepare(self):\n x1 = numpy.random.uniform(0, 255, (320, 240, 3)).astype(numpy.uint8)\n x2 = numpy.random.uniform(0, 255, (320, 240)).astype(numpy.uint8)\n x3 = numpy.random.uniform(0, 255, (160, 120, 3)).astype(numpy.float32)\n x4 = numpy.random.uniform(0, 255, (1, 160, 120)).astype(numpy.float32)\n x5 = numpy.random.uniform(0, 255, (3, 160, 120)).astype(numpy.uint8)\n\n y1 = resnet.prepare(x1)\n self.assertEqual(y1.shape, (3, 224, 224))\n self.assertEqual(y1.dtype, numpy.float32)\n y2 = resnet.prepare(x2)\n self.assertEqual(y2.shape, (3, 224, 224))\n self.assertEqual(y2.dtype, numpy.float32)\n y3 = resnet.prepare(x3, size=None)\n self.assertEqual(y3.shape, (3, 160, 120))\n self.assertEqual(y3.dtype, numpy.float32)\n y4 = resnet.prepare(x4)\n self.assertEqual(y4.shape, (3, 224, 224))\n self.assertEqual(y4.dtype, numpy.float32)\n y5 = resnet.prepare(x5, size=None)\n self.assertEqual(y5.shape, (3, 160, 120))\n self.assertEqual(y5.dtype, numpy.float32)\n\n def check_extract(self):\n x1 = numpy.random.uniform(0, 255, (320, 240, 3)).astype(numpy.uint8)\n x2 = numpy.random.uniform(0, 255, (320, 240)).astype(numpy.uint8)\n\n with numpy.errstate(divide='ignore'):\n result = self.link.extract([x1, x2], layers=['res3', 'pool5'])\n self.assertEqual(len(result), 2)\n y1 = cuda.to_cpu(result['res3'].data)\n self.assertEqual(y1.shape, (2, 512, 28, 28))\n self.assertEqual(y1.dtype, numpy.float32)\n y2 = cuda.to_cpu(result['pool5'].data)\n self.assertEqual(y2.shape, (2, 2048))\n self.assertEqual(y2.dtype, numpy.float32)\n\n x3 = numpy.random.uniform(0, 255, (80, 60)).astype(numpy.uint8)\n result = self.link.extract([x3], layers=['res2'], size=None)\n self.assertEqual(len(result), 1)\n y3 = cuda.to_cpu(result['res2'].data)\n self.assertEqual(y3.shape, (1, 256, 20, 15))\n self.assertEqual(y3.dtype, numpy.float32)\n\n def test_extract_cpu(self):\n self.check_extract()\n\n @attr.gpu\n def test_extract_gpu(self):\n self.link.to_gpu()\n self.check_extract()\n\n def check_predict(self):\n x1 = numpy.random.uniform(0, 255, (320, 240, 3)).astype(numpy.uint8)\n x2 = numpy.random.uniform(0, 255, (320, 240)).astype(numpy.uint8)\n\n with numpy.errstate(divide='ignore'):\n result = self.link.predict([x1, x2], oversample=False)\n y = cuda.to_cpu(result.data)\n self.assertEqual(y.shape, (2, 1000))\n self.assertEqual(y.dtype, numpy.float32)\n result = self.link.predict([x1, x2], oversample=True)\n y = cuda.to_cpu(result.data)\n self.assertEqual(y.shape, (2, 1000))\n self.assertEqual(y.dtype, numpy.float32)\n\n def test_predict_cpu(self):\n self.check_predict()\n\n @attr.gpu\n def test_predict_gpu(self):\n self.link.to_gpu()\n self.check_predict()\n\n def check_copy(self):\n copied = self.link.copy()\n\n self.assertIs(copied.conv1, copied.functions['conv1'][0])\n self.assertIs(copied.res2.a, copied.res2.forward[0])\n\n def test_copy_cpu(self):\n self.check_copy()\n\n @attr.gpu\n def test_copy_gpu(self):\n self.link.to_gpu()\n self.check_copy()\n\n\[email protected](resnet.available, 'Pillow is required')\[email protected]\nclass TestVGG16Layers(unittest.TestCase):\n\n def setUp(self):\n self.link = vgg.VGG16Layers(pretrained_model=None)\n\n def test_available_layers(self):\n result = self.link.available_layers\n self.assertIsInstance(result, list)\n self.assertEqual(len(result), 22)\n\n def check_call(self):\n xp = self.link.xp\n\n x1 = Variable(xp.asarray(numpy.random.uniform(\n -1, 1, (1, 3, 224, 224)).astype(numpy.float32)))\n y1 = cuda.to_cpu(self.link(x1)['prob'].data)\n self.assertEqual(y1.shape, (1, 1000))\n\n def test_call_cpu(self):\n self.check_call()\n\n @attr.gpu\n def test_call_gpu(self):\n self.link.to_gpu()\n self.check_call()\n\n def test_prepare(self):\n x1 = numpy.random.uniform(0, 255, (320, 240, 3)).astype(numpy.uint8)\n x2 = numpy.random.uniform(0, 255, (320, 240)).astype(numpy.uint8)\n x3 = numpy.random.uniform(0, 255, (160, 120, 3)).astype(numpy.float32)\n x4 = numpy.random.uniform(0, 255, (1, 160, 120)).astype(numpy.float32)\n x5 = numpy.random.uniform(0, 255, (3, 160, 120)).astype(numpy.uint8)\n\n y1 = vgg.prepare(x1)\n self.assertEqual(y1.shape, (3, 224, 224))\n self.assertEqual(y1.dtype, numpy.float32)\n y2 = vgg.prepare(x2)\n self.assertEqual(y2.shape, (3, 224, 224))\n self.assertEqual(y2.dtype, numpy.float32)\n y3 = vgg.prepare(x3, size=None)\n self.assertEqual(y3.shape, (3, 160, 120))\n self.assertEqual(y3.dtype, numpy.float32)\n y4 = vgg.prepare(x4)\n self.assertEqual(y4.shape, (3, 224, 224))\n self.assertEqual(y4.dtype, numpy.float32)\n y5 = vgg.prepare(x5, size=None)\n self.assertEqual(y5.shape, (3, 160, 120))\n self.assertEqual(y5.dtype, numpy.float32)\n\n def check_extract(self):\n x1 = numpy.random.uniform(0, 255, (320, 240, 3)).astype(numpy.uint8)\n x2 = numpy.random.uniform(0, 255, (320, 240)).astype(numpy.uint8)\n result = self.link.extract([x1, x2], layers=['pool3', 'fc7'])\n self.assertEqual(len(result), 2)\n y1 = cuda.to_cpu(result['pool3'].data)\n self.assertEqual(y1.shape, (2, 256, 28, 28))\n self.assertEqual(y1.dtype, numpy.float32)\n y2 = cuda.to_cpu(result['fc7'].data)\n self.assertEqual(y2.shape, (2, 4096))\n self.assertEqual(y2.dtype, numpy.float32)\n\n x3 = numpy.random.uniform(0, 255, (80, 60)).astype(numpy.uint8)\n result = self.link.extract([x3], layers=['pool1'], size=None)\n self.assertEqual(len(result), 1)\n y3 = cuda.to_cpu(result['pool1'].data)\n self.assertEqual(y3.shape, (1, 64, 40, 30))\n self.assertEqual(y3.dtype, numpy.float32)\n\n def test_extract_cpu(self):\n self.check_extract()\n\n @attr.gpu\n def test_extract_gpu(self):\n self.link.to_gpu()\n self.check_extract()\n\n def check_predict(self):\n x1 = numpy.random.uniform(0, 255, (320, 240, 3)).astype(numpy.uint8)\n x2 = numpy.random.uniform(0, 255, (320, 240)).astype(numpy.uint8)\n result = self.link.predict([x1, x2], oversample=False)\n y = cuda.to_cpu(result.data)\n self.assertEqual(y.shape, (2, 1000))\n self.assertEqual(y.dtype, numpy.float32)\n result = self.link.predict([x1, x2], oversample=True)\n y = cuda.to_cpu(result.data)\n self.assertEqual(y.shape, (2, 1000))\n self.assertEqual(y.dtype, numpy.float32)\n\n def test_predict_cpu(self):\n self.check_predict()\n\n @attr.gpu\n def test_predict_gpu(self):\n self.link.to_gpu()\n self.check_predict()\n\n def check_copy(self):\n copied = self.link.copy()\n\n self.assertIs(copied.conv1_1, copied.functions['conv1_1'][0])\n\n def test_copy_cpu(self):\n self.check_copy()\n\n @attr.gpu\n def test_copy_gpu(self):\n self.link.to_gpu()\n self.check_copy()\n\n\[email protected](googlenet.available, 'Pillow is required')\[email protected]\nclass TestGoogLeNet(unittest.TestCase):\n\n def setUp(self):\n self.link = googlenet.GoogLeNet(pretrained_model=None)\n\n def test_available_layers(self):\n result = self.link.available_layers\n self.assertIsInstance(result, list)\n self.assertEqual(len(result), 21)\n\n def check_call_prob(self):\n xp = self.link.xp\n\n x = Variable(xp.asarray(numpy.random.uniform(\n -1, 1, (1, 3, 224, 224)).astype(numpy.float32)))\n y = cuda.to_cpu(self.link(x)['prob'].data)\n self.assertEqual(y.shape, (1, 1000))\n\n def check_call_loss1_fc2(self):\n xp = self.link.xp\n\n x = Variable(xp.asarray(numpy.random.uniform(\n -1, 1, (1, 3, 224, 224)).astype(numpy.float32)))\n y = cuda.to_cpu(self.link(x, ['loss1_fc2'])['loss1_fc2'].data)\n self.assertEqual(y.shape, (1, 1000))\n\n def check_call_loss2_fc2(self):\n xp = self.link.xp\n\n x = Variable(xp.asarray(numpy.random.uniform(\n -1, 1, (1, 3, 224, 224)).astype(numpy.float32)))\n y = cuda.to_cpu(self.link(x, ['loss2_fc2'])['loss2_fc2'].data)\n self.assertEqual(y.shape, (1, 1000))\n\n def test_call_cpu(self):\n self.check_call_prob()\n self.check_call_loss1_fc2()\n self.check_call_loss2_fc2()\n\n @attr.gpu\n def test_call_gpu(self):\n self.link.to_gpu()\n self.check_call_prob()\n self.check_call_loss1_fc2()\n self.check_call_loss2_fc2()\n\n def test_prepare(self):\n x1 = numpy.random.uniform(0, 255, (320, 240, 3)).astype(numpy.uint8)\n x2 = numpy.random.uniform(0, 255, (320, 240)).astype(numpy.uint8)\n x3 = numpy.random.uniform(0, 255, (160, 120, 3)).astype(numpy.float32)\n x4 = numpy.random.uniform(0, 255, (1, 160, 120)).astype(numpy.float32)\n x5 = numpy.random.uniform(0, 255, (3, 160, 120)).astype(numpy.uint8)\n\n y1 = googlenet.prepare(x1)\n self.assertEqual(y1.shape, (3, 224, 224))\n self.assertEqual(y1.dtype, numpy.float32)\n y2 = googlenet.prepare(x2)\n self.assertEqual(y2.shape, (3, 224, 224))\n self.assertEqual(y2.dtype, numpy.float32)\n y3 = googlenet.prepare(x3, size=None)\n self.assertEqual(y3.shape, (3, 160, 120))\n self.assertEqual(y3.dtype, numpy.float32)\n y4 = googlenet.prepare(x4)\n self.assertEqual(y4.shape, (3, 224, 224))\n self.assertEqual(y4.dtype, numpy.float32)\n y5 = googlenet.prepare(x5, size=None)\n self.assertEqual(y5.shape, (3, 160, 120))\n self.assertEqual(y5.dtype, numpy.float32)\n\n def check_extract(self):\n x1 = numpy.random.uniform(0, 255, (320, 240, 3)).astype(numpy.uint8)\n x2 = numpy.random.uniform(0, 255, (320, 240)).astype(numpy.uint8)\n\n result = self.link.extract([x1, x2], layers=['pool5', 'loss3_fc'])\n self.assertEqual(len(result), 2)\n y1 = cuda.to_cpu(result['pool5'].data)\n self.assertEqual(y1.shape, (2, 1024, 1, 1))\n self.assertEqual(y1.dtype, numpy.float32)\n y2 = cuda.to_cpu(result['loss3_fc'].data)\n self.assertEqual(y2.shape, (2, 1000))\n self.assertEqual(y2.dtype, numpy.float32)\n\n x3 = numpy.random.uniform(0, 255, (80, 60)).astype(numpy.uint8)\n result = self.link.extract([x3], layers=['pool1'], size=None)\n self.assertEqual(len(result), 1)\n y3 = cuda.to_cpu(result['pool1'].data)\n self.assertEqual(y3.shape, (1, 64, 20, 15))\n self.assertEqual(y3.dtype, numpy.float32)\n\n def test_extract_cpu(self):\n self.check_extract()\n\n @attr.gpu\n def test_extract_gpu(self):\n self.link.to_gpu()\n self.check_extract()\n\n def check_predict(self):\n x1 = numpy.random.uniform(0, 255, (320, 240, 3)).astype(numpy.uint8)\n x2 = numpy.random.uniform(0, 255, (320, 240)).astype(numpy.uint8)\n\n result = self.link.predict([x1, x2], oversample=False)\n y = cuda.to_cpu(result.data)\n self.assertEqual(y.shape, (2, 1000))\n self.assertEqual(y.dtype, numpy.float32)\n result = self.link.predict([x1, x2], oversample=True)\n y = cuda.to_cpu(result.data)\n self.assertEqual(y.shape, (2, 1000))\n self.assertEqual(y.dtype, numpy.float32)\n\n def test_predict_cpu(self):\n self.check_predict()\n\n @attr.gpu\n def test_predict_gpu(self):\n self.link.to_gpu()\n self.check_predict()\n\n def check_copy(self):\n copied = self.link.copy()\n\n self.assertIs(copied.conv1, copied.functions['conv1'][0])\n\n def test_copy_cpu(self):\n self.check_copy()\n\n @attr.gpu\n def test_copy_gpu(self):\n self.link.to_gpu()\n self.check_copy()\n\n\ntesting.run_module(__name__, __file__)\n",
"import unittest\n\nimport numpy\n\nimport chainer\nfrom chainer import cuda\nfrom chainer import gradient_check\nfrom chainer import links\nfrom chainer import testing\nfrom chainer.testing import attr\nfrom chainer.testing import condition\n\n\ndef relu(x):\n return x * (x > 0)\n\n\[email protected](*testing.product({\n 'hidden_none': [True, False],\n 'activation': ['tanh', 'relu'],\n}))\nclass TestNStepRNN(unittest.TestCase):\n\n lengths = [3, 1, 2]\n n_layer = 2\n in_size = 3\n out_size = 2\n dropout = 0.0\n\n def setUp(self):\n shape = (self.n_layer, len(self.lengths), self.out_size)\n if self.hidden_none:\n self.h = numpy.zeros(shape, 'f')\n else:\n self.h = numpy.random.uniform(-1, 1, shape).astype('f')\n self.xs = [\n numpy.random.uniform(-1, 1, (l, self.in_size)).astype('f')\n for l in self.lengths]\n\n self.gh = numpy.random.uniform(-1, 1, shape).astype('f')\n self.gys = [\n numpy.random.uniform(-1, 1, (l, self.out_size)).astype('f')\n for l in self.lengths]\n if self.activation == 'tanh':\n rnn_link_class = links.NStepRNNTanh\n elif self.activation == 'relu':\n rnn_link_class = links.NStepRNNReLU\n self.rnn = rnn_link_class(\n self.n_layer, self.in_size, self.out_size, self.dropout)\n\n for layer in self.rnn:\n for p in layer.params():\n p.data[...] = numpy.random.uniform(-1, 1, p.data.shape)\n self.rnn.cleargrads()\n\n def check_forward(self, h_data, xs_data):\n if self.hidden_none:\n h = None\n else:\n h = chainer.Variable(h_data)\n xs = [chainer.Variable(x) for x in xs_data]\n hy, ys = self.rnn(h, xs)\n\n self.assertEqual(hy.data.shape, h_data.shape)\n self.assertEqual(len(xs), len(ys))\n for x, y in zip(xs, ys):\n self.assertEqual(len(x.data), len(y.data))\n self.assertEqual(y.data.shape[1], self.out_size)\n\n self.rnn.to_cpu()\n\n for batch, seq in enumerate(self.xs):\n for layer in range(self.n_layer):\n p = self.rnn[layer]\n h_prev = self.h[layer, batch]\n hs = []\n for x in seq:\n if self.activation == 'tanh':\n activation_func = numpy.tanh\n elif self.activation == 'relu':\n activation_func = relu\n\n h_prev = activation_func(x.dot(p.w0.data.T) +\n h_prev.dot(p.w1.data.T) +\n p.b0.data + p.b1.data)\n\n hs.append(h_prev)\n\n seq = hs\n testing.assert_allclose(hy.data[layer, batch], h_prev)\n\n for y, ey in zip(ys[batch].data, seq):\n testing.assert_allclose(y, ey)\n\n def test_forward_cpu_train(self):\n with chainer.using_config('train', True):\n self.check_forward(self.h, self.xs)\n\n @attr.gpu\n def test_forward_gpu_train(self):\n self.rnn.to_gpu()\n with chainer.using_config('use_cudnn', 'always'), \\\n chainer.using_config('train', True):\n self.check_forward(\n cuda.to_gpu(self.h),\n [cuda.to_gpu(x) for x in self.xs])\n\n def test_forward_cpu_test(self):\n with chainer.using_config('train', False):\n self.check_forward(self.h, self.xs)\n\n @attr.gpu\n def test_forward_gpu_test(self):\n self.rnn.to_gpu()\n with chainer.using_config('use_cudnn', 'always'), \\\n chainer.using_config('train', False):\n self.check_forward(\n cuda.to_gpu(self.h),\n [cuda.to_gpu(x) for x in self.xs])\n\n def check_backward(\n self, h_data, xs_data, gh_data, gys_data):\n\n def fun(*args):\n if self.hidden_none:\n h = None\n xs = args\n else:\n h, = args[:1]\n xs = args[1:]\n hy, ys = self.rnn(h, xs)\n return tuple([hy, ] + list(ys))\n\n params = []\n for layer in self.rnn:\n for p in layer.params():\n params.append(p)\n\n if self.hidden_none:\n in_data = xs_data\n else:\n in_data = [h_data, ] + xs_data\n gradient_check.check_backward(\n fun, tuple(in_data),\n tuple([gh_data, ] + gys_data),\n tuple(params), rtol=1e-2, atol=5e-2)\n\n @condition.retry(3)\n def test_backward_cpu(self):\n self.check_backward(\n self.h, self.xs, self.gh, self.gys)\n\n @attr.gpu\n @condition.retry(3)\n def test_backward_gpu(self):\n self.rnn.to_gpu()\n with chainer.using_config('use_cudnn', 'auto'):\n self.check_backward(\n cuda.to_gpu(self.h),\n [cuda.to_gpu(x) for x in self.xs],\n cuda.to_gpu(self.gh),\n [cuda.to_gpu(gy) for gy in self.gys])\n\n\[email protected](*testing.product({\n 'hidden_none': [True, False],\n 'activation': ['tanh', 'relu'],\n}))\nclass TestNStepBiRNN(unittest.TestCase):\n\n lengths = [3, 1, 2]\n n_layer = 2\n in_size = 3\n out_size = 2\n dropout = 0.0\n\n def setUp(self):\n shape = (self.n_layer * 2, len(self.lengths), self.out_size)\n if self.hidden_none:\n self.h = numpy.zeros(shape, 'f')\n else:\n self.h = numpy.random.uniform(-1, 1, shape).astype('f')\n self.xs = [\n numpy.random.uniform(-1, 1, (l, self.in_size)).astype('f')\n for l in self.lengths]\n\n self.gh = numpy.random.uniform(-1, 1, shape).astype('f')\n self.gys = [\n numpy.random.uniform(-1, 1, (l, self.out_size * 2)).astype('f')\n for l in self.lengths]\n if self.activation == 'tanh':\n rnn_link_class = links.NStepBiRNNTanh\n elif self.activation == 'relu':\n rnn_link_class = links.NStepBiRNNReLU\n self.rnn = rnn_link_class(\n self.n_layer, self.in_size, self.out_size, self.dropout)\n\n for layer in self.rnn:\n for p in layer.params():\n p.data[...] = numpy.random.uniform(-1, 1, p.data.shape)\n self.rnn.cleargrads()\n\n def check_forward(self, h_data, xs_data):\n if self.hidden_none:\n h = None\n else:\n h = chainer.Variable(h_data)\n xs = [chainer.Variable(x) for x in xs_data]\n hy, ys = self.rnn(h, xs)\n\n self.assertEqual(hy.data.shape, h_data.shape)\n self.assertEqual(len(xs), len(ys))\n for x, y in zip(xs, ys):\n self.assertEqual(len(x.data), len(y.data))\n self.assertEqual(y.data.shape[1], self.out_size * 2)\n\n self.rnn.to_cpu()\n\n for batch, seq in enumerate(self.xs):\n for layer in range(self.n_layer):\n # forward\n di = 0\n layer_idx = layer * 2 + di\n p = self.rnn[layer_idx]\n h_prev = self.h[layer_idx, batch]\n hs_f = []\n for x in seq:\n if self.activation == 'tanh':\n activation_func = numpy.tanh\n elif self.activation == 'relu':\n activation_func = relu\n\n h_prev = activation_func(x.dot(p.w0.data.T) +\n h_prev.dot(p.w1.data.T) +\n p.b0.data + p.b1.data)\n hs_f.append(h_prev)\n\n testing.assert_allclose(hy.data[layer_idx, batch], h_prev)\n\n # backward\n di = 1\n layer_idx = layer * 2 + di\n p = self.rnn[layer_idx]\n h_prev = self.h[layer_idx, batch]\n hs_b = []\n for x in reversed(seq):\n if self.activation == 'tanh':\n activation_func = numpy.tanh\n elif self.activation == 'relu':\n activation_func = relu\n h_prev = activation_func(x.dot(p.w0.data.T) +\n h_prev.dot(p.w1.data.T) +\n p.b0.data + p.b1.data)\n hs_b.append(h_prev)\n testing.assert_allclose(hy.data[layer_idx, batch], h_prev)\n\n hs_b.reverse()\n seq = [numpy.concatenate([hfi, hbi], axis=0) for (hfi, hbi)\n in zip(hs_f, hs_b)]\n\n for y, ey in zip(ys[batch].data, seq):\n testing.assert_allclose(y, ey)\n\n def test_forward_cpu_train(self):\n with chainer.using_config('train', True):\n self.check_forward(self.h, self.xs)\n\n @attr.gpu\n def test_forward_gpu_train(self):\n self.rnn.to_gpu()\n with chainer.using_config('use_cudnn', 'always'), \\\n chainer.using_config('train', True):\n self.check_forward(\n cuda.to_gpu(self.h),\n [cuda.to_gpu(x) for x in self.xs])\n\n def test_forward_cpu_test(self):\n with chainer.using_config('train', False):\n self.check_forward(self.h, self.xs)\n\n @attr.gpu\n def test_forward_gpu_test(self):\n self.rnn.to_gpu()\n with chainer.using_config('use_cudnn', 'always'), \\\n chainer.using_config('train', False):\n self.check_forward(\n cuda.to_gpu(self.h),\n [cuda.to_gpu(x) for x in self.xs])\n\n def check_backward(\n self, h_data, xs_data, gh_data, gys_data):\n\n def fun(*args):\n if self.hidden_none:\n h = None\n xs = args\n else:\n h, = args[:1]\n xs = args[1:]\n hy, ys = self.rnn(h, xs)\n return tuple([hy, ] + list(ys))\n\n params = []\n for layer in self.rnn:\n for p in layer.params():\n params.append(p)\n\n if self.hidden_none:\n in_data = xs_data\n else:\n in_data = [h_data, ] + xs_data\n gradient_check.check_backward(\n fun, tuple(in_data),\n tuple([gh_data, ] + gys_data),\n tuple(params), rtol=1e-2, atol=5e-2)\n\n @condition.retry(3)\n def test_backward_cpu(self):\n self.check_backward(\n self.h, self.xs, self.gh, self.gys)\n\n @attr.gpu\n @condition.retry(3)\n def test_backward_gpu(self):\n self.rnn.to_gpu()\n with chainer.using_config('use_cudnn', 'auto'):\n self.check_backward(\n cuda.to_gpu(self.h),\n [cuda.to_gpu(x) for x in self.xs],\n cuda.to_gpu(self.gh),\n [cuda.to_gpu(gy) for gy in self.gys])\n\n\ntesting.run_module(__name__, __file__)\n"
] | [
[
"numpy.arange",
"numpy.array",
"numpy.random.uniform",
"numpy.random.shuffle"
],
[
"numpy.random.uniform"
],
[
"numpy.random.uniform",
"numpy.zeros"
],
[
"numpy.interp",
"numpy.mean",
"numpy.random.rand"
],
[
"numpy.ndindex",
"numpy.copy",
"numpy.zeros",
"numpy.random.uniform"
],
[
"numpy.random.uniform"
],
[
"numpy.random.normal",
"numpy.mean",
"numpy.clip"
],
[
"numpy.random.uniform",
"numpy.squeeze"
],
[
"numpy.errstate",
"numpy.random.uniform"
],
[
"numpy.concatenate",
"numpy.random.uniform",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
cristinalunaj/WI-IAT20_PopularityModule | [
"0a4894e2b889bf31ea1a8beab3025d5dd0b1ed47"
] | [
"src/POPULARITY_MODULE/popularity_predictor.py"
] | [
"import pandas as pd\nimport subprocess, os\nimport src.utils.loader as loader\n\ndef create_test_arff(participant, test_df, aux_path):\n arff_text = \"@relation summary_features \\n\\n\" \\\n \"@attribute n_faces numeric\\n\" \\\n \"@attribute avg_confidence_faces numeric\\n\" \\\n \"@attribute std_confidence_faces numeric\\n\" \\\n \"@attribute avg_relativeSize_faces numeric\\n\" \\\n \"@attribute std_relativeSize_faces numeric\\n\" \\\n \"@attribute avg_thirdRule_x numeric\\n\" \\\n \"@attribute std_thirdRule_x numeric\\n\" \\\n \"@attribute avg_thirdRule_y numeric\\n\" \\\n \"@attribute std_thirdRule_y numeric\\n\" \\\n \"@attribute num_clts numeric\\n\" \\\n \"@attribute avg_silhouette numeric\\n\" \\\n \"@attribute avg_intra_clt_dist numeric\\n\" \\\n \"@attribute avg_inter_clt_dist numeric\\n\" \\\n \"@attribute faces_in_noise_clt numeric\\n\" \\\n \"@attribute num_core_samples numeric\\n\" \\\n \"@attribute avg_imgs_clt numeric\\n\" \\\n \"@attribute avg_std_silhouette numeric\\n\" \\\n \"@attribute avg_std_intra_clt_dist numeric\\n\" \\\n \"@attribute avg_std_inter_clt_dist numeric\\n\" \\\n \"@attribute avg_n_core_samples numeric\\n\" \\\n \"@attribute std_n_core_samples numeric\\n\" \\\n \"@attribute GTrends_popularity numeric\\n\" \\\n \"@attribute label {1,0}\\n\\n\" \\\n \"@data\\n\"\n\n data = test_df.loc[test_df[\"id\"]==participant]\n data = data.drop(columns=\"id\")\n data_str = \"\"\n for ele in data.values[0]:\n data_str += str(ele)+\",\"\n data_str = data_str[0:-3]\n arff_text+=data_str\n print(arff_text)\n\n f = open(aux_path, \"w\")\n f.write(arff_text)\n\ndef evaluate_test_arff(model_path, test_arff_path, out_path):\n \"\"\"\n Obtain predictions of test_file using the trained model in model_path\n :param output_folder:\n :param output_name:\n :param model_path:\n :param test_file:\n \"\"\"\n # PREDICTIONS FILE HEADERS: INSTANCE, ACTUAL, PREDICTED, ERROR\n bash_file_path = \"../../data/bash_scripts/explorer_test_model.sh \"\n with open(out_path, 'w') as fi:\n fi.close()\n command = \"\".join([bash_file_path, test_arff_path, \" \", model_path, \" \", out_path])\n print(command)\n subprocess.call(command, shell=True)\n remove_lines(out_path) # remove headers of prediction file\n df_participant = pd.read_csv(out_path, header=0, sep=\",\")\n return df_participant\n\ndef remove_lines(path_csv):\n with open(path_csv, 'r') as fin:\n data = fin.read().splitlines(True)\n with open(path_csv, 'w') as fout:\n fout.writelines(data[4:]) #en 4 las cabeceras\n fout.close()\n\n\nif __name__ == \"__main__\":\n th = \"05\"\n path_model = \"../../data/models/popularity_module/CLASIF/th\"+th+\"/RandomForest.model\"\n complete_df_ids = \"../../data/datasets/popularity_module_features/train/summary_features_participants_classification_th\"+th+\".csv\"\n aux_path = \"../../data/datasets/popularity_module_features/aux_test.arff\"\n out_path_prediction = \"../../data/datasets/popularity_module_features/aux_prediction.csv\"\n complete_df = pd.read_csv(complete_df_ids, header=0, sep=\",\")\n bash_test_model = \"\"\n path_participants = \"../../data/datasets/DATASET_GOOGLE_IMGS/participants/\"\n list_participants = loader.load_list_of_tertulianos(path_participants, \"participants_complete_rtve2018\",\".csv\")\n #list_participants = [participant.replace(\" \", \"_\") for participant in part]\n df_popularity = pd.DataFrame([], columns=[\"prediction\", \"popular\", \"id\"])\n out_path_popularity_df = \"../../data/results/popularity_models_output/popularity_df_th\"+th+\".csv\"\n for participant in list_participants:\n participant = participant.replace(\"_\", \" \")\n create_test_arff(participant, complete_df, aux_path)\n df_participant = evaluate_test_arff(path_model, aux_path, out_path_prediction)\n df_popularity = df_popularity.append(pd.DataFrame([[df_participant[\"predicted\"][0].split(\":\")[-1], df_participant[\"predicted\"][0].split(\":\")[-1]==\"1\", participant\n ]], columns=[\"prediction\", \"popular\", \"id\"]))\n df_popularity.to_csv(out_path_popularity_df, sep=\";\", header=True, index=False)\n\n\n\n\n\n"
] | [
[
"pandas.read_csv",
"pandas.DataFrame"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
antmicro/raviewer | [
"7529664d37e994d4c2f4c450a5577b79d73c4bb0"
] | [
"tests/image_test.py"
] | [
"import unittest\nimport numpy\nimport os\nimport raviewer.image.image as image\nimport raviewer.image.color_format as cf\nfrom raviewer.src.core import load_image\n\n\nclass TestImageClass(unittest.TestCase):\n\n def setUp(self):\n self.TEST_FILE_BGR = os.path.join(os.path.dirname(__file__),\n \"../resources/RGB24_1000_750\")\n self.empty_img = image.Image(None)\n with open(self.TEST_FILE_BGR, \"rb\") as file:\n self.img = image.Image(file.read(), cf.AVAILABLE_FORMATS['RGB24'],\n numpy.zeros(720 * 1280 * 4), 1280, 720)\n\n def test_from_file(self):\n self.assertEqual(\n load_image(self.TEST_FILE_BGR).data_buffer, self.img.data_buffer)\n with self.assertRaises(Exception):\n load_image(\"not_real_path\")\n\n def test_height_width(self):\n self.assertEqual(self.img.width, 1280)\n self.assertEqual(self.img.height, 720)\n self.assertEqual(self.empty_img.width, None)\n self.assertEqual(self.empty_img.height, None)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] | [
[
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Esail/tensorflow | [
"2538e68a69e585696175bd972cae119e06bde294",
"2538e68a69e585696175bd972cae119e06bde294",
"2538e68a69e585696175bd972cae119e06bde294",
"2538e68a69e585696175bd972cae119e06bde294"
] | [
"tensorflow/contrib/data/python/ops/threadpool.py",
"tensorflow/contrib/data/python/kernel_tests/optimization/map_parallelization_test.py",
"tensorflow/contrib/data/python/kernel_tests/window_dataset_op_test.py",
"tensorflow/contrib/data/python/kernel_tests/threadpool_dataset_ops_test.py"
] | [
"# Copyright 2018 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\"\"\"Experimental API for controlling threading in `tf.data` pipelines.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport threading\n\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.ops import gen_experimental_dataset_ops as ged_ops\nfrom tensorflow.python.ops import resource_variable_ops\n\n_uid_counter = 0\n_uid_lock = threading.Lock()\n\n\ndef _generate_shared_name(prefix):\n with _uid_lock:\n global _uid_counter\n uid = _uid_counter\n _uid_counter += 1\n return \"{}{}\".format(prefix, uid)\n\n\n# TODO(b/73383364): Properly export in the `tf.contrib.data` API when stable\n# or make private / remove.\nclass PrivateThreadPool(object):\n \"\"\"A stateful resource that represents a private thread pool.\"\"\"\n\n def __init__(self, num_threads, display_name=None,\n max_intra_op_parallelism=1):\n \"\"\"Creates a `PrivateThreadPool` with the given number of threads.\"\"\"\n if context.executing_eagerly():\n shared_name = _generate_shared_name(\"privatethreadpool\")\n self._resource = ged_ops.experimental_thread_pool_handle(\n num_threads=num_threads,\n max_intra_op_parallelism=max_intra_op_parallelism,\n display_name=display_name,\n shared_name=shared_name)\n self._resource_deleter = resource_variable_ops.EagerResourceDeleter(\n handle=self._resource, handle_device=context.context().device_name)\n else:\n self._resource = ged_ops.experimental_thread_pool_handle(\n num_threads=num_threads,\n max_intra_op_parallelism=max_intra_op_parallelism,\n display_name=display_name)\n\n\nclass _ThreadPoolDataset(dataset_ops.UnaryDataset):\n \"\"\"A `Dataset` that acts as an identity, and sets a custom threadpool.\"\"\"\n\n def __init__(self, input_dataset, thread_pool):\n super(_ThreadPoolDataset, self).__init__(input_dataset)\n self._input_dataset = input_dataset\n self._thread_pool = thread_pool\n\n def _as_variant_tensor(self):\n return ged_ops.experimental_thread_pool_dataset(\n self._input_dataset._as_variant_tensor(), # pylint: disable=protected-access\n self._thread_pool._resource, # pylint: disable=protected-access\n **dataset_ops.flat_structure(self))\n\n @property\n def output_shapes(self):\n return self._input_dataset.output_shapes\n\n @property\n def output_types(self):\n return self._input_dataset.output_types\n\n @property\n def output_classes(self):\n return self._input_dataset.output_classes\n\n\n# TODO(b/73383364): Properly export in the `tf.contrib.data` API when stable\n# or make private / remove.\ndef override_threadpool(dataset, thread_pool):\n \"\"\"Returns a new dataset that uses the given thread pool for its operations.\n\n Args:\n dataset: A `tf.data.Dataset` object.\n thread_pool: A `PrivateThreadPool` object.\n\n Returns:\n A dataset containing the same values as `dataset`, but which uses\n `thread_pool` to compute any of its parallel operations (such as\n `tf.data.Dataset.map`).\n \"\"\"\n return _ThreadPoolDataset(dataset, thread_pool)\n",
"# Copyright 2018 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 the MapParallelization optimization.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\n\nfrom tensorflow.contrib.data.python.ops import optimization\nfrom tensorflow.python.data.kernel_tests import test_base\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.platform import test\n\n\nclass MapParallelizationTest(test_base.DatasetTestBase, parameterized.TestCase):\n\n @staticmethod\n def map_functions():\n identity = lambda x: x\n increment = lambda x: x + 1\n\n def assert_greater(x):\n assert_op = control_flow_ops.Assert(math_ops.greater(x, -1), [x])\n with ops.control_dependencies([assert_op]):\n return x\n\n def random(_):\n return random_ops.random_uniform([],\n minval=0,\n maxval=10,\n dtype=dtypes.int64,\n seed=42)\n\n def assert_with_random(x):\n x = assert_greater(x)\n return random(x)\n\n return ((\"Identity\", identity, True), (\"Increment\", increment, True),\n (\"AssertGreater\", assert_greater, True), (\"Random\", random, False),\n (\"AssertWithRandom\", assert_with_random, False))\n\n @parameterized.named_parameters(*map_functions.__func__())\n def testMapParallelization(self, function, should_optimize):\n next_nodes = [\"ParallelMap\"] if should_optimize else [\"Map\"]\n dataset = dataset_ops.Dataset.range(5).apply(\n optimization.assert_next(next_nodes)).map(function).apply(\n optimization.optimize([\"map_parallelization\"]))\n iterator = dataset.make_one_shot_iterator()\n get_next = iterator.get_next()\n\n with self.test_session() as sess:\n for x in range(5):\n result = sess.run(get_next)\n # No need to run the pipeline if it was not optimized. Also the results\n # might be hard to check because of random.\n if not should_optimize:\n return\n r = function(x)\n self.assertAllEqual(r, result)\n\n with self.assertRaises(errors.OutOfRangeError):\n sess.run(get_next)\n\n\nif __name__ == \"__main__\":\n test.main()\n",
"# Copyright 2017 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 the experimental input pipeline ops.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.contrib.data.python.ops import batching\nfrom tensorflow.contrib.data.python.ops import grouping\nfrom tensorflow.python.data.kernel_tests import test_base\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import sparse_ops\nfrom tensorflow.python.platform import test\n\n\nclass WindowDatasetTest(test_base.DatasetTestBase, parameterized.TestCase):\n\n def _structuredDataset(self, structure, shape, dtype):\n if structure is None:\n return dataset_ops.Dataset.from_tensors(\n array_ops.zeros(shape, dtype=dtype))\n else:\n return dataset_ops.Dataset.zip(\n tuple([\n self._structuredDataset(substructure, shape, dtype)\n for substructure in structure\n ]))\n\n def _structuredElement(self, structure, shape, dtype):\n if structure is None:\n return array_ops.zeros(shape, dtype=dtype)\n else:\n return tuple([\n self._structuredElement(substructure, shape, dtype)\n for substructure in structure\n ])\n\n def _assertEqual(self, xs, ys):\n self.assertEqual(type(xs), type(ys))\n if isinstance(xs, tuple) and isinstance(ys, tuple):\n self.assertEqual(len(xs), len(ys))\n for x, y in zip(xs, ys):\n self._assertEqual(x, y)\n elif isinstance(xs, np.ndarray) and isinstance(ys, np.ndarray):\n self.assertAllEqual(xs, ys)\n else:\n self.assertEqual(xs, ys)\n\n @parameterized.named_parameters(\n (\"1\", None, np.int32([]), dtypes.bool),\n (\"2\", None, np.int32([]), dtypes.int32),\n (\"3\", None, np.int32([]), dtypes.float32),\n (\"4\", None, np.int32([]), dtypes.string),\n (\"5\", None, np.int32([2]), dtypes.int32),\n (\"6\", None, np.int32([2, 2]), dtypes.int32),\n (\"7\", (None, None, None), np.int32([]), dtypes.int32),\n (\"8\", (None, (None, None)), np.int32([]), dtypes.int32),\n )\n def testWindowDatasetFlatMap(self, structure, shape, dtype):\n \"\"\"Tests windowing by chaining it with flat map.\n\n Args:\n structure: the input structure\n shape: the input shape\n dtype: the input data type\n \"\"\"\n\n def fn(*args):\n if len(args) == 1 and not isinstance(args[0], tuple):\n return args[0]\n return dataset_ops.Dataset.zip(\n tuple([fn(*arg) if isinstance(arg, tuple) else arg for arg in args]))\n\n dataset = self._structuredDataset(structure, shape, dtype).repeat(5).apply(\n grouping.window_dataset(5)).flat_map(fn)\n get_next = dataset.make_one_shot_iterator().get_next()\n with self.cached_session() as sess:\n expected = sess.run(self._structuredElement(structure, shape, dtype))\n for _ in range(5):\n actual = sess.run(get_next)\n self._assertEqual(expected, actual)\n\n @parameterized.named_parameters(\n (\"1\", None, np.int32([]), dtypes.bool),\n (\"2\", None, np.int32([]), dtypes.int32),\n (\"3\", None, np.int32([]), dtypes.float32),\n (\"4\", None, np.int32([]), dtypes.string),\n (\"5\", None, np.int32([2]), dtypes.int32),\n (\"6\", None, np.int32([2, 2]), dtypes.int32),\n (\"7\", (None, None, None), np.int32([]), dtypes.int32),\n (\"8\", (None, (None, None)), np.int32([]), dtypes.int32),\n )\n def testWindowDatasetBatchDense(self, structure, shape, dtype):\n \"\"\"Tests batching of dense tensor windows.\n\n Args:\n structure: the input structure\n shape: the input shape\n dtype: the input data type\n \"\"\"\n\n def fn(*args):\n if len(args) == 1 and not isinstance(args[0], tuple):\n return batching.batch_window(args[0])\n\n return tuple([\n fn(*arg) if isinstance(arg, tuple) else batching.batch_window(arg)\n for arg in args\n ])\n\n dataset = self._structuredDataset(structure, shape, dtype).repeat(5).apply(\n grouping.window_dataset(5)).apply(grouping._map_x_dataset(fn))\n get_next = dataset.make_one_shot_iterator().get_next()\n with self.cached_session() as sess:\n expected = sess.run(\n self._structuredElement(structure, np.concatenate(\n ([5], shape), axis=0), dtype))\n actual = sess.run(get_next)\n self._assertEqual(expected, actual)\n\n @parameterized.named_parameters(\n (\"1\", np.int32([])),\n (\"2\", np.int32([1])),\n (\"3\", np.int32([1, 2, 3])),\n )\n def testWindowDatasetBatchDenseDynamicShape(self, shape):\n \"\"\"Tests batching of dynamically shaped dense tensor windows.\n\n Args:\n shape: the input shape\n \"\"\"\n\n shape_t = array_ops.placeholder(dtypes.int32)\n dataset = dataset_ops.Dataset.from_tensors(\n array_ops.zeros(shape_t)).repeat(5).apply(\n grouping.window_dataset(5)).apply(\n grouping._map_x_dataset(batching.batch_window))\n iterator = dataset.make_initializable_iterator()\n init_op = iterator.initializer\n get_next = iterator.get_next()\n with self.cached_session() as sess:\n sess.run(init_op, {shape_t: shape})\n expected = sess.run(\n self._structuredElement(None, np.concatenate(([5], shape), axis=0),\n dtypes.int32))\n actual = sess.run(get_next)\n self._assertEqual(expected, actual)\n\n def _make_dense_to_sparse_fn(self, is_scalar):\n\n def dense_to_sparse_scalar(tensor):\n indices = [[]]\n values = array_ops.expand_dims(tensor, 0)\n shape = []\n return sparse_tensor.SparseTensorValue(indices, values, shape)\n\n def dense_to_sparse_non_scalar(tensor):\n indices = array_ops.where(array_ops.ones_like(tensor, dtype=dtypes.bool))\n values = array_ops.gather_nd(tensor, indices)\n shape = array_ops.shape(tensor, out_type=dtypes.int64)\n return sparse_tensor.SparseTensorValue(indices, values, shape)\n\n if is_scalar:\n return dense_to_sparse_scalar\n return dense_to_sparse_non_scalar\n\n def _structuredSparseDataset(self, structure, shape, dtype):\n dense_to_sparse = self._make_dense_to_sparse_fn(len(shape) == 0) # pylint: disable=g-explicit-length-test\n if structure is None:\n return dataset_ops.Dataset.from_tensors(\n dense_to_sparse(array_ops.zeros(shape, dtype=dtype)))\n else:\n return dataset_ops.Dataset.zip(\n tuple([\n self._structuredSparseDataset(substructure, shape, dtype)\n for substructure in structure\n ]))\n\n def _structuredSparseElement(self, structure, shape, dtype):\n dense_to_sparse = self._make_dense_to_sparse_fn(len(shape) == 0) # pylint: disable=g-explicit-length-test\n if structure is None:\n return dense_to_sparse(array_ops.zeros(shape, dtype=dtype))\n else:\n return tuple([\n self._structuredSparseElement(substructure, shape, dtype)\n for substructure in structure\n ])\n\n @parameterized.named_parameters(\n (\"1\", None, np.int32([]), dtypes.bool),\n (\"2\", None, np.int32([]), dtypes.int32),\n (\"3\", None, np.int32([]), dtypes.float32),\n (\"4\", None, np.int32([]), dtypes.string),\n (\"5\", None, np.int32([2]), dtypes.int32),\n (\"6\", None, np.int32([2, 2]), dtypes.int32),\n (\"7\", (None, None, None), np.int32([]), dtypes.int32),\n (\"8\", (None, (None, None)), np.int32([]), dtypes.int32),\n )\n def testWindowDatasetBatchSparse(self, structure, shape, dtype):\n \"\"\"Tests batching of sparse tensor windows.\n\n Args:\n structure: the input structure\n shape: the input shape\n dtype: the input data type\n \"\"\"\n\n def fn(*args):\n if len(args) == 1 and not isinstance(args[0], tuple):\n return batching.batch_window(args[0])\n\n return tuple([\n fn(*arg) if isinstance(arg, tuple) else batching.batch_window(arg)\n for arg in args\n ])\n\n dataset = self._structuredSparseDataset(\n structure, shape, dtype).repeat(5).apply(\n grouping.window_dataset(5)).apply(grouping._map_x_dataset(fn))\n get_next = dataset.make_one_shot_iterator().get_next()\n with self.cached_session() as sess:\n expected = sess.run(\n self._structuredSparseElement(structure,\n np.concatenate(([5], shape), axis=0),\n dtype))\n actual = sess.run(get_next)\n self._assertEqual(expected, actual)\n\n @parameterized.named_parameters(\n (\"1\", np.int32([])),\n (\"2\", np.int32([1])),\n (\"3\", np.int32([1, 2, 3])),\n )\n def testWindowDatasetBatchSparseDynamicShape(self, shape):\n \"\"\"Tests batching of dynamically shaped sparse tensor windows.\n\n Args:\n shape: the input shape\n \"\"\"\n\n shape_t = array_ops.placeholder(dtypes.int32)\n dataset = dataset_ops.Dataset.from_tensors(array_ops.zeros(shape_t)).map(\n self._make_dense_to_sparse_fn(len(shape) == 0)).repeat(5).apply( # pylint: disable=g-explicit-length-test\n grouping.window_dataset(5)).apply(\n grouping._map_x_dataset(batching.batch_window))\n iterator = dataset.make_initializable_iterator()\n init_op = iterator.initializer\n get_next = iterator.get_next()\n with self.cached_session() as sess:\n sess.run(init_op, {shape_t: shape})\n expected = sess.run(\n self._structuredSparseElement(None,\n np.concatenate(([5], shape), axis=0),\n dtypes.int32))\n actual = sess.run(get_next)\n self._assertEqual(expected, actual)\n\n def _structuredRaggedDataset(self, structure, shapes, dtype):\n\n if structure is None:\n return dataset_ops.Dataset.from_tensor_slices(shapes).map(\n lambda shape: array_ops.zeros(shape, dtype=dtype))\n else:\n return dataset_ops.Dataset.zip(\n tuple([\n self._structuredRaggedDataset(substructure, shapes, dtype)\n for substructure in structure\n ]))\n\n @parameterized.named_parameters(\n (\"1\", None, np.int32([[1], [2], [3]]), dtypes.bool, [-1]),\n (\"2\", None, np.int32([[1], [2], [3]]), dtypes.int32, [-1]),\n (\"3\", None, np.int32([[1], [2], [3]]), dtypes.float32, [-1]),\n (\"4\", None, np.int32([[1], [2], [3]]), dtypes.string, [-1]),\n (\"5\", None, np.int32([[1, 3], [2, 2], [3, 1]]), dtypes.int32, [-1, -1]),\n (\"6\", None, np.int32([[3, 1, 3], [1, 3, 1]]), dtypes.int32, [-1, -1, -1]),\n (\"7\", (None, None, None), np.int32([[1], [2], [3]]), dtypes.int32, [-1]),\n (\"8\", (None,\n (None, None)), np.int32([[1], [2], [3]]), dtypes.int32, [-1]),\n (\"9\", None, np.int32([[1], [2], [3]]), dtypes.int32, [-1]),\n (\"10\", None, np.int32([[1], [2], [3]]), dtypes.int32, np.int32([10])),\n )\n def testWindowDatasetPaddedBatchDense(self, structure, shapes, dtype,\n padded_shape):\n \"\"\"Tests padded batching of dense tensor windows.\n\n Args:\n structure: the input structure\n shapes: the input shapes\n dtype: the input data type\n padded_shape: the shape to pad the output to\n \"\"\"\n\n def fn(*args):\n if len(args) == 1 and not isinstance(args[0], tuple):\n return batching.padded_batch_window(args[0], padded_shape)\n\n return tuple([\n fn(*arg) if isinstance(arg, tuple) else batching.padded_batch_window(\n arg, padded_shape) for arg in args\n ])\n\n dataset = self._structuredRaggedDataset(structure, shapes, dtype).apply(\n grouping.window_dataset(len(shapes))).apply(\n grouping._map_x_dataset(fn))\n get_next = dataset.make_one_shot_iterator().get_next()\n with self.cached_session() as sess:\n expected_shape = np.maximum(np.amax(shapes, axis=0), padded_shape)\n expected = sess.run(\n self._structuredElement(\n structure,\n np.concatenate((np.int32([len(shapes)]), expected_shape)), dtype))\n actual = sess.run(get_next)\n self._assertEqual(expected, actual)\n\n @parameterized.named_parameters(\n (\"1\", np.int32([[1], [2], [3]]), [-1]),\n (\"2\", np.int32([[1, 3], [2, 2], [3, 1]]), [-1, -1]),\n (\"3\", np.int32([[3, 1, 3], [1, 3, 1]]), [-1, -1, -1]),\n )\n def testWindowDatasetPaddedBatchDenseDynamicShape(self, shapes, padded_shape):\n \"\"\"Tests padded batching of dynamically shaped dense tensor windows.\n\n Args:\n shapes: the input shapes\n padded_shape: the shape to pad the output to\n \"\"\"\n\n shapes_t = array_ops.placeholder(dtypes.int32)\n dataset = dataset_ops.Dataset.from_tensor_slices(shapes_t).map(\n lambda shape: array_ops.zeros(shape, dtype=dtypes.int32)).apply(\n grouping.window_dataset(len(shapes))).apply(\n grouping._map_x_dataset(\n lambda x: batching.padded_batch_window(x, padded_shape)))\n iterator = dataset.make_initializable_iterator()\n init_op = iterator.initializer\n get_next = iterator.get_next()\n with self.cached_session() as sess:\n sess.run(init_op, {shapes_t: shapes})\n expected_shape = np.maximum(np.amax(shapes, axis=0), padded_shape)\n expected = sess.run(\n self._structuredElement(\n None, np.concatenate((np.int32([len(shapes)]), expected_shape)),\n dtypes.int32))\n actual = sess.run(get_next)\n self._assertEqual(expected, actual)\n\n @parameterized.named_parameters(\n (\"1\", np.int32([[1]]), np.int32([0])),\n (\"2\", np.int32([[10], [20]]), np.int32([15])),\n )\n def testWindowDatasetPaddedBatchDenseInvalid(self, shapes, padded_shape):\n \"\"\"Tests invalid padded batching of dense tensor windows.\n\n Args:\n shapes: the input shapes\n padded_shape: the shape to pad the output to\n \"\"\"\n\n dataset = dataset_ops.Dataset.from_tensor_slices(shapes).map(\n lambda shape: array_ops.zeros(shape, dtype=dtypes.int32)).apply(\n grouping.window_dataset(len(shapes))).apply(\n grouping._map_x_dataset(\n lambda x: batching.padded_batch_window(x, padded_shape)))\n get_next = dataset.make_one_shot_iterator().get_next()\n with self.cached_session() as sess:\n with self.assertRaises(errors.InvalidArgumentError):\n sess.run(get_next)\n\n def _structuredRaggedSparseDataset(self, structure, shapes, dtype):\n\n def map_fn(shape):\n dense_to_sparse = self._make_dense_to_sparse_fn(False)\n return dense_to_sparse(array_ops.zeros(shape, dtype=dtype))\n\n if structure is None:\n return dataset_ops.Dataset.from_tensor_slices(shapes).map(map_fn)\n else:\n return dataset_ops.Dataset.zip(\n tuple([\n self._structuredRaggedSparseDataset(substructure, shapes, dtype)\n for substructure in structure\n ]))\n\n def _structuredRaggedSparseElement(self, structure, shapes, dtype,\n padded_shape):\n if structure is None:\n dense_shape = np.maximum(np.amax(shapes, axis=0), padded_shape)\n values = []\n for shape in shapes:\n dense_to_sparse = self._make_dense_to_sparse_fn(len(shape) == 0) # pylint: disable=g-explicit-length-test\n sparse = dense_to_sparse(array_ops.zeros(shape, dtype=dtype))\n padded_sparse = sparse_tensor.SparseTensor(sparse.indices,\n sparse.values, dense_shape)\n reshaped_sparse = sparse_ops.sparse_reshape(\n padded_sparse,\n array_ops.concat([np.array([1], dtype=np.int64), dense_shape], 0))\n values.append(reshaped_sparse)\n return sparse_ops.sparse_concat(0, values)\n else:\n return tuple([\n self._structuredRaggedSparseElement(substructure, shapes, dtype,\n padded_shape)\n for substructure in structure\n ])\n\n @parameterized.named_parameters(\n (\"1\", None, np.int64([[1], [2], [3]]), dtypes.bool, [-1]),\n (\"2\", None, np.int64([[1], [2], [3]]), dtypes.int32, [-1]),\n (\"3\", None, np.int64([[1], [2], [3]]), dtypes.float32, [-1]),\n (\"4\", None, np.int64([[1], [2], [3]]), dtypes.string, [-1]),\n (\"5\", None, np.int64([[1, 3], [2, 2], [3, 1]]), dtypes.int32, [-1, -1]),\n (\"6\", None, np.int64([[1, 3, 1], [3, 1, 3]]), dtypes.int32, [-1, -1, -1]),\n (\"7\", (None, None, None), np.int64([[1], [2], [3]]), dtypes.int32, [-1]),\n (\"8\", (None,\n (None, None)), np.int64([[1], [2], [3]]), dtypes.int32, [-1]),\n (\"9\", None, np.int64([[1], [2], [3]]), dtypes.int32, [-1]),\n (\"10\", None, np.int64([[1], [2], [3]]), dtypes.int32, np.int64([10])),\n )\n def testWindowDatasetPaddedBatchSparse(self, structure, shapes, dtype,\n padded_shape):\n \"\"\"Tests padded batching of sparse tensor windows.\n\n Args:\n structure: the input structure\n shapes: the input shapes\n dtype: the input data type\n padded_shape: the shape to pad the output to\n \"\"\"\n\n def fn(*args):\n if len(args) == 1 and not isinstance(args[0], tuple):\n return batching.padded_batch_window(args[0], padded_shape)\n\n return tuple([\n fn(*arg) if isinstance(arg, tuple) else batching.padded_batch_window(\n arg, padded_shape) for arg in args\n ])\n\n dataset = self._structuredRaggedSparseDataset(\n structure, shapes, dtype).apply(grouping.window_dataset(\n len(shapes))).apply(grouping._map_x_dataset(fn))\n get_next = dataset.make_one_shot_iterator().get_next()\n with self.cached_session() as sess:\n expected = sess.run(\n self._structuredRaggedSparseElement(structure, shapes, dtype,\n padded_shape))\n actual = sess.run(get_next)\n self._assertEqual(expected, actual)\n\n @parameterized.named_parameters(\n (\"1\", np.int64([[1], [2], [3]]), [-1]),\n (\"2\", np.int64([[1, 3], [2, 2], [3, 1]]), [-1, -1]),\n (\"3\", np.int64([[3, 1, 3], [1, 3, 1]]), [-1, -1, -1]),\n )\n def testWindowDatasetPaddedBatchSparseDynamicShape(self, shapes,\n padded_shape):\n \"\"\"Tests padded batching of dynamically shaped sparse tensor windows.\n\n Args:\n shapes: the input shapes\n padded_shape: the shape to pad the output to\n \"\"\"\n\n shapes_t = array_ops.placeholder(dtypes.int32)\n dataset = dataset_ops.Dataset.from_tensor_slices(shapes_t).map(\n lambda shape: array_ops.zeros(shape, dtype=dtypes.int32)).map(\n self._make_dense_to_sparse_fn(False)\n ).apply(grouping.window_dataset(len(shapes))).apply(\n grouping._map_x_dataset(\n lambda x: batching.padded_batch_window(x, padded_shape)))\n iterator = dataset.make_initializable_iterator()\n init_op = iterator.initializer\n get_next = iterator.get_next()\n with self.cached_session() as sess:\n sess.run(init_op, {shapes_t: shapes})\n expected = sess.run(\n self._structuredRaggedSparseElement(None, shapes, dtypes.int32,\n padded_shape))\n actual = sess.run(get_next)\n self._assertEqual(expected, actual)\n\n @parameterized.named_parameters(\n (\"1\", np.int64([[1]]), [0]),\n (\"2\", np.int64([[10], [20]]), [15]),\n )\n def testWindowDatasetPaddedBatchSparseInvalid(self, shapes, padded_shape):\n \"\"\"Tests invalid padded batching of sparse tensor windows.\n\n Args:\n shapes: the input shapes\n padded_shape: the shape to pad the output to\n \"\"\"\n\n dataset = dataset_ops.Dataset.from_tensor_slices(shapes).map(\n lambda shape: array_ops.zeros(shape, dtype=dtypes.int32)).map(\n self._make_dense_to_sparse_fn(False)\n ).apply(grouping.window_dataset(len(shapes))).apply(\n grouping._map_x_dataset(\n lambda x: batching.padded_batch_window(x, padded_shape)))\n get_next = dataset.make_one_shot_iterator().get_next()\n with self.cached_session() as sess:\n with self.assertRaises(errors.InvalidArgumentError):\n sess.run(get_next)\n\n\nif __name__ == \"__main__\":\n test.main()\n",
"# Copyright 2018 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 the experimental input pipeline statistics gathering ops.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport threading\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.contrib.data.python.ops import threadpool\nfrom tensorflow.contrib.data.python.ops import unique\nfrom tensorflow.python.data.kernel_tests import test_base\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.ops import script_ops\nfrom tensorflow.python.platform import test\n\n\nclass OverrideThreadpoolDatasetTest(test_base.DatasetTestBase,\n parameterized.TestCase):\n\n @parameterized.named_parameters(\n (\"1\", 1, None),\n (\"2\", 2, None),\n (\"3\", 4, None),\n (\"4\", 8, None),\n (\"5\", 16, None),\n (\"6\", 4, -1),\n (\"7\", 4, 0),\n (\"8\", 4, 1),\n (\"9\", 4, 4),\n )\n def testNumThreads(self, num_threads, max_intra_op_parallelism):\n\n def get_thread_id(_):\n # Python creates a dummy thread object to represent the current\n # thread when called from an \"alien\" thread (such as a\n # `PrivateThreadPool` thread in this case). It does not include\n # the TensorFlow-given display name, but it has a unique\n # identifier that maps one-to-one with the underlying OS thread.\n return np.array(threading.current_thread().ident).astype(np.int64)\n\n dataset = (\n dataset_ops.Dataset.range(1000).map(\n lambda x: script_ops.py_func(get_thread_id, [x], dtypes.int64),\n num_parallel_calls=32).apply(unique.unique()))\n\n dataset = threadpool.override_threadpool(\n dataset,\n threadpool.PrivateThreadPool(\n num_threads,\n max_intra_op_parallelism=max_intra_op_parallelism,\n display_name=\"private_thread_pool_%d\" % num_threads))\n\n iterator = dataset.make_initializable_iterator()\n next_element = iterator.get_next()\n\n with self.cached_session() as sess:\n sess.run(iterator.initializer)\n thread_ids = []\n try:\n while True:\n thread_ids.append(sess.run(next_element))\n except errors.OutOfRangeError:\n pass\n self.assertEqual(len(thread_ids), len(set(thread_ids)))\n self.assertGreater(len(thread_ids), 0)\n # NOTE(mrry): We don't control the thread pool scheduling, and\n # so cannot guarantee that all of the threads in the pool will\n # perform work.\n self.assertLessEqual(len(thread_ids), num_threads)\n\n\nif __name__ == \"__main__\":\n test.main()\n"
] | [
[
"tensorflow.python.ops.gen_experimental_dataset_ops.experimental_thread_pool_handle",
"tensorflow.python.eager.context.context",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.data.ops.dataset_ops.flat_structure"
],
[
"tensorflow.python.ops.math_ops.greater",
"tensorflow.contrib.data.python.ops.optimization.assert_next",
"tensorflow.python.platform.test.main",
"tensorflow.python.data.ops.dataset_ops.Dataset.range",
"tensorflow.python.framework.ops.control_dependencies",
"tensorflow.python.ops.random_ops.random_uniform",
"tensorflow.contrib.data.python.ops.optimization.optimize"
],
[
"numpy.amax",
"tensorflow.python.ops.array_ops.shape",
"tensorflow.python.ops.array_ops.placeholder",
"numpy.concatenate",
"tensorflow.python.ops.array_ops.gather_nd",
"tensorflow.python.ops.array_ops.zeros",
"tensorflow.python.framework.sparse_tensor.SparseTensorValue",
"tensorflow.python.ops.sparse_ops.sparse_concat",
"tensorflow.python.framework.sparse_tensor.SparseTensor",
"tensorflow.python.platform.test.main",
"tensorflow.contrib.data.python.ops.grouping._map_x_dataset",
"tensorflow.python.data.ops.dataset_ops.Dataset.from_tensor_slices",
"numpy.int64",
"numpy.array",
"tensorflow.contrib.data.python.ops.batching.padded_batch_window",
"tensorflow.python.ops.array_ops.ones_like",
"numpy.int32",
"tensorflow.contrib.data.python.ops.grouping.window_dataset",
"tensorflow.contrib.data.python.ops.batching.batch_window",
"tensorflow.python.ops.array_ops.expand_dims"
],
[
"tensorflow.contrib.data.python.ops.threadpool.PrivateThreadPool",
"tensorflow.python.ops.script_ops.py_func",
"tensorflow.python.platform.test.main",
"tensorflow.contrib.data.python.ops.unique.unique",
"tensorflow.python.data.ops.dataset_ops.Dataset.range"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.13",
"1.12"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.13",
"1.7",
"1.10",
"1.12"
]
}
] |
koonimaru/DeepGMAP | [
"7daac354229fc25fba81649b741921345dc5db05",
"7daac354229fc25fba81649b741921345dc5db05"
] | [
"deepgmap/train/deepshark_local_oop_1d.py",
"deepgmap/post_train_tools/motif_compare.py"
] | [
"import tensorflow as tf\nimport sys\nimport numpy as np\nimport time\nimport glob\nfrom natsort import natsorted\nimport getopt\nimport importlib as il\nimport matplotlib.pyplot as plt\n\ndef next_batch(loop, input_dir, batch_size, data_length):\n f = glob.glob(str(input_dir)+\"*\")\n f_srt=natsorted(f)\n with np.load(str(f_srt[loop])) as f1:\n try:\n dnase_data_labels=f1['labels'], f1['data_array']\n \n except EOFError:\n print(\"cannot load: \"+str(f_srt[loop]))\n images=np.reshape(dnase_data_labels[1], (batch_size, data_length, 4, 1))\n labels=dnase_data_labels[0]\n halfimages=np.vsplit(images, 2)\n halflabels=np.vsplit(labels, 2)\n return halfimages[0], halflabels[0], halfimages[1], halflabels[1]\n\ndef process(f,half_batch,data_length):\n with np.load(f) as f1:\n try:\n dnase_data_labels=f1['labels'], f1['data_array']\n \n except EOFError:\n print(\"cannot load: \"+str(f))\n \n shape=dnase_data_labels[1].shape\n images=np.reshape(dnase_data_labels[1], (shape[0], data_length, 4, 1))\n labels=dnase_data_labels[0] \n #print(shape[0]) \n if shape[0]>half_batch:\n halfimages=images[:half_batch] , images[half_batch:]\n halflabels=labels[:half_batch], labels[half_batch:]\n else:\n halfimages=images\n halflabels=labels\n \n return halfimages, halflabels\n\ndef process2(f,data_length):\n with np.load(f) as f1:\n try:\n dnase_data_labels=f1['labels'], f1['data_array']\n \n except EOFError:\n print(\"cannot load: \"+str(f))\n \n shape=dnase_data_labels[1].shape\n images=np.reshape(dnase_data_labels[1], (shape[0], data_length, 4, 1))\n labels=dnase_data_labels[0] \n return images, labels\n\n\ndef batch_queuing(file_list, batch_size, data_length):\n \n with tf.device('/cpu:0'):\n half_batch=batch_size/2\n image_list=[]\n label_list=[]\n #CPU=20\n #pool=mltp.Pool(CPU)\n for f in file_list:\n #res=apply_async(pool, process,args=(f,))\n #halfimages, halflabels=res.get()\n \n halfimages, halflabels=process(f,half_batch,data_length)\n image_list.append(halfimages)\n label_list.append(halflabels)\n #pool.close()\n #pool.join()\n return image_list, label_list\n\ndef batch_queuing2(file_list, batch_size, data_length):\n \n with tf.device('/cpu:0'):\n image_list=[]\n label_list=[]\n #CPU=20\n #pool=mltp.Pool(CPU)\n for f in file_list:\n #res=apply_async(pool, process,args=(f,))\n #halfimages, halflabels=res.get()\n \n images, labels=process2(f,data_length)\n image_list.append(images)\n label_list.append(labels)\n #pool.close()\n #pool.join()\n return image_list, label_list\n\n\ndef softmax(w, t = 1.0):\n npa = np.array\n e = np.exp(npa(w) / t)\n dist = e /np.stack((np.sum(e, axis=1),np.sum(e, axis=1)),axis=-1)\n return dist\ndef test_batch(input_dir,output_dir,test_batch_num,batch_size, data_length):\n f = glob.glob(str(input_dir))\n f_srt=natsorted(f, key=lambda y: y.lower())\n test_dir=output_dir.replace('output/', '')\n #print len(f_srt), test_batch_num\n data_list=[]\n labels_list=[]\n for i in range(3):\n a=np.load(f_srt[int(test_batch_num)+i])\n label_=a['labels'], \n data_=a['data_array']\n data_shape=np.shape(data_)\n label_shape=np.shape(label_)\n #print \"labelshape=\"+str(label_shape)\n data_list.append(np.reshape(data_, (data_shape[0], data_length, 4, 1)))\n labels_list.append(np.reshape(label_,(-1,label_shape[-1])))\n\n return data_list[0], labels_list[0], data_list[1], labels_list[1], data_list[2], labels_list[2]\n\ndef div_roundup(x, y):\n if y%x==0:\n return y/x\n else:\n return y/x+1\n \ndef run(args):\n main(args)\n\n\ndef main(args=None):\n \n start=time.time()\n a=time.asctime()\n b=a.replace(':', '')\n start_at=b.replace(' ', '_')\n mode=\"train\"\n loop_num_=None\n test_batch_num=None\n max_to_keep=2\n TEST_THRESHHOLD=0.75\n SAVE_THRESHHOLD=0\n dropout_1=1.00\n dropout_2=0.80\n dropout_3=0.50\n queue_len=5000\n #max_train=20000\n \n if args!=None:\n mode=args.mode\n loop_num_=args.loop_number\n test_batch_num=args.test_batch_number\n max_to_keep=args.max_to_keep\n input_dir=args.in_directory\n model_name=args.model\n pretrained_dir=args.ckpt_file\n output_dir=args.out_directory \n else:\n try:\n options, args =getopt.getopt(sys.argv[1:], 'm:i:n:b:o:c:p:', ['mode=', 'in_dir=', 'loop_num=', 'test_batch_num=', 'out_dir=','network_constructor=','pretrained_model='])\n except getopt.GetoptError as err:\n print(str(err))\n sys.exit(2)\n if len(options)<3:\n print('too few argument')\n sys.exit(0)\n for opt, arg in options:\n if opt in ('-m', '--mode'):\n mode=arg\n elif opt in ('-i', '--in_dir'):\n input_dir=arg\n \n elif opt in ('-n', '--loop_num'):\n loop_num_=int(arg)\n elif opt in ('-b', '--test_batch_num'):\n test_batch_num=int(arg)\n elif opt in ('-o', '--out_dir'):\n output_dir=arg\n elif opt in ('-c', '--network_constructor'):\n model_name=arg\n elif opt in ('-p', '--pretrained_model'):\n pretrained_dir=arg\n \n if input_dir.endswith(\"/\"):\n input_dir=str(input_dir)+\"*.npz\"\n elif input_dir.endswith(\"*\") or input_dir.endswith(\".npz\"):\n pass\n else:\n input_dir=str(input_dir)+\"/*.npz\"\n f = glob.glob(input_dir)\n if len(f)==0:\n print(\"can't open input files, no such a directory\")\n sys.exit(0)\n \n f_srt=natsorted(f)\n \n if loop_num_==None:\n loop_num_=len(f_srt)-5\n \n if test_batch_num==None:\n test_batch_num=loop_num_+1\n \n \n with np.load(str(f_srt[0])) as f:\n labels=f['labels']\n _data=f['data_array']\n batch_size, label_dim=labels.shape\n _, data_length, _2=_data.shape\n print(batch_size, label_dim) \n\n config = tf.ConfigProto(device_count = {'GPU': 2})\n config.gpu_options.allow_growth=True\n #config.graph_options.optimizer_options.global_jit_level = tf.OptimizerOptions.ON_1\n sess = tf.Session(config=config)\n x_image = tf.placeholder(tf.float32, shape=[None, data_length, 4, 1])\n y_ = tf.placeholder(tf.float32, shape=[None, label_dim])\n phase=tf.placeholder(tf.bool)\n keep_prob = tf.placeholder(tf.float32)\n keep_prob2 = tf.placeholder(tf.float32)\n keep_prob3 = tf.placeholder(tf.float32)\n nc=il.import_module(\"deepgmap.network_constructors.\"+str(model_name))\n print(\"running \"+str(model_name))\n\n model = nc.Model(image=x_image, label=y_, \n output_dir=output_dir,\n phase=phase, \n start_at=start_at, \n keep_prob=keep_prob, \n keep_prob2=keep_prob2, \n keep_prob3=keep_prob3, \n data_length=data_length,\n max_to_keep=max_to_keep)\n\n sess.run(tf.global_variables_initializer())\n saver=model.saver\n\n if mode=='retrain':\n saver.restore(sess, pretrained_dir)\n \n train_accuracy_record=[]\n loss_val_record=[]\n total_learing=[]\n loop_num=div_roundup(queue_len, len(f_srt))\n BREAK=False\n prev_ac=None\n test_step=[]\n CHECK_TEST_FR=False\n for i in range(loop_num):\n if BREAK:\n print(\"breaking the train loop\")\n break\n input_files=f_srt[i*queue_len:(i+1)*queue_len]\n image_list, label_list=batch_queuing(input_files, batch_size, data_length)\n \n for k in range(len(image_list)):\n start_tmp=time.time()\n a=np.shape(image_list[k])\n\n #print a\n if len(a)==4:\n train_accuracy_,loss_val= sess.run([model.error, \n model.cost], \n feed_dict=\n {x_image: image_list[k], \n y_: label_list[k], \n keep_prob: 1.0, keep_prob2: 1.0, keep_prob3: 1.0, \n phase: False})\n else:\n batch=image_list[k][0],label_list[k][0],image_list[k][1],label_list[k][1]\n #print(len(batch))\n #batch = next_batch(i,input_files, batch_size, data_length)\n train_accuracy_,loss_val= sess.run([model.error, model.cost], feed_dict={x_image: np.concatenate((batch[2],batch[0])), \n y_: np.concatenate((batch[3],batch[1])), \n keep_prob: 1.0, keep_prob2: 1.0, keep_prob3: 1.0, \n phase: False})\n \"\"\"train_accuracy_,loss_val= sess.run([model.error, model.cost], feed_dict={x_image:batch[2], \n y_: batch[3], \n keep_prob: 1.0, keep_prob2: 1.0, keep_prob3: 1.0, \n phase: False})\"\"\"\n FPR_list, TPR_list, PPV_list=train_accuracy_\n #print np.nansum(PPV_list)\n curr_accu=float(np.round(np.nanmean(2*np.array(TPR_list)*np.array(PPV_list)/(0.0000001+np.array(PPV_list)+np.array(TPR_list))),4))\n sys.stdout.write(\"\\r\"+\"step \"+str(i*queue_len+k)\n +\", cost: \"+str(loss_val)\n +\", train_accuracy: \"\n +str(list([curr_accu]))+\", \"+str(time.time()-start_tmp)) \n sys.stdout.flush()\n \n #train_accuracy_record.append(TPR_list[0]-FPR_list[0])\n train_accuracy_record.append(curr_accu)\n loss_val_record.append(loss_val)\n total_learing.append((i*queue_len+k)*batch_size/1000.0)\n if i*queue_len+k>=2:\n #temporal_accuracy=train_accuracy_record[i*queue_len+k]+train_accuracy_record[i*queue_len+k-1]+train_accuracy_record[i*queue_len+k-2]\n temporal_accuracy=np.round((train_accuracy_record[i*queue_len+k]+train_accuracy_record[i*queue_len+k-1]+train_accuracy_record[i*queue_len+k-2])/3.0,4)\n if len(test_step)>1:\n CHECK_TEST_FR=((i*queue_len+k-test_step[-1])>1000)\n CHECK_ACCU=(temporal_accuracy>=TEST_THRESHHOLD)\n if CHECK_ACCU or CHECK_TEST_FR:\n \n test_step.append(i*queue_len+k)\n if len(test_step)>10:\n e, f=test_step[-1],test_step[-10]\n if e-f<=40:\n TEST_THRESHHOLD+=0.10\n print(\"\\n\"+str(TEST_THRESHHOLD))\n if TEST_THRESHHOLD>0.9800:\n TEST_THRESHHOLD=0.9800\n \n if CHECK_TEST_FR:\n TEST_THRESHHOLD-=0.02\n #TEST_THRESHHOLD=temporal_accuracy-0.005\n t_batch = test_batch(input_dir,output_dir,test_batch_num,batch_size, data_length)\n \n \n f1_list=[]\n for o in range(3):\n ta=sess.run(model.error, feed_dict={x_image: t_batch[o*2], y_: t_batch[o*2+1], keep_prob: 1.0, keep_prob2: 1.0, keep_prob3: 1.0,phase:False})\n FPR_list, TPR_list, PPV_list=ta\n \n f1=float(np.round(np.nanmean(2*np.array(TPR_list)*np.array(PPV_list)/(0.0000001+np.array(PPV_list)+np.array(TPR_list))),4))\n f1_list.append(f1) \n\n\n mean_ac=np.round(np.nanmean(f1_list),4)\n to_print=(\"\\nThis is tests for the model at the train step: \"+str(i*queue_len+k)+\"\\n\"\n +\"mean accuracy : \"+str(mean_ac)\n +\"\\n Total time \"+ str(time.time()-start))\n print(to_print)\n if (prev_ac==None and mean_ac>=SAVE_THRESHHOLD) or (prev_ac!=None and mean_ac>=prev_ac):\n \n flog=open(str(output_dir)+str(start_at)+'.log', 'a')\n flog.write(\"This is tests for the model at the train step: \"+str(i*queue_len+k)+\"\\nThe average of TPR+PPV: \"+str(mean_ac)+'\\n')\n flog.close()\n saver.save(sess, str(output_dir)+str(model_name)+\"_\"+str(start_at)+'_step'+str(i*queue_len+k)+'.ckpt', global_step=i*queue_len+k)\n prev_ac=mean_ac \n \n if mean_ac>=0.999:\n BREAK=True\n break\n #sess.run(model.optimize, feed_dict={x_image: np.concatenate((batch[2],batch[0])),y_: np.concatenate((batch[3],batch[1])), keep_prob: dropout_1, keep_prob2: dropout_2, keep_prob3: dropout_3,phase:True})\n if len(a)==4:\n sess.run(model.optimize, feed_dict={x_image: image_list[k], y_:label_list[k], keep_prob: dropout_1, keep_prob2: dropout_2, keep_prob3: dropout_3,phase:True})\n else:\n sess.run(model.optimize, feed_dict={x_image: batch[2], y_: batch[3], keep_prob: dropout_1, keep_prob2: dropout_2, keep_prob3: dropout_3,phase:True})\n sess.run(model.optimize, feed_dict={x_image: batch[0], y_: batch[1], keep_prob: dropout_1, keep_prob2: dropout_2, keep_prob3: dropout_3,phase:True})\n sess.run(model.optimize, feed_dict={x_image: batch[2], y_: batch[3], keep_prob: dropout_1, keep_prob2: dropout_2, keep_prob3: dropout_3,phase:True})\n sess.run(model.optimize, feed_dict={x_image: batch[0], y_: batch[1], keep_prob: dropout_1, keep_prob2: dropout_2, keep_prob3: dropout_3,phase:True})\n \n if (i*queue_len+k)==loop_num_: # or (i*queue_len+k) >= max_train:\n BREAK=True\n break\n \n saver.save(sess, str(output_dir)+str(model_name)+\"_\"+str(start_at)+\".ckpt\", global_step=i*queue_len+k)\n \n t_batch = test_batch(input_dir,output_dir,test_batch_num,batch_size, data_length) \n f1_list=[]\n for o in range(3):\n ta=sess.run(model.error, feed_dict={x_image: t_batch[o*2], y_: t_batch[o*2+1], keep_prob: 1.0, keep_prob2: 1.0, keep_prob3: 1.0,phase:False})\n FPR_list, TPR_list, PPV_list=ta\n \n f1=float(np.round(np.nanmean(2*np.array(TPR_list)*np.array(PPV_list)/(0.0000001+np.array(PPV_list)+np.array(TPR_list))),4))\n print(f1)\n f1_list.append(f1)\n \n \n current_variable={}\n all_tv=tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)\n for v in all_tv:\n value=sess.run(v)\n scope=v.name\n current_variable[scope]=value\n all_lv=tf.get_collection(tf.GraphKeys.LOCAL_VARIABLES)\n local_variable={}\n for v in all_lv:\n value=sess.run(v)\n scope=v.name\n print(scope)\n local_variable[scope]=value\n all_=tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)\n np.savez(str(output_dir)+str(model_name)+'_trained_variables_'+str(start_at)+'.npz', **current_variable)\n np.savez(str(output_dir)+str(model_name)+'_local_variables_'+str(start_at)+'.npz', **local_variable)\n mean_ac=np.round(np.nanmean(f1_list),4) \n running_time=time.time()-start\n import datetime\n if args is not None:\n _args=args\n else:\n _args=sys.argv\n to_print=(\"dropout parameters: \"+str(dropout_1)+\", \"+str(dropout_2)+\", \"+str(dropout_3)+\"\\n\"\n +\"input directory: \"+str(input_dir)+\"\\n\"\n +\"The average of TPR+PPV: \"+str(np.round(mean_ac,2))\n +\"\\nTotal time \"+ str(datetime.timedelta(seconds=running_time))\n +\"\\nThe model is \"+str(model_name)\n +\"\\nArguments are \"+str(sys.argv[1:])\n +\"\\nGlobal variables: \"+str(all_))\n \n sess.close()\n print(to_print)\n flog=open(str(output_dir)+str(start_at)+'.log', 'a')\n flog.write(to_print+'\\n')\n flog.close()\n \n fit=np.polyfit(total_learing, train_accuracy_record, 1)\n fit_fn=np.poly1d(fit)\n \n plt.figure(1)\n ax1=plt.subplot(211)\n plt.title('Train accuracy')\n plt.plot(total_learing, train_accuracy_record, 'c.', total_learing, fit_fn(total_learing), 'm-')\n ax1.grid(True)\n\n x1,x2,y1,y2 = plt.axis()\n plt.axis((x1,x2,y1,1.0))\n \n plt.figure(1)\n plt.subplot(212)\n plt.title('Cost')\n plt.plot(total_learing,loss_val_record, '-')\n \n \n x1,x2,y1,y2 = plt.axis()\n plt.axis((x1,x2,0,1.0))\n plt.savefig(str(output_dir)+'plot_'+str(start_at)+'.pdf', format='pdf')\n np.savez_compressed(str(output_dir)+str(model_name)+\"_\"+str(start_at)+'_train_rec',total_learing=total_learing, train_accuracy_record=train_accuracy_record,loss_val_record=loss_val_record)\n \n plt.show() \n\n\nif __name__ == '__main__':\n main()\n \n \n \n \n ",
"import numpy as np\nimport sys\n#from curses.ascii import isdigit\nfrom scipy.spatial.distance import cdist\nimport deepgmap.post_train_tools.cython_util as cutil\nmc=cutil.motif_compare\nfrom matplotlib import pyplot as plt \nimport os\ndef _is_number(s):\n try:\n complex(s) # for int, long, float and complex\n except ValueError:\n return False\n\n return True\n\ndef motif_reader(motif_data_dir):\n motif_name=\"\"\n motif_dict={}\n motif_list=[]\n with open(motif_data_dir, 'r') as fin:\n MOTIF=False\n i=0\n for line in fin:\n i+=1\n line=line.split()\n if len(line)==0:\n MOTIF=False\n continue\n elif line[0]==\"MOTIF\":\n if len(motif_name)>0:\n motif_dict[motif_name]=np.array(motif_list)\n \n motif_list=[]\n motif_name=\"\"\n if len(line)>2:\n motif_name=\"_\".join(line[1:])\n else:\n motif_name=line[1]\n \n elif line[0]==\"letter-probability\":\n if line[4]==\"w=\":\n motif_length=int(line[5])\n else:\n print(\"something wrong in line \"+str(i))\n sys.exit()\n MOTIF=True\n elif MOTIF==True:\n #print _is_number(line[0])\n if not _is_number(line[0]):\n MOTIF=False\n continue\n else:\n motif_list.append(map(float, line))\n \n motif_dict[motif_name]=np.array(motif_list)\n return motif_dict\n\n\n\n\ndef motif_compare(motif_data_dict, long_motif_dict, fout, THRESHOLD=-5.0):\n with open(fout, \"w\") as f:\n f.write(\"Motif name\\tStart\\tEnd\\tdistance\\n\")\n for k1, v1 in long_motif_dict.items():\n \n v1shape=v1.shape\n #print v1\n j=0\n for k2, v2 in motif_data_dict.items():\n if \"secondary\" in k2:\n continue\n #print k2\n #j+=1\n #print j\n v2shape=v2.shape\n RAND_DIST=[]\n for i in range(12):\n rand=np.random.rand(v2shape[0],v2shape[1])\n for k in range(v2shape[1]):\n rand[k]=rand[k]/np.sum(rand[k])\n RAND_DIST.append(np.mean(np.diagonal(cdist(v2, rand,metric='cosine'))))\n RAND_MEAN=np.mean(RAND_DIST)\n RAND_DEV=np.std(RAND_DIST)\n #print RAND_MEAN, RAND_DEV\n #print(\"randome_dist: \"+str(RAND_DIST))\n \n \n \n for i in range(v1shape[0]-v2shape[0]):\n partial_motif=v1[i:(i+v2shape[0])]\n #print v2shape, partial_motif.shape\n \"\"\"M=0.5*(partial_motif+v2)+0.00001\n JSD=0.5*(np.sum(-v2*np.log(M/(v2+0.00001)))+np.sum(-partial_motif*np.log(M/(partial_motif+0.00001))))/v2shape[0]\n print JSD\"\"\"\n DIST=np.mean(np.diagonal(cdist(v2, partial_motif,metric='cosine')))\n Z_SCORE=(DIST-RAND_MEAN)/RAND_DEV\n #print Z_SCORE\n if Z_SCORE<=THRESHOLD:\n f.write(str(k2)+\"\\t\"+str(i)+\"\\t\"+str(i+v2shape[0])+\"\\t\"+str(Z_SCORE)+\"\\n\")\n\ndef main():\n motif_data_dir=\"/home/fast/onimaru/data/meme/merged.meme\"\n #long_motif_dir=\"/home/fast/onimaru/deepgmap/data/reconstructions/conv4frss_Fri_May_11_075425_2018.ckpt-16747Tue_May_15_112518_2018_all_.pdf.meme\"\n long_motif_dir=\"/home/fast/onimaru/deepgmap/data/reconstructions/conv4frss_Fri_May_11_075425_2018.ckpt-16747Tue_May_15_104419_2018_es_e14_.pdf.meme\"\n fout=os.path.splitext(long_motif_dir)[0]+\".matches\"\n #fout=\"/home/fast/onimaru/data/output/network_constructor_deepsea_1d3_Fri_Oct_13_133809_2017.ckpt-15899Mon_Oct_16_105338_2017.npz.matches\"\n motif_data_dict=motif_reader(motif_data_dir)\n #print len(motif_data_dict)\n long_motif_dict=motif_reader(long_motif_dir)\n #print len(long_motif_dict)\n #motif_compare(motif_data_dict, long_motif_dict, fout)\n Z_SCORE_list=mc(motif_data_dict, long_motif_dict, fout, THRESHOLD=-5)\n plt.hist(Z_SCORE_list, 1000)\n plt.xticks(np.arange(min(Z_SCORE_list), max(Z_SCORE_list)+1, 1.0))\n plt.show()\n\nif __name__== '__main__':\n main() \n "
] | [
[
"numpy.polyfit",
"numpy.poly1d",
"tensorflow.device",
"matplotlib.pyplot.plot",
"numpy.round",
"numpy.concatenate",
"numpy.nanmean",
"numpy.reshape",
"tensorflow.get_collection",
"tensorflow.ConfigProto",
"matplotlib.pyplot.subplot",
"tensorflow.Session",
"matplotlib.pyplot.axis",
"numpy.load",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"numpy.vsplit",
"tensorflow.placeholder",
"tensorflow.global_variables_initializer",
"matplotlib.pyplot.show",
"numpy.array",
"numpy.sum",
"numpy.shape"
],
[
"numpy.sum",
"scipy.spatial.distance.cdist",
"numpy.std",
"numpy.mean",
"numpy.random.rand",
"numpy.array",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.show"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"0.13",
"1.6",
"0.14",
"1.10",
"0.15",
"1.4",
"0.16",
"1.9",
"0.19",
"1.5",
"0.18",
"1.2",
"1.7",
"0.12",
"1.0",
"0.17",
"1.3",
"1.8"
],
"tensorflow": []
}
] |
zonca/sotodlib | [
"0c64e07ab429e7f0c0e95befeedbaca486d3a414"
] | [
"sotodlib/utils/pipeline_tools/noise.py"
] | [
"# Copyright (c) 2019-2020 Simons Observatory.\n# Full license can be found in the top level \"LICENSE\" file.\n\nimport numpy as np\n\nfrom toast.timing import function_timer, Timer\nfrom toast.tod import AnalyticNoise\nfrom toast.utils import Logger\nimport toast.qarray as qa\n\nfrom ...sim_hardware import get_example\n\n\ndef add_so_noise_args(parser):\n parser.add_argument(\n \"--common-mode-noise\",\n required=False,\n help=\"String defining analytical parameters of a per-tube \"\n \"common mode that is co-added with every detector: \"\n \"'fmin[Hz],fknee[Hz],alpha,NET[K]'\",\n )\n return\n\n\n@function_timer\ndef get_elevation_noise(args, comm, data, key=\"noise\"):\n \"\"\" Insert elevation-dependent noise\n\n \"\"\"\n timer = Timer()\n timer.start()\n # fsample = args.sample_rate\n for obs in data.obs:\n tod = obs[\"tod\"]\n fp = obs[\"focalplane\"]\n noise = obs[key]\n for det in tod.local_dets:\n if det not in noise.keys:\n raise RuntimeError(\n 'Detector \"{}\" does not have a PSD in the noise object'.format(det)\n )\n A = fp[det][\"A\"]\n C = fp[det][\"C\"]\n psd = noise.psd(det)\n try:\n # Some TOD classes provide a shortcut to Az/El\n _, el = tod.read_azel(detector=det)\n except Exception:\n azelquat = tod.read_pntg(detector=det, azel=True)\n # Convert Az/El quaternion of the detector back into\n # angles for the simulation.\n theta, _ = qa.to_position(azelquat)\n el = np.pi / 2 - theta\n el = np.median(el)\n # Scale the analytical noise PSD. Pivot is at el = 50 deg.\n psd[:] *= (A / np.sin(el) + C) ** 2\n timer.stop()\n if comm.world_rank == 0:\n timer.report(\"Elevation noise\")\n return\n\n\n@function_timer\ndef get_analytic_noise(args, comm, focalplane, verbose=True):\n \"\"\" Create a TOAST noise object.\n\n Create a noise object from the 1/f noise parameters contained in the\n focalplane database.\n\n \"\"\"\n timer = Timer()\n timer.start()\n detectors = sorted(focalplane.keys())\n fmins = {}\n fknees = {}\n alphas = {}\n NETs = {}\n rates = {}\n indices = {}\n for d in detectors:\n rates[d] = args.sample_rate\n fmins[d] = focalplane[d][\"fmin\"]\n fknees[d] = focalplane[d][\"fknee\"]\n alphas[d] = focalplane[d][\"alpha\"]\n NETs[d] = focalplane[d][\"NET\"]\n indices[d] = focalplane[d][\"index\"]\n\n if args.common_mode_noise:\n # Add an extra \"virtual\" detector for common mode noise for\n # every optics tube\n fmin, fknee, alpha, net = np.array(args.common_mode_noise.split(\",\")).astype(\n np.float64\n )\n hw = get_example()\n for itube, tube in enumerate(sorted(hw.data[\"tubes\"].keys())):\n d = \"common_mode_{}\".format(tube)\n detectors.append(d)\n rates[d] = args.sample_rate\n fmins[d] = fmin\n fknees[d] = fknee\n alphas[d] = alpha\n NETs[d] = net\n indices[d] = 100000 + itube\n\n noise = AnalyticNoise(\n rate=rates,\n fmin=fmins,\n detectors=detectors,\n fknee=fknees,\n alpha=alphas,\n NET=NETs,\n indices=indices,\n )\n\n if args.common_mode_noise:\n # Update the mixing matrix in the noise operator\n mixmatrix = {}\n keys = set()\n for det in focalplane.keys():\n tube = focalplane[det][\"tube\"]\n common = \"common_mode_{}\".format(tube)\n mixmatrix[det] = {det: 1, common: 1}\n keys.add(det)\n keys.add(common)\n # There should probably be an accessor method to update the\n # mixmatrix in the TOAST Noise object.\n if noise._mixmatrix is not None:\n raise RuntimeError(\"Did not expect non-empty mixing matrix\")\n noise._mixmatrix = mixmatrix\n noise._keys = list(sorted(keys))\n\n timer.stop()\n if comm.world_rank == 0 and verbose:\n timer.report(\"Creating noise model\")\n return noise\n"
] | [
[
"numpy.median",
"numpy.sin"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
xcist/CatSim | [
"4fdd0be26f9915a46a3c3327ed0617328f5ca8b4"
] | [
"reconstruction/fbp_equiAngular/fbp_equiAngular.py"
] | [
"import ctypes as ct\rimport numpy as np\rimport scipy.io as scio\rimport matplotlib.pyplot as plt\r\r# Init ctypes types\rDOUBLE = ct.c_double\rPtrDOUBLE = ct.POINTER(DOUBLE)\rPtrPtrDOUBLE = ct.POINTER(PtrDOUBLE)\r\r\rclass TestStruct(ct.Structure):\r _fields_ = [\r (\"ScanR\", ct.c_double),\r (\"DecFanAng\", ct.c_double),\r (\"YL\", ct.c_int),\r (\"AngleNumber\", ct.c_int),\r (\"Radius\", ct.c_double),\r (\"RecSizeX\", ct.c_int),\r (\"RecSizeY\", ct.c_int),\r (\"centerX\", ct.c_int),\r (\"centerY\", ct.c_int),\r (\"FOILength\", ct.c_int),\r (\"FOIWidth\", ct.c_int),\r (\"GF\", PtrPtrDOUBLE),\r (\"RecIm\", PtrPtrDOUBLE)\r ]\r\r\rdef double2darray2pointer(array):\r # Converts a 2D numpy into a array ctypes 2D array.\r arr_dimx = DOUBLE * array.shape[1]\r arr_dimy = PtrDOUBLE * array.shape[0]\r arr_ptr = arr_dimy()\r\r for i, row in enumerate(array):\r arr_ptr[i] = arr_dimx()\r for j, val in enumerate(row):\r arr_ptr[i][j] = val\r\r return arr_ptr\r\r\rdef double2dpointer2array(ptr, n, m):\r # Converts ctypes 2D array into a 2D numpy array.\r arr = np.zeros(shape=(n, m))\r for i in range(n):\r for j in range(m):\r arr[i][j] = ptr[i][j]\r return arr\r\r\r# Load the compiled library\rrecon = ct.CDLL(\"./fbp_equiAngular.dll\")\r# Define arguments of the C function\rrecon.fbp.argtypes = [ct.POINTER(TestStruct)]\r# Define the return type of the C function\rrecon.fbp.restype = None\r\r# Load the data\rdataFile = './data/Res_Filtering_Angle.mat'\rdata = scio.loadmat(dataFile)\r\r# init the struct\rt = TestStruct()\r\rt.ScanR = data['ScanR']\rt.DecFanAng = data['DecFanAng']\rt.YL = data['YL']\rt.AngleNumber = len(data['GF'])\rt.Radius = data['Radius']\r\r# These are flexible parameters.\rt.RecSizeX = 256\rt.RecSizeY = 256\rt.centerX = 128\rt.centerY = 128\rt.FOILength = 256\rt.FOIWidth = 256\r\r# Generate a 2D ctypes array from numpy array\rGF = data['GF']\rGF = GF.T\rGF_ptr = double2darray2pointer(GF)\rt.GF = GF_ptr\r\rRecIm = np.zeros(shape=(t.FOILength, t.FOIWidth))\rRecIm_ptr = double2darray2pointer(RecIm)\rt.RecIm = RecIm_ptr\r\r# interface with C function\rrecon.fbp(ct.byref(t))\r\r# Convert ctypes 2D arrays to numpy arrays\rRecA = double2dpointer2array(RecIm_ptr, *RecIm.shape)\rRecA = RecA.T\r\r# save result\rdataNew = './data/Res_equiAngular.mat'\rscio.savemat(dataNew,\r {'Rec': RecA})\rplt.figure()\rplt.imshow(RecA, cmap='gray')\rplt.show()\r"
] | [
[
"matplotlib.pyplot.imshow",
"scipy.io.loadmat",
"scipy.io.savemat",
"matplotlib.pyplot.show",
"numpy.zeros",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
}
] |
antsfamily/pysparse | [
"1de292f3e9c6d81950656b9405d4d87ef746d950"
] | [
"tests/test_omp_sin3.py"
] | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2017-07-06 10:38:13\n# @Author : Yan Liu & Zhi Liu ([email protected])\n# @Link : http://iridescent.ink\n# @Version : $1.0$\n#\n\nimport numpy as np\nimport pysparse as pys\nimport matplotlib.pyplot as plt\n\nFs = 2000\nTs = 1\nNs = int(Ts * Fs)\n\nf1 = 100\nf2 = 200\nf3 = 700\n\nt = np.linspace(0, Ts, Ns)\n\nxo = np.sin(2 * np.pi * f1 * t) + np.sin(2 * np.pi * f2 * t) + \\\n np.sin(2 * np.pi * f3 * t)\n\nx = np.abs(np.fft.fftshift(np.fft.fft(xo)))\nf = np.linspace(-Fs / 2, Fs / 2, Ns)\n\nCR = 4\n\nk1 = 2\nk2 = 4\nk3 = 6\nk4 = 100\n\nalpha = 0.0\nN = np.size(x)\nM = int(N / CR)\nA = pys.gaussian((M, N))\n# A = np.ones((M, N))\ny = np.matmul(A, x)\n\nx1 = pys.romp(y, A, k=k1, alpha=alpha, verbose=False)\n\nx2 = pys.romp(y, A, k=k2, alpha=alpha, verbose=False)\n\nx3 = pys.romp(y, A, k=k3, alpha=alpha, verbose=False)\n\nx4 = pys.romp(y, A, k=k4, alpha=alpha, verbose=False)\n\nprint(\"---MSE(x, x1) with k = \" + str(k1) + \": \", pys.mse(x, x1))\nprint(\"---MSE(x, x2) with k = \" + str(k2) + \": \", pys.mse(x, x2))\nprint(\"---MSE(x, x3) with k = \" + str(k3) + \": \", pys.mse(x, x3))\nprint(\"---MSE(x, x4) with k = \" + str(k4) + \": \", pys.mse(x, x4))\n\nplt.figure()\nplt.subplot(121)\nplt.plot(t, xo)\nplt.xlabel('Time/s')\nplt.ylabel('Amplitude')\nplt.title('Orignal Signal (Time domain)')\nplt.grid()\n\nplt.subplot(122)\nplt.plot(f, x)\nplt.xlabel('Frequency/Hz')\nplt.ylabel('Amplitude')\nplt.title('Orignal Signal (frequency domain)')\nplt.grid()\nplt.tight_layout()\nplt.show()\n\nplt.figure()\nplt.subplot(221)\nplt.plot(f, x1)\nplt.xlabel('Frequency/Hz')\nplt.ylabel('Amplitude')\nplt.title('Reconstructed Signal (k=' + str(k1) + ')')\nplt.grid()\n\nplt.subplot(222)\nplt.plot(f, x2)\nplt.xlabel('Frequency/Hz')\nplt.ylabel('Amplitude')\nplt.title('Reconstructed Signal (k=' + str(k2) + ')')\nplt.grid()\n\nplt.subplot(223)\nplt.plot(f, x3)\nplt.xlabel('Frequency/Hz')\nplt.ylabel('Amplitude')\nplt.title('Reconstructed Signal (k=' + str(k3) + ')')\nplt.grid()\n\nplt.subplot(224)\nplt.plot(f, x4)\nplt.xlabel('Frequency/Hz')\nplt.ylabel('Amplitude')\nplt.title('Reconstructed Signal (k=' + str(k4) + ')')\nplt.grid()\nplt.tight_layout()\nplt.show()\n"
] | [
[
"matplotlib.pyplot.tight_layout",
"numpy.linspace",
"matplotlib.pyplot.title",
"numpy.fft.fft",
"numpy.matmul",
"numpy.sin",
"matplotlib.pyplot.plot",
"numpy.size",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
EsauPR/3d-pose-baseline | [
"2f521fe3008ddee81b666550606f7405efd2f547",
"2f521fe3008ddee81b666550606f7405efd2f547"
] | [
"src/3d_pose_vae_filter_kin.py",
"src/vae_filter.py"
] | [
"\"\"\" Train a VAE model used to filter and enhance 3d points \"\"\"\n\nimport json\nfrom datetime import datetime\n\nimport matplotlib\nimport matplotlib.gridspec as gridspec\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\n\nfrom tqdm import tqdm\n\nimport cameras\nimport data_utils\nimport viz\nfrom top_vae_3d_pose import data_handler, losses, models\nfrom top_vae_3d_pose.args_def import ENVIRON as ENV\n\nmatplotlib.use('Agg')\n# matplotlib.use('TkAgg')\n\n# tf.debugging.set_log_device_placement(True)\n\n\ndef to_world(points_3d, key3d, root_pos):\n \"\"\" Trasform coordenates from camera to world coordenates \"\"\"\n _, _, rcams = data_handler.get_data_params()\n n_cams = 4\n n_joints_h36m = 32\n\n # Add global position back\n points_3d = points_3d + np.tile(root_pos, [1, n_joints_h36m])\n\n # Load the appropriate camera\n # key3d = data_handler.get_key3d(key2d)\n subj, _, sname = key3d\n subj = int(subj)\n\n cname = sname.split('.')[1] # <-- camera name\n scams = {(subj, c+1): rcams[(subj, c+1)] for c in range(n_cams)} # cams of this subject\n scam_idx = [scams[(subj, c+1)][-1] for c in range(n_cams)].index(cname) # index of camera used\n the_cam = scams[(subj, scam_idx+1)] # <-- the camera used\n R, T, f, c, k, p, name = the_cam\n assert name == cname\n\n def cam2world_centered(data_3d_camframe):\n data_3d_worldframe = cameras.camera_to_world_frame(data_3d_camframe.reshape((-1, 3)), R, T)\n data_3d_worldframe = data_3d_worldframe.reshape((-1, n_joints_h36m*3))\n # subtract root translation\n return data_3d_worldframe - np.tile(data_3d_worldframe[:, :3], (1, n_joints_h36m))\n\n # Apply inverse rotation and translation\n return cam2world_centered(points_3d)\n\n\ndef gen_sample_img(dataset, model=None, idx=None):\n \"\"\" Plot 3d poses, real, with noise and decode from vae model if a model is provided\n pass 'idx' to select samples otherwise idx will be randomly generated\n \"\"\"\n # select random samples\n nsamples = 15\n if idx is None:\n idx = np.random.choice(dataset.x_data.shape[0], nsamples, replace=False)\n\n x_in = dataset.x_data[idx, :]\n y_real = dataset.y_data[idx, :]\n y_out = model(x_in.reshape(x_in.shape[0], x_in.shape[1] * x_in.shape[2]), training=False)\n\n # unnormalize data\n x_in = [data_utils.unNormalizeData(p3d,\n dataset.x_metadata.mean,\n dataset.x_metadata.std,\n dataset.x_metadata.dim_ignored) for p3d in x_in]\n\n y_real = data_utils.unNormalizeData(y_real,\n dataset.y_metadata.mean,\n dataset.y_metadata.std,\n dataset.y_metadata.dim_ignored)\n y_out = data_utils.unNormalizeData(y_out,\n dataset.y_metadata.mean,\n dataset.y_metadata.std,\n dataset.y_metadata.dim_ignored)\n\n if ENV.FLAGS.camera_frame:\n keys3d = dataset.mapkeys[idx, :]\n root_pos = dataset.y_metadata.root_positions[idx, :]\n\n x_in = np.array([to_world(p3d,\n keys3d[i],\n root_pos[i])\n for i, p3d in enumerate(x_in)])\n y_real = np.array([to_world(p3d.reshape((1, -1)), keys3d[i],\n root_pos[i][-1].reshape((1, 3)))[0]\n for i, p3d in enumerate(y_real)])\n y_out = np.array([to_world(p3d.reshape((1, -1)), keys3d[i],\n root_pos[i][-1].reshape((1, 3)))[0]\n for i, p3d in enumerate(y_out)])\n\n # 1080p\t= 1,920 x 1,080\n fig = plt.figure(figsize=(19.2, 10.8))\n\n gs1 = gridspec.GridSpec(5, 6*3) # 5 rows, 18 columns\n gs1.update(wspace=-0.00, hspace=0.05) # set the spacing between axes.\n plt.axis('off')\n\n subplot_idx, exidx = 0, 0\n for _ in np.arange(nsamples):\n # Sequence\n for pt3d in x_in[exidx]:\n # Plot 3d gt\n ax2 = plt.subplot(gs1[subplot_idx], projection='3d')\n p3d = pt3d\n viz.show3Dpose(p3d, ax2)\n subplot_idx += 1\n\n # Plot 3d predictions\n ax3 = plt.subplot(gs1[subplot_idx], projection='3d')\n p3d = y_out[exidx, :]\n viz.show3Dpose(p3d, ax3, lcolor=\"#9b59b6\", rcolor=\"#2ecc71\")\n subplot_idx += 1\n\n # Plot 3d real\n ax4 = plt.subplot(gs1[subplot_idx], projection='3d')\n p3d = y_real[exidx, :]\n viz.show3Dpose(p3d, ax4, lcolor=\"#9b59b6\", rcolor=\"#2ecc71\")\n subplot_idx += 1\n\n exidx = exidx + 1\n\n file_name = \"imgs/vae_concat_seq/%s.png\" % datetime.utcnow().isoformat()\n plt.savefig(file_name)\n print(\"Saved samples on: %s\" % file_name)\n # plt.show()\n plt.close()\n\n\ndef get_optimizer():\n \"\"\" Returns the optimizer required by flags \"\"\"\n if ENV.FLAGS.optimizer == 'adam':\n return tf.keras.optimizers.Adam(ENV.FLAGS.learning_rate)\n if ENV.FLAGS.optimizer == 'rmsprop':\n return tf.keras.optimizers.RMSprop(ENV.FLAGS.learning_rate)\n raise Exception('Optimizer not found: %s' % ENV.FLAGS.optimizer)\n\n\[email protected]\ndef train_step_vae(model, x_data, y_data, optimizer):\n \"\"\" Define a train step \"\"\"\n with tf.GradientTape() as tape:\n loss = losses.ELBO.compute_loss(model, x_data, y_data)\n gradients = tape.gradient(loss, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n\n return loss\n\n\ndef train():\n \"\"\" Train function \"\"\"\n data_train, data_test = data_handler.load_dataset_3d_seq(seq_len=3)\n print(\"Dataset dims\")\n print(data_train.x_data.shape, data_train.y_data.shape)\n print(data_test.x_data.shape, data_test.y_data.shape)\n\n seq_len, size = data_train.x_data[0].shape\n # The Vae model must process the seq as a single concatenate input\n model = models.VAE(seq_len*size,\n latent_dim=ENV.FLAGS.latent_dim,\n enc_dim=ENV.FLAGS.enc_dim,\n dec_dim=ENV.FLAGS.dec_dim)\n\n optimizer = get_optimizer()\n\n ckpt = tf.train.Checkpoint(step=tf.Variable(1), optimizer=optimizer, net=model)\n manager = tf.train.CheckpointManager(ckpt, './experiments/vae_concat_seq/tf_ckpts', max_to_keep=3)\n ckpt.restore(manager.latest_checkpoint)\n if manager.latest_checkpoint:\n print(\"Restaurado de {}\".format(manager.latest_checkpoint))\n else:\n print(\"Inicializando desde cero.\")\n\n\n print(\"Trainable weights:\", len(model.trainable_weights))\n\n # Indexes for sampling\n idx = np.random.choice(data_test.x_data.shape[0], 15, replace=False)\n\n # Logs for errors and losses\n\n loss_train_history = []\n loss_test_history = []\n pred_error_history = []\n error_34_history = []\n error_3_pred_history = []\n\n for epoch in range(1, ENV.FLAGS.epochs + 1):\n print(\"\\nStarting epoch:\", epoch)\n\n loss_train = tf.keras.metrics.Mean()\n # start_time = time.time()\n for step, (x_train, y_train) in enumerate(tqdm(data_train, ascii=True)):\n # x_train is a batch of seq of dimentions (batch_size, seq_len, input_size)\n batch_size, seq_len, size = x_train.shape\n x_train = x_train.reshape(batch_size, seq_len * size)\n x_train = data_handler.add_noise(x_train)\n\n step_loss = train_step_vae(model, x_train, y_train, optimizer)\n loss_train(step_loss)\n if step % ENV.FLAGS.step_log == 0:\n ltp = tf.math.reduce_mean(step_loss)\n tqdm.write(\" Training loss at step %d: %.4f\" % (step, ltp))\n tqdm.write(\" Seen : %s samples\" % ((step + 1) * ENV.FLAGS.batch_size))\n # end_time = time.time()\n loss_train_history.append(loss_train.result())\n\n print(\"Evaluation on Test data...\")\n loss_test = tf.keras.metrics.Mean()\n pred_error = tf.keras.metrics.Mean()\n error_34 = tf.keras.metrics.Mean()\n error_3_pred = tf.keras.metrics.Mean()\n error_2_pred = tf.keras.metrics.Mean()\n error_1_pred = tf.keras.metrics.Mean()\n\n for x_test, y_test in tqdm(data_test, ascii=True):\n # x_test is a batch of seq of dimentions (batch_size, seq_len, input_size)\n batch_size, seq_len, size = x_test.shape\n y_test = x_test[:, 2, :]\n x_test3 = x_test[:, 1, :]\n x_test2 = x_test[:, 0, :]\n # x_test1 = x_test[:, 0, :]\n x_test = x_test.reshape(batch_size, seq_len * size)\n loss_test(losses.ELBO.compute_loss(model, x_test, y_test))\n preds = model(x_test, training=False)\n pred_error(losses.ELBO.compute_pred_error(y_test, preds))\n error_34(losses.ELBO.compute_pred_error(x_test3, y_test))\n error_3_pred(losses.ELBO.compute_pred_error(x_test3, preds))\n error_2_pred(losses.ELBO.compute_pred_error(x_test2, preds))\n # error_1_pred(losses.ELBO.compute_pred_error(x_test1, preds))\n loss_test_history.append(loss_test.result())\n pred_error_history.append(pred_error.result())\n error_34_history.append(error_34.result())\n error_3_pred_history.append(error_3_pred.result())\n\n print('Epoch: {}, Test set ELBO: {}'.format(epoch, loss_test_history[-1]))\n print('Epoch: {}, Error frame 2 vs 3: {}'.format(epoch, error_34_history[-1]))\n print('Epoch: {}, Prediction Error: {}'.format(epoch, pred_error_history[-1]))\n print('Epoch: {}, Error frame 2 vs pred: {}'.format(epoch, error_3_pred_history[-1]))\n print('Epoch: {}, Error frame 1 vs pred: {}'.format(epoch, error_2_pred.result()))\n # print('Epoch: {}, Error frame 1 vs pred: {}'.format(epoch, error_1_pred.result()))\n\n tf.print('\\nSaving samples...')\n gen_sample_img(data_test, model=model, idx=idx)\n\n # Reset data for next epoch\n data_train.on_epoch_end()\n data_test.on_epoch_end(avoid_suffle=True)\n\n ckpt.step.assign_add(1)\n save_path = manager.save()\n print(\"Checkpoint saved: {}\".format(save_path))\n\n data_handler.plot_history([('Train Loss', loss_train_history),\n ('Test Loss', loss_test_history)],\n xlabel='Epochs',\n ylabel='Loss',\n fname='loss.png')\n data_handler.plot_history([('Pred error', pred_error_history),\n # ('Frame err 4vs5', error_34_history),\n ('Frame err 4vsPred', error_3_pred_history)],\n xlabel='Epochs',\n ylabel='Error',\n fname='error.png')\n\n # Save the weights of the las model and the config use to run and train\n model.save_weights('./experiments/vae_concat_seq/last_model_weights')\n with open('./experiments/vae_concat_seq/train.cfg', 'w') as cfg:\n json.dump(vars(ENV.FLAGS), cfg)\n\n data_handler.save_history(loss_train_history, 'train_loss.npy')\n data_handler.save_history(loss_test_history, 'test_loss.npy')\n\n\n\n\ndef evaluate():\n data2d, data3d = data_handler.load_2d_3d_data(return_raw=True)\n\n model_2d23d = models.PoseBase()\n # Dummy input for creation for bach normalization weigths\n ainput = np.ones((10, 32), dtype=np.float32)\n model_2d23d(ainput, training=False)\n # Load weights for 2d to 3d prediction\n model_2d23d.load_weights('pretrained_models/4874200_PoseBase/PoseBase')\n\n # Load VAE Model\n seq_len = 3\n human_3d_size = 48\n model_vae_kin = models.VAE(seq_len*human_3d_size,\n latent_dim=ENV.FLAGS.latent_dim,\n enc_dim=ENV.FLAGS.enc_dim,\n dec_dim=ENV.FLAGS.dec_dim)\n model_vae_kin.load_weights('experiments/vae_concat_seq/last_model_weights')\n\n error_2d_3d = tf.keras.metrics.Mean()\n error_vae_kin = tf.keras.metrics.Mean()\n noise_log = []\n\n for key2d in tqdm(data2d.test.keys(), ascii=True):\n err23d = tf.keras.metrics.Mean()\n errvk = tf.keras.metrics.Mean()\n\n tqdm.write(\"Subject: {}, action: {}, fname: {}\".format(*key2d))\n\n key3d = data_handler.get_key3d(key2d)\n\n x_in = data2d.test[key2d]\n x_out = data3d.test[key3d]\n\n # Make a batch of size x.shape[0] to start the generation of the buffer\n x_in = np.array_split(x_in, x_in.shape[0])\n x_out = np.array_split(x_out, x_out.shape[0])\n\n buffer = []\n\n for x_2d, y_3d in tqdm(zip(x_in, x_out), total=len(x_in), ascii=True):\n pred_3d = model_2d23d(x_2d, training=False)\n\n if len(buffer) == 0:\n # Start the buffer with the same predicion\n buffer = [pred_3d[0] for _ in range(seq_len)]\n\n buffer.append(pred_3d[0])\n buffer.pop(0)\n\n # print(pred_3d.shape)\n # print(buffer)\n # print(len(buffer))\n vin = np.array([np.concatenate(buffer)])\n ref_3d = model_vae_kin(vin, training=False)\n\n # Add the last ref to the buffer\n buffer[-1] = ref_3d[0]\n\n err1 = losses.ELBO.compute_pred_error(y_3d, pred_3d)\n err2 = losses.ELBO.compute_pred_error(y_3d, ref_3d)\n err23d(err1)\n errvk(err2)\n error_2d_3d(err1)\n error_vae_kin(err2)\n\n noise_log.append(err1)\n\n tqdm.write(\"Err 2d-3d: {}, VAE: {}\".format(err23d.result(), errvk.result()))\n\n print(\"Pred error 2d to 3d:\", error_2d_3d.result())\n print(\"Pred error vae filter:\", error_vae_kin.result())\n\n print(tf.math.reduce_mean(noise_log))\n print(tf.math.reduce_std(noise_log))\n print(tf.math.reduce_min(noise_log))\n print(tf.math.reduce_max(noise_log))\n\n\n\n\ndef main():\n \"\"\" Main \"\"\"\n with tf.device('/device:GPU:%d' % ENV.FLAGS.gpu_device):\n if ENV.FLAGS.evaluate:\n evaluate()\n else:\n train()\n\n\nif __name__ == \"__main__\":\n ENV.setup()\n main()\n",
"\"\"\" Train a VAE model used to filter and enhance 3d points \"\"\"\n\nimport json\nimport time\nfrom datetime import datetime\n\nimport matplotlib\nimport matplotlib.gridspec as gridspec\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\n\nimport data_utils\nimport viz\nfrom top_vae_3d_pose import data_handler, losses, models\nfrom top_vae_3d_pose.args_def import ENVIRON as ENV\n\nmatplotlib.use('Agg')\n# matplotlib.use('TkAgg')\n\n\ndef gen_sample_img(real_points, noised_points, mean, std, dim_ignored, model=None, idx=None):\n \"\"\" Plot 3d poses, real, with noise and decode from vae model if a model is provided\n pass 'idx' to select samples otherwise idx will be randomly generated\n \"\"\"\n # select random samples\n nsamples = 9\n if idx is None:\n idx = np.random.choice(real_points.shape[0], nsamples, replace=False)\n real_points = real_points[idx, :]\n noised_points = noised_points[idx, :]\n\n # Use the model to generate new samples or use the noised samples provided\n if model is not None:\n z = model.reparametrize(*model.encode(noised_points))\n if ENV.FLAGS.f_loss == 'xent':\n pred_points = model.decode(z).numpy()\n else:\n pred_points = model.decode(z).numpy()\n\n\n # unnormalioze data\n real_points = data_utils.unNormalizeData(real_points, mean, std, dim_ignored)\n noised_points = data_utils.unNormalizeData(noised_points, mean, std, dim_ignored)\n if model is not None:\n pred_points = data_utils.unNormalizeData(pred_points, mean, std, dim_ignored)\n\n # Make athe plot and save the fig\n fig = plt.figure(figsize=(19.2, 10.8))\n # fig = plt.figure(figsize=(10.24, 7.48))\n if model is None:\n gs1 = gridspec.GridSpec(3, 6) # 5 rows, 9 columns\n else:\n gs1 = gridspec.GridSpec(3, 9) # 5 rows, 9 columns\n gs1.update(wspace=-0.00, hspace=0.05) # set the spacing between axes.\n plt.axis('off')\n\n subplot_idx, exidx = 1, 1\n for _ in np.arange(nsamples):\n # Plot 3d predictions\n ax3 = plt.subplot(gs1[subplot_idx-1], projection='3d')\n p3d = real_points[exidx-1, :]\n # print('3D points', p3d)\n viz.show3Dpose(p3d, ax3, lcolor=\"#9b59b6\", rcolor=\"#2ecc71\")\n\n ax3 = plt.subplot(gs1[subplot_idx], projection='3d')\n p3d = noised_points[exidx-1, :]\n # print('3D points', p3d)\n viz.show3Dpose(p3d, ax3, lcolor=\"#9b59b6\", rcolor=\"#2ecc71\")\n\n if model is not None:\n ax3 = plt.subplot(gs1[subplot_idx+1], projection='3d')\n p3d = pred_points[exidx-1, :]\n # print('3D points', p3d)\n viz.show3Dpose(p3d, ax3, lcolor=\"#9b59b6\", rcolor=\"#2ecc71\")\n\n exidx = exidx + 1\n if model is None:\n subplot_idx = subplot_idx + 2\n else:\n subplot_idx = subplot_idx + 3\n\n # plt.show()\n if ENV.FLAGS.noised_sample:\n file_name = \"imgs/vae/noised_%f_%f.png\" % (ENV.FLAGS.noise_3d[0], ENV.FLAGS.noise_3d[1])\n else:\n file_name = \"imgs/vae/%s.png\" % datetime.utcnow().isoformat()\n plt.savefig(file_name)\n print(\"Saved samples on: %s\" % file_name)\n # plt.show()\n plt.close()\n\n\ndef plot_history(train_loss, test_loss, error_pred, error_noised):\n \"\"\" Plot the train vs test loss and prediction error vs noised error through the epochs \"\"\"\n x_data = np.arange(len(train_loss)) + 1\n\n plt.figure(figsize=(12, 6))\n plt.plot(x_data, train_loss)\n plt.plot(x_data, test_loss)\n plt.xlabel('epoch')\n plt.ylabel('loss')\n plt.legend([\"Train loss\", \"Test loss\"])\n plt.savefig('imgs/vae/0_loss.png')\n plt.close()\n\n plt.figure(figsize=(12, 6))\n plt.plot(x_data, error_pred)\n plt.plot(x_data, error_noised)\n plt.xlabel('epoch')\n plt.ylabel('error')\n plt.legend([\"Error pred\", \"Error noised\"])\n plt.savefig('imgs/vae/0_error.png')\n plt.close()\n\n\ndef get_optimizer():\n \"\"\" Returns the optimizer required by flags \"\"\"\n if ENV.FLAGS.optimizer == 'adam':\n return tf.keras.optimizers.Adam(ENV.FLAGS.learning_rate)\n if ENV.FLAGS.optimizer == 'rmsprop':\n return tf.keras.optimizers.RMSprop(ENV.FLAGS.learning_rate)\n raise Exception('Optimizer not found: %s' % ENV.FLAGS.optimizer)\n\n\[email protected]\ndef train_step(model, x_noised, x_truth, optimizer):\n \"\"\" Define a train step \"\"\"\n with tf.GradientTape() as tape:\n loss = losses.ELBO.compute_loss(model, x_noised, x_truth)\n gradients = tape.gradient(loss, model.trainable_variables)\n optimizer.apply_gradients(zip(gradients, model.trainable_variables))\n return loss\n\n\ndef train():\n \"\"\" Train function \"\"\"\n data_train, data_test = data_handler.load_3d_data()\n print(\"Dataset dims\")\n print(data_train.data.shape, data_test.data.shape)\n\n model = models.VAE(data_train.data.shape[1],\n latent_dim=ENV.FLAGS.vae_dim[-1],\n inter_dim=ENV.FLAGS.vae_dim[:-1])\n optimizer = get_optimizer()\n\n ckpt = tf.train.Checkpoint(step=tf.Variable(1), optimizer=optimizer, net=model)\n manager = tf.train.CheckpointManager(ckpt, './experiments/vae/tf_ckpts', max_to_keep=3)\n ckpt.restore(manager.latest_checkpoint)\n if manager.latest_checkpoint:\n print(\"Restaurado de {}\".format(manager.latest_checkpoint))\n else:\n print(\"Inicializando desde cero.\")\n\n\n # Indexes for sampling\n idx = np.random.choice(data_test.data.shape[0], 9, replace=False)\n\n # Logs for errors and losses\n error_pred_history = []\n error_noised_history = []\n loss_train_history = []\n loss_test_history = []\n\n for epoch in range(1, ENV.FLAGS.epochs + 1):\n print(\"\\nStarting epoch:\", epoch)\n\n\n loss_train = tf.keras.metrics.Mean()\n start_time = time.time()\n for step, (x_noised, x_truth) in enumerate(data_train):\n step_loss = train_step(model, x_noised, x_truth, optimizer)\n loss_train(step_loss)\n if step % ENV.FLAGS.step_log == 0:\n print(\" Training loss at step %d: %.4f\" % (step, tf.math.reduce_mean(step_loss)))\n print(\" Seen : %s samples\" % ((step + 1) * ENV.FLAGS.batch_size))\n end_time = time.time()\n loss_train_history.append(loss_train.result())\n\n loss_test = tf.keras.metrics.Mean()\n error_pred = tf.keras.metrics.Mean()\n error_noised = tf.keras.metrics.Mean()\n for x_noised, x_truth in data_test:\n loss_test(losses.ELBO.compute_loss(model, x_noised, x_truth))\n\n err_n, err_p = losses.ELBO.compute_pred_error(x_noised, x_truth), \\\n losses.ELBO.compute_pred_error(model(x_noised, training=False), x_truth)\n\n error_pred(err_p)\n error_noised(err_n)\n loss_test_history.append(loss_test.result())\n error_pred_history.append(error_pred.result())\n error_noised_history.append(error_noised.result())\n\n print('Epoch: {}, Test set ELBO: {}, time elapse for current epoch: {}'.format(epoch, loss_test_history[-1], end_time - start_time))\n tf.print('Error real vs noised:', error_noised_history[-1])\n tf.print('Error real vs pred:', error_pred_history[-1])\n tf.print('\\nSaving samples...')\n gen_sample_img(data_test.data, data_test.data_noised,\n data_test.metadata.mean, data_test.metadata.std,\n data_test.metadata.dim_ignored,\n model=model, idx=idx)\n\n # Reset data for next epoch\n data_train.on_epoch_end(new_noise=True)\n data_test.on_epoch_end(new_noise=True)\n\n ckpt.step.assign_add(1)\n save_path = manager.save()\n print(\"Checkpoint saved: {}\".format(save_path))\n\n plot_history(loss_train_history, loss_test_history,\n error_pred_history, error_noised_history)\n\n # Save the weights of the las model and the config use to run and train\n model.save_weights('./experiments/vae/last_model_weights')\n with open('./experiments/vae/train.cfg', 'w') as cfg:\n json.dump(vars(ENV.FLAGS), cfg)\n\n\n\ndef main():\n if ENV.FLAGS.noised_sample:\n # Generate a sample of data with noise\n\n data_train, data_test = data_handler.load_3d_data()\n print(\"Dataset dims\")\n print(data_train.data.shape, data_test.data.shape)\n\n gen_sample_img(data_test.data, data_test.data_noised,\n data_test.metadata.mean, data_test.metadata.std,\n data_test.metadata.dim_ignored,\n idx=np.random.choice(data_test.data.shape[0], 9, replace=False))\n else:\n with tf.device('/device:GPU:2'):\n train()\n\n\nif __name__ == \"__main__\":\n ENV.setup()\n main()\n"
] | [
[
"tensorflow.device",
"numpy.concatenate",
"tensorflow.Variable",
"numpy.arange",
"tensorflow.keras.optimizers.RMSprop",
"matplotlib.pyplot.subplot",
"matplotlib.gridspec.GridSpec",
"matplotlib.pyplot.close",
"matplotlib.pyplot.axis",
"tensorflow.keras.metrics.Mean",
"matplotlib.pyplot.figure",
"tensorflow.train.CheckpointManager",
"numpy.random.choice",
"tensorflow.math.reduce_max",
"matplotlib.pyplot.savefig",
"tensorflow.math.reduce_std",
"tensorflow.print",
"tensorflow.GradientTape",
"tensorflow.math.reduce_min",
"matplotlib.use",
"numpy.tile",
"tensorflow.math.reduce_mean",
"numpy.ones",
"tensorflow.keras.optimizers.Adam",
"numpy.array_split"
],
[
"matplotlib.pyplot.legend",
"tensorflow.device",
"matplotlib.pyplot.plot",
"tensorflow.Variable",
"numpy.arange",
"tensorflow.keras.optimizers.RMSprop",
"matplotlib.pyplot.subplot",
"matplotlib.gridspec.GridSpec",
"matplotlib.pyplot.close",
"matplotlib.pyplot.axis",
"tensorflow.keras.metrics.Mean",
"matplotlib.pyplot.figure",
"tensorflow.train.CheckpointManager",
"numpy.random.choice",
"matplotlib.pyplot.savefig",
"tensorflow.print",
"matplotlib.pyplot.ylabel",
"tensorflow.GradientTape",
"matplotlib.use",
"tensorflow.math.reduce_mean",
"tensorflow.keras.optimizers.Adam",
"matplotlib.pyplot.xlabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
qpwodlsqp/torchdyn | [
"aa26dc0ea22acedfce6744f0bff10f551d175a2f"
] | [
"test/test_normalizing_flows.py"
] | [
"import torch\nimport torch.nn as nn\nfrom torch.distributions import MultivariateNormal\nfrom torchdyn.models import NeuralODE\nfrom torchdyn import Augmenter\nfrom torchdyn.models.cnf import CNF, hutch_trace, autograd_trace\n\n\ndef test_cnf_vanilla():\n device = torch.device('cpu')\n net = nn.Sequential(\n nn.Linear(2, 512),\n nn.ELU(),\n nn.Linear(512, 2)\n )\n defunc = CNF(net)\n nde = NeuralODE(defunc, solver='dopri5', s_span=torch.linspace(0, 1, 2), atol=1e-5, rtol=1e-5, sensitivity='adjoint')\n model = nn.Sequential(Augmenter(augment_idx=1, augment_dims=1),\n nde).to(device)\n x = torch.randn((512, 2)).to(device)\n out = model(x)\n assert out.shape[1] == x.shape[1] + 1\n\ndef test_hutch_vanilla():\n device = torch.device('cpu')\n net = nn.Sequential(\n nn.Linear(2, 512),\n nn.ELU(),\n nn.Linear(512, 2)\n )\n noise_dist = MultivariateNormal(torch.zeros(2).to(device), torch.eye(2).to(device))\n defunc = nn.Sequential(CNF(net, trace_estimator=hutch_trace, noise_dist=noise_dist))\n\n nde = NeuralODE(defunc, solver='dopri5', s_span=torch.linspace(0, 1, 2), atol=1e-5, rtol=1e-5, sensitivity='adjoint')\n model = nn.Sequential(Augmenter(augment_idx=1, augment_dims=1),\n nde).to(device)\n x = torch.randn((512, 2)).to(device)\n out = model(x)\n assert out.shape[1] == x.shape[1] + 1\n\ndef test_hutch_estimator_gauss_noise():\n noise_dist = MultivariateNormal(torch.zeros(2), torch.eye(2))\n x_in = torch.randn((64, 2), requires_grad=True)\n m = nn.Sequential(nn.Linear(2, 32), nn.Softplus(), nn.Linear(32, 2))\n x_out = m(x_in)\n trJ = autograd_trace(x_out, x_in)\n hutch_trJ = torch.zeros(trJ.shape)\n for i in range(10000):\n x_out = m(x_in)\n eps = noise_dist.sample((64,))\n hutch_trJ += hutch_trace(x_out, x_in, noise=eps)\n assert (hutch_trJ / 10000 - trJ < 1e-1).all()\n"
] | [
[
"torch.linspace",
"torch.nn.Softplus",
"torch.zeros",
"torch.randn",
"torch.nn.ELU",
"torch.eye",
"torch.nn.Linear",
"torch.device"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
BAMresearch/probeye | [
"ff018ef629f7d5ce4a263b6656b363f90ab6be02"
] | [
"tests/unit_tests/inference/dynesty_/test_solver.py"
] | [
"# standard library\nimport logging\nimport unittest\n\n# third party imports\nimport numpy as np\n\n# local imports\nfrom probeye.definition.forward_model import ForwardModelBase\nfrom probeye.definition.sensor import Sensor\nfrom probeye.definition.inference_problem import InferenceProblem\nfrom probeye.definition.noise_model import NormalNoiseModel\nfrom probeye.inference.dynesty_.solver import DynestySolver\n\n\nclass TestProblem(unittest.TestCase):\n def test_dynesty_solver(self):\n\n np.random.seed(6174)\n\n # define the forward model\n class LinRe(ForwardModelBase):\n def __call__(self, inp):\n x = inp[\"x\"]\n a = inp[\"a\"]\n b = inp[\"b\"]\n return {\"y\": a * x + b}\n\n # set up the problem\n problem = InferenceProblem(\"Linear regression\")\n problem.add_parameter(\"a\", \"model\", prior=(\"normal\", {\"loc\": 0, \"scale\": 1}))\n problem.add_parameter(\"b\", \"model\", prior=(\"normal\", {\"loc\": 0, \"scale\": 1}))\n problem.add_parameter(\n \"sigma\", \"noise\", prior=(\"uniform\", {\"low\": 0.1, \"high\": 1})\n )\n problem.add_forward_model(\n \"LinRe\", LinRe([\"a\", \"b\"], [Sensor(\"x\")], [Sensor(\"y\")])\n )\n problem.add_noise_model(NormalNoiseModel({\"sigma\": \"std\"}, sensors=Sensor(\"y\")))\n\n # generate and add some simple test data\n n_tests = 5000\n true = {\"a\": 0.3, \"b\": -0.2, \"sigma\": 0.1}\n x_test = np.linspace(0.0, 1.0, n_tests)\n y_true = true[\"a\"] * x_test + true[\"b\"]\n y_test = np.random.normal(loc=y_true, scale=true[\"sigma\"])\n problem.add_experiment(\n f\"Tests\", fwd_model_name=\"LinRe\", sensor_values={\"x\": x_test, \"y\": y_test}\n )\n\n # run the dynesty solver with deactivated output\n logging.root.disabled = True\n dynesty_solver = DynestySolver(problem, show_progress=True, seed=6174)\n dynesty_solver.run_dynesty(\"dynamic\", nlive_init=10, nlive_batch=10, maxbatch=2)\n\n sample_means = dynesty_solver.summary[\"mean\"]\n for parameter, true_value in true.items():\n self.assertAlmostEqual(sample_means[parameter], true_value, delta=0.01)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] | [
[
"numpy.random.normal",
"numpy.random.seed",
"numpy.linspace"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Rubikplayer/SoftRas | [
"bfc6e7aba8531f4937f933122b3662b39b1114f1"
] | [
"soft_renderer/mesh.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\nimport soft_renderer.functional as srf\n\n\nclass Mesh(object):\n '''\n A simple class for creating and manipulating trimesh objects\n '''\n def __init__(self, vertices, faces, textures=None, texture_res=1, texture_type='surface'):\n '''\n vertices, faces and textures(if not None) are expected to be Tensor objects\n '''\n self._vertices = vertices\n self._faces = faces\n\n if isinstance(self._vertices, np.ndarray):\n self._vertices = torch.from_numpy(self._vertices).float().cuda()\n if isinstance(self._faces, np.ndarray):\n self._faces = torch.from_numpy(self._faces).int().cuda()\n if self._vertices.ndimension() == 2:\n self._vertices = self._vertices[None, :, :]\n if self._faces.ndimension() == 2:\n self._faces = self._faces[None, :, :]\n\n self.device = self._vertices.device\n self.texture_type = texture_type\n\n self.batch_size = self._vertices.shape[0]\n self.num_vertices = self._vertices.shape[1]\n self.num_faces = self._faces.shape[1]\n\n self._face_vertices = None\n self._face_vertices_update = True\n self._surface_normals = None\n self._surface_normals_update = True\n self._vertex_normals = None\n self._vertex_normals_update = True\n\n self._fill_back = False\n\n # create textures\n if textures is None:\n if texture_type == 'surface':\n self._textures = torch.ones(self.batch_size, self.num_faces, texture_res**2, 3, \n dtype=torch.float32).to(self.device)\n self.texture_res = texture_res\n elif texture_type == 'vertex':\n self._textures = torch.ones(self.batch_size, self.num_vertices, 3, \n dtype=torch.float32).to(self.device)\n self.texture_res = 1\n else:\n if isinstance(textures, np.ndarray):\n textures = torch.from_numpy(textures).float().cuda()\n if textures.ndimension() == 3 and texture_type == 'surface':\n textures = textures[None, :, :, :]\n if textures.ndimension() == 2 and texture_type == 'vertex':\n textures = textures[None, :, :]\n self._textures = textures\n self.texture_res = int(np.sqrt(self._textures.shape[2]))\n\n self._origin_vertices = self._vertices\n self._origin_faces = self._faces\n self._origin_textures = self._textures\n\n @property\n def faces(self):\n return self._faces\n\n @faces.setter\n def faces(self, faces):\n # need check tensor\n self._faces = faces\n self.num_faces = self._faces.shape[1]\n self._face_vertices_update = True\n self._surface_normals_update = True\n self._vertex_normals_update = True\n\n @property\n def vertices(self):\n return self._vertices\n\n @vertices.setter\n def vertices(self, vertices):\n # need check tensor\n self._vertices = vertices\n self.num_vertices = self._vertices.shape[1]\n self._face_vertices_update = True\n self._surface_normals_update = True\n self._vertex_normals_update = True\n\n @property\n def textures(self):\n return self._textures\n\n @textures.setter\n def textures(self, textures):\n # need check tensor\n self._textures = textures\n\n @property\n def face_vertices(self):\n if self._face_vertices_update:\n self._face_vertices = srf.face_vertices(self.vertices, self.faces)\n self._face_vertices_update = False\n return self._face_vertices\n\n @property\n def surface_normals(self):\n if self._surface_normals_update:\n v10 = self.face_vertices[:, :, 0] - self.face_vertices[:, :, 1]\n v12 = self.face_vertices[:, :, 2] - self.face_vertices[:, :, 1]\n self._surface_normals = F.normalize(torch.cross(v12, v10), p=2, dim=2, eps=1e-6)\n self._surface_normals_update = False\n return self._surface_normals\n\n @property\n def vertex_normals(self):\n if self._vertex_normals_update:\n self._vertex_normals = srf.vertex_normals(self.vertices, self.faces)\n self._vertex_normals_update = False\n return self._vertex_normals\n\n @property\n def face_textures(self):\n if self.texture_type in ['surface']:\n return self.textures\n elif self.texture_type in ['vertex']:\n return srf.face_vertices(self.textures, self.faces)\n else:\n raise ValueError('texture type not applicable')\n\n def fill_back_(self):\n if not self._fill_back:\n self.faces = torch.cat((self.faces, self.faces[:, :, [2, 1, 0]]), dim=1)\n self.textures = torch.cat((self.textures, self.textures), dim=1)\n self._fill_back = True\n\n def reset_(self, bake_lighting_lambda=None):\n self.vertices = self._origin_vertices\n self.faces = self._origin_faces\n\n if bake_lighting_lambda is None:\n self.textures = self._origin_textures\n else:\n if self.texture_type in ['surface']:\n raise NotImplementedError\n elif self.texture_type in ['vertex']:\n self.textures = bake_lighting_lambda( self._origin_textures, self. vertex_normals)\n else:\n raise ValueError('texture type not applicable')\n self._fill_back = False\n \n @classmethod\n def from_obj(cls, filename_obj, normalization=False, load_texture=False, texture_res=1, texture_type='surface'):\n '''\n Create a Mesh object from a .obj file\n '''\n if load_texture:\n vertices, faces, textures = srf.load_obj(filename_obj,\n normalization=normalization,\n texture_res=texture_res,\n load_texture=True,\n texture_type=texture_type)\n else:\n vertices, faces = srf.load_obj(filename_obj,\n normalization=normalization,\n texture_res=texture_res,\n load_texture=False)\n textures = None\n return cls(vertices, faces, textures, texture_res, texture_type)\n\n def save_obj(self, filename_obj, save_texture=False, texture_res_out=16):\n if self.batch_size != 1:\n raise ValueError('Could not save when batch size >= 1')\n if save_texture:\n srf.save_obj(filename_obj, self.vertices[0], self.faces[0], \n textures=self.textures[0],\n texture_res=texture_res_out, texture_type=self.texture_type)\n else:\n srf.save_obj(filename_obj, self.vertices[0], self.faces[0], textures=None)\n\n def voxelize(self, voxel_size=32):\n face_vertices_norm = self.face_vertices * voxel_size / (voxel_size - 1) + 0.5\n return srf.voxelization(face_vertices_norm, voxel_size, False)"
] | [
[
"torch.ones",
"numpy.sqrt",
"torch.cat",
"torch.from_numpy",
"torch.cross"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
robertjankowski/social-media-influence-on-covid-pandemic | [
"1b04aa4aa88d4788fdfa023eb21b1f00b16f0110",
"1b04aa4aa88d4788fdfa023eb21b1f00b16f0110"
] | [
"scripts/data_utils.py",
"scripts/metrics.py"
] | [
"import pandas as pd\n\n\ndef get_value(text):\n return text.split(\"_\")[0]\n\n\ndef load_results(path: str, params):\n all_parameters = {}\n file_name = path.split(\"/\")[-1].split(\".csv\")[0]\n file_name = file_name.split(\"=\")[1:]\n\n for i, f in enumerate(file_name):\n all_parameters[params[i]] = get_value(f)\n\n df = pd.read_csv(path, index_col=0)\n return all_parameters, df\n\n\ndef load_multilayer_results(path: str):\n params = ['beta', 'gamma', 'mu', 'kappa', 'max_infected_time', 'q', 'p', 'xi', 'n', 'n_times', 'n_steps',\n 'n_agents', 'n_fraclinks']\n return load_results(path, params)\n\n\ndef load_singlelayer_results(path: str):\n params = ['beta', 'gamma', 'mu', 'kappa', 'max_infected_time', 'FRAC_A', 'FRAC_B', 'n_times', 'n_steps', 'n_agents']\n return load_results(path, params)\n",
"import networkx as nx\r\nimport numpy as np\r\n\r\n\r\ndef _get_degrees(g: nx.Graph) -> list:\r\n return list(dict(g.degree).values())\r\n\r\n\r\ndef pearson_coefficient_between_layers(g1: nx.Graph, g2: nx.Graph) -> float:\r\n \"\"\"\r\n Return person correlation between layers for given two graphs\r\n\r\n r_{\\alpha\\beta} \\in <-1, 1>\r\n\r\n :param g1: nx.Graph\r\n :param g2: nx.Graph\r\n :return: r_{\\alpha\\beta}\r\n \"\"\"\r\n g1_degrees = _get_degrees(g1)\r\n g2_degrees = _get_degrees(g2)\r\n g1_sigma = np.std(g1_degrees)\r\n g2_sigma = np.std(g2_degrees)\r\n\r\n k_1_2 = np.mean([k1 * k2 for k1, k2 in zip(g1_degrees, g2_degrees)])\r\n k_1 = np.mean(g1_degrees)\r\n k_2 = np.mean(g2_degrees)\r\n top = k_1_2 - k_1 * k_2\r\n bottom = g1_sigma * g2_sigma\r\n return top / bottom\r\n"
] | [
[
"pandas.read_csv"
],
[
"numpy.std",
"numpy.mean"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
cffbots/ESMValTool | [
"a9b6592a02f2085634a214ff5f36a736fa18ff47",
"a9b6592a02f2085634a214ff5f36a736fa18ff47",
"a9b6592a02f2085634a214ff5f36a736fa18ff47",
"a9b6592a02f2085634a214ff5f36a736fa18ff47",
"a9b6592a02f2085634a214ff5f36a736fa18ff47",
"a9b6592a02f2085634a214ff5f36a736fa18ff47"
] | [
"tests/system/esmvaltool_testlib.py",
"esmvaltool/diag_scripts/mlr/custom_sklearn.py",
"esmvaltool/diag_scripts/mlr/mmm.py",
"esmvaltool/diag_scripts/runoff_et/catchment_analysis.py",
"esmvaltool/diag_scripts/kcs/global_matching.py",
"esmvaltool/diag_scripts/arctic_ocean/arctic_ocean.py"
] | [
"\"\"\"Provide a class for testing esmvaltool.\"\"\"\n\nimport glob\nimport os\nimport shutil\nimport sys\nfrom unittest import SkipTest\n\nimport numpy as np\nimport yaml\n# from easytest import EasyTest\n\nimport esmvaltool\n\n\ndef _load_config(filename=None):\n \"\"\"Load test configuration\"\"\"\n if filename is None:\n # look in default locations for config-test.yml\n config_file = 'config-test.yml'\n default_locations = [\n '.',\n '~/.esmvaltool',\n os.path.dirname(__file__),\n ]\n for path in default_locations:\n filepath = os.path.join(os.path.expanduser(path), config_file)\n if os.path.exists(filepath):\n filename = os.path.abspath(filepath)\n break\n\n with open(filename, 'r') as file:\n cfg = yaml.safe_load(file)\n\n cfg['configfile'] = filename\n cfg['reference']['output'] = os.path.abspath(\n os.path.expanduser(cfg['reference']['output']))\n\n if cfg['test'].get('recipes', []) == []:\n script_root = esmvaltool.get_script_root()\n recipe_glob = os.path.join(script_root, 'nml', 'recipe_*.yml')\n cfg['test']['recipes'] = glob.glob(recipe_glob)\n\n return cfg\n\n\n_CFG = _load_config()\n\nRECIPES = _CFG['test']['recipes']\n\n\ndef _create_config_user_file(output_directory):\n \"\"\"Write a config-user.yml file.\n\n Write a configuration file for running ESMValTool\n such that it writes all output to `output_directory`.\n \"\"\"\n cfg = _CFG['user']\n\n cfg['output_dir'] = output_directory\n\n # write to file\n filename = os.path.join(output_directory, 'config-user.yml')\n with open(filename, 'w') as file:\n yaml.safe_dump(cfg, file)\n\n return filename\n\n\nclass ESMValToolTest: # was ESMValToolTest(EasyTest)\n \"\"\"Main class for ESMValTool test runs.\"\"\"\n\n def __init__(self, recipe, output_directory, ignore='', **kwargs):\n \"\"\"\n Create ESMValToolTest instance\n\n recipe: str\n The filename of the recipe that should be tested.\n output_directory : str\n The name of a directory where results can be stored.\n ignore: str or iterable of str\n Glob patterns of files to be ignored when testing.\n \"\"\"\n if not _CFG['test']['run']:\n raise SkipTest(\"System tests disabled in {}\".format(\n _CFG['configfile']))\n\n self.ignore = (ignore, ) if isinstance(ignore, str) else ignore\n\n script_root = esmvaltool.get_script_root()\n\n # Set recipe path\n if not os.path.exists(recipe):\n recipe = os.path.join(\n os.path.dirname(script_root), 'recipes', recipe)\n self.recipe_file = os.path.abspath(recipe)\n\n # Simulate input data?\n self.simulate_input = _CFG['test']['simulate_input']\n\n # Create reference output?\n self.create_reference_output = _CFG['reference']['generate']\n\n # Define reference output path\n reference_dir = os.path.join(\n _CFG['reference']['output'],\n os.path.splitext(os.path.basename(self.recipe_file))[0])\n\n # If reference data is neither available nor should be generated, skip\n if not (os.path.exists(reference_dir) or self.create_reference_output):\n raise SkipTest(\n \"No reference data available for recipe {} in {}\".format(\n recipe, _CFG['reference']['output']))\n\n # Write ESMValTool configuration file\n self.config_user_file = _create_config_user_file(output_directory)\n\n super(ESMValToolTest, self).__init__(\n exe='esmvaltool',\n args=['-n', self.recipe_file, '-c', self.config_user_file],\n output_directory=output_directory,\n refdirectory=reference_dir,\n **kwargs)\n\n def run(self, **kwargs):\n \"\"\"Run tests or generate reference data.\"\"\"\n if self.simulate_input:\n from .data_simulator import simulate_input_data\n simulate_input_data(\n recipe_file=self.recipe_file,\n config_user_file=self.config_user_file)\n\n if self.create_reference_output:\n self.generate_reference_output()\n raise SkipTest(\"Generated reference data instead of running test\")\n else:\n super(ESMValToolTest, self).run_tests(**kwargs)\n\n def generate_reference_output(self):\n \"\"\"Generate reference output.\n\n Generate reference data by executing the recipe and then moving\n results to the output directory.\n \"\"\"\n if not os.path.exists(self.refdirectory):\n self._execute()\n shutil.move(self.output_directory,\n os.path.dirname(self.refdirectory))\n else:\n print(\"Warning: not generating reference data, reference \"\n \"directory {} already exists.\".format(self.refdirectory))\n\n def _execute(self):\n \"\"\"Execute ESMValTool\n\n Override the _execute method because we want to run in our own\n Python instance to get coverage reporting and we want to update\n the location of `self.output_directory` afterwards.\n \"\"\"\n # run ESMValTool\n sys.argv[1:] = self.args\n esmvaltool.main.run()\n\n # Update the output directory to point to the output of the run\n output_directory = self.output_directory # noqa\n\n output = []\n for path in os.listdir(output_directory):\n path = os.path.join(output_directory, path)\n if os.path.isdir(path):\n output.append(path)\n\n if not output:\n raise OSError(\n \"Output directory not found in location {}. \"\n \"Probably ESMValTool failed to create any output.\".format(\n output_directory))\n\n if len(output) > 1:\n print(\"Warning: found multiple output directories:\\n{}\\nin output \"\n \"location {}\\nusing the first one.\".format(\n output, output_directory))\n\n self.output_directory = output[0] + os.sep # noqa\n\n def _get_files_from_refdir(self):\n \"\"\"Get a list of files from reference directory.\n\n Ignore files that match patterns in self.ignore.\n\n Override this method of easytest.EasyTest to be able to ignore certain\n files.\n \"\"\"\n from fnmatch import fnmatchcase\n\n matches = []\n for root, _, filenames in os.walk(self.refdirectory):\n for filename in filenames:\n path = os.path.join(root, filename)\n relpath = os.path.relpath(path, start=self.refdirectory)\n for pattern in self.ignore:\n if fnmatchcase(relpath, pattern):\n break\n else:\n matches.append(path)\n\n return matches\n\n def _compare_netcdf_values(self, f1, f2, allow_subset=False):\n \"\"\"Compare two netCDF4 Dataset instances.\n\n Check if dataset2 contains the same variable values as dataset1.\n\n Override this method of easytest.EasyTest because it is broken\n for the case where value1 and value2 have no length.\n \"\"\"\n if allow_subset: # allow that only a subset of data is compared\n raise NotImplementedError\n\n for key in f1.variables:\n values1 = f1.variables[key][:]\n values2 = f2.variables[key][:]\n\n if not np.array_equal(values1, values2):\n return False\n\n return True\n",
"\"\"\"Custom expansions of :mod:`sklearn` functionalities.\n\nNote\n----\nThis module provides custom expansions of some :mod:`sklearn` classes and\nfunctions which are necessary to fit the purposes for the desired\nfunctionalities of the :ref:`MLR module <api.esmvaltool.diag_scripts.mlr>`. As\nlong-term goal we would like to include these functionalities to the\n:mod:`sklearn` package since we believe these additions might be helpful for\neveryone. This module serves as interim solution. To ensure that all features\nare properly working this module is also covered by extensive tests.\n\nParts of this code have been copied from :mod:`sklearn`.\n\nLicense: BSD 3-Clause License\n\nCopyright (c) 2007-2020 The scikit-learn developers.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n* Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from this\n software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"\n\n# pylint: disable=arguments-differ\n# pylint: disable=attribute-defined-outside-init\n# pylint: disable=protected-access\n# pylint: disable=super-init-not-called\n# pylint: disable=too-many-arguments\n# pylint: disable=too-many-instance-attributes\n# pylint: disable=too-many-locals\n# pylint: disable=too-many-return-statements\n\nimport itertools\nimport logging\nimport numbers\nimport os\nimport warnings\nfrom contextlib import suppress\nfrom copy import deepcopy\nfrom inspect import getfullargspec\nfrom traceback import format_exc\n\nimport numpy as np\nimport scipy.sparse as sp\nfrom joblib import Parallel, delayed, effective_n_jobs\nfrom sklearn.base import BaseEstimator, clone, is_classifier\nfrom sklearn.compose import ColumnTransformer, TransformedTargetRegressor\nfrom sklearn.exceptions import FitFailedWarning, NotFittedError\nfrom sklearn.feature_selection import RFE, SelectorMixin\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import check_scoring\nfrom sklearn.model_selection import check_cv\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import FunctionTransformer\nfrom sklearn.utils import check_array, check_X_y, indexable, safe_sqr\nfrom sklearn.utils.fixes import np_version, parse_version\nfrom sklearn.utils.metaestimators import if_delegate_has_method\nfrom sklearn.utils.validation import check_is_fitted\n\nfrom esmvaltool.diag_scripts import mlr\n\nlogger = logging.getLogger(os.path.basename(__file__))\n\n\n_DEFAULT_TAGS = {\n 'non_deterministic': False,\n 'requires_positive_X': False,\n 'requires_positive_y': False,\n 'X_types': ['2darray'],\n 'poor_score': False,\n 'no_validation': False,\n 'multioutput': False,\n \"allow_nan\": False,\n 'stateless': False,\n 'multilabel': False,\n '_skip_test': False,\n '_xfail_checks': False,\n 'multioutput_only': False,\n 'binary_only': False,\n 'requires_fit': True,\n 'preserves_dtype': [np.float64],\n 'requires_y': False,\n 'pairwise': False,\n}\n\n\ndef _determine_key_type(key, accept_slice=True):\n \"\"\"Determine the data type of key.\"\"\"\n err_msg = (\"No valid specification of the columns. Only a scalar, list or \"\n \"slice of all integers or all strings, or boolean mask is \"\n \"allowed\")\n\n dtype_to_str = {int: 'int', str: 'str', bool: 'bool', np.bool_: 'bool'}\n array_dtype_to_str = {'i': 'int', 'u': 'int', 'b': 'bool', 'O': 'str',\n 'U': 'str', 'S': 'str'}\n\n if key is None:\n return None\n if isinstance(key, tuple(dtype_to_str.keys())):\n try:\n return dtype_to_str[type(key)]\n except KeyError:\n raise ValueError(err_msg)\n if isinstance(key, slice):\n if not accept_slice:\n raise TypeError(\n 'Only array-like or scalar are supported. '\n 'A Python slice was given.'\n )\n if key.start is None and key.stop is None:\n return None\n key_start_type = _determine_key_type(key.start)\n key_stop_type = _determine_key_type(key.stop)\n if key_start_type is not None and key_stop_type is not None:\n if key_start_type != key_stop_type:\n raise ValueError(err_msg)\n if key_start_type is not None:\n return key_start_type\n return key_stop_type\n if isinstance(key, (list, tuple)):\n unique_key = set(key)\n key_type = {_determine_key_type(elt) for elt in unique_key}\n if not key_type:\n return None\n if len(key_type) != 1:\n raise ValueError(err_msg)\n return key_type.pop()\n if hasattr(key, 'dtype'):\n try:\n return array_dtype_to_str[key.dtype.kind]\n except KeyError:\n raise ValueError(err_msg)\n raise ValueError(err_msg)\n\n\ndef _array_indexing(array, key, key_dtype, axis):\n \"\"\"Index an array or scipy.sparse consistently across numpy version.\"\"\"\n if np_version < parse_version('1.12') or sp.issparse(array):\n if key_dtype == 'bool':\n key = np.asarray(key)\n if isinstance(key, tuple):\n key = list(key)\n return array[key] if axis == 0 else array[:, key]\n\n\ndef _list_indexing(x_data, key, key_dtype):\n \"\"\"Index a python list.\"\"\"\n if np.isscalar(key) or isinstance(key, slice):\n # key is a slice or a scalar\n return x_data[key]\n if key_dtype == 'bool':\n # key is a boolean array-like\n return list(itertools.compress(x_data, key))\n # key is a integer array-like of key\n return [x_data[idx] for idx in key]\n\n\ndef _pandas_indexing(x_data, key, key_dtype, axis):\n \"\"\"Index a pandas dataframe or a series.\"\"\"\n if hasattr(key, 'shape'):\n key = np.asarray(key)\n key = key if key.flags.writeable else key.copy()\n elif isinstance(key, tuple):\n key = list(key)\n # check whether we should index with loc or iloc\n indexer = x_data.iloc if key_dtype == 'int' else x_data.loc\n return indexer[:, key] if axis else indexer[key]\n\n\ndef _safe_indexing(x_data, indices, *_, axis=0):\n \"\"\"Return rows, items or columns of x_data using indices.\"\"\"\n if indices is None:\n return x_data\n\n if axis not in (0, 1):\n raise ValueError(\n \"'axis' should be either 0 (to index rows) or 1 (to index \"\n \"column). Got {} instead.\".format(axis)\n )\n\n indices_dtype = _determine_key_type(indices)\n\n if axis == 0 and indices_dtype == 'str':\n raise ValueError(\n \"String indexing is not supported with 'axis=0'\"\n )\n\n if axis == 1 and x_data.ndim != 2:\n raise ValueError(\n \"'x_data' should be a 2D NumPy array, 2D sparse matrix or pandas \"\n \"dataframe when indexing the columns (i.e. 'axis=1'). \"\n \"Got {} instead with {} dimension(s).\".format(type(x_data),\n x_data.ndim)\n )\n\n if axis == 1 and indices_dtype == 'str' and not hasattr(x_data, 'loc'):\n raise ValueError(\n \"Specifying the columns using strings is only supported for \"\n \"pandas DataFrames\"\n )\n\n if hasattr(x_data, \"iloc\"):\n return _pandas_indexing(x_data, indices, indices_dtype, axis=axis)\n if hasattr(x_data, \"shape\"):\n return _array_indexing(x_data, indices, indices_dtype, axis=axis)\n return _list_indexing(x_data, indices, indices_dtype)\n\n\ndef _is_arraylike(input_array):\n \"\"\"Check whether the input is array-like.\"\"\"\n return (hasattr(input_array, '__len__') or\n hasattr(input_array, 'shape') or\n hasattr(input_array, '__array__'))\n\n\ndef _make_indexable(iterable):\n \"\"\"Ensure iterable supports indexing or convert to an indexable variant.\"\"\"\n if sp.issparse(iterable):\n return iterable.tocsr()\n if hasattr(iterable, \"__getitem__\") or hasattr(iterable, \"iloc\"):\n return iterable\n if iterable is None:\n return iterable\n return np.array(iterable)\n\n\ndef _num_samples(x_data):\n \"\"\"Return number of samples in array-like x_data.\"\"\"\n message = 'Expected sequence or array-like, got %s' % type(x_data)\n if hasattr(x_data, 'fit') and callable(x_data.fit):\n # Don't get num_samples from an ensembles length!\n raise TypeError(message)\n\n if not hasattr(x_data, '__len__') and not hasattr(x_data, 'shape'):\n if hasattr(x_data, '__array__'):\n x_data = np.asarray(x_data)\n else:\n raise TypeError(message)\n\n if hasattr(x_data, 'shape') and x_data.shape is not None:\n if len(x_data.shape) == 0:\n raise TypeError(\"Singleton array %r cannot be considered a valid \"\n \"collection.\" % x_data)\n # Check that shape is returning an integer or default to len\n # Dask dataframes may not return numeric shape[0] value\n if isinstance(x_data.shape[0], numbers.Integral):\n return x_data.shape[0]\n\n try:\n return len(x_data)\n except TypeError as type_error:\n raise TypeError(message) from type_error\n\n\ndef _check_fit_params(x_data, fit_params, indices=None):\n \"\"\"Check and validate the parameters passed during ``fit``.\"\"\"\n fit_params_validated = {}\n for param_key, param_value in fit_params.items():\n if (not _is_arraylike(param_value) or\n _num_samples(param_value) != _num_samples(x_data)):\n # Non-indexable pass-through (for now for backward-compatibility).\n # https://github.com/scikit-learn/scikit-learn/issues/15805\n fit_params_validated[param_key] = param_value\n else:\n # Any other fit_params should support indexing\n # (e.g. for cross-validation).\n fit_params_validated[param_key] = _make_indexable(param_value)\n fit_params_validated[param_key] = _safe_indexing(\n fit_params_validated[param_key], indices\n )\n\n return fit_params_validated\n\n\ndef _safe_tags(estimator, key=None):\n \"\"\"Safely get estimator tags.\"\"\"\n if hasattr(estimator, \"_get_tags\"):\n tags_provider = \"_get_tags()\"\n tags = estimator._get_tags()\n elif hasattr(estimator, \"_more_tags\"):\n tags_provider = \"_more_tags()\"\n tags = {**_DEFAULT_TAGS, **estimator._more_tags()}\n else:\n tags_provider = \"_DEFAULT_TAGS\"\n tags = _DEFAULT_TAGS\n\n if key is not None:\n if key not in tags:\n raise ValueError(\n f\"The key {key} is not defined in {tags_provider} for the \"\n f\"class {estimator.__class__.__name__}.\"\n )\n return tags[key]\n return tags\n\n\ndef _is_pairwise(estimator):\n \"\"\"Return ``True`` if estimator is pairwise.\"\"\"\n with warnings.catch_warnings():\n warnings.filterwarnings('ignore', category=FutureWarning)\n has_pairwise_attribute = hasattr(estimator, '_pairwise')\n pairwise_attribute = getattr(estimator, '_pairwise', False)\n pairwise_tag = _safe_tags(estimator, key=\"pairwise\")\n\n if has_pairwise_attribute:\n if pairwise_attribute != pairwise_tag:\n warnings.warn(\n \"_pairwise attribute is inconsistent with tags. Set the \"\n \"estimator tags of your estimator instead\", FutureWarning,\n )\n return pairwise_attribute\n\n # Use pairwise tag when the attribute is not present\n return pairwise_tag\n\n\ndef _safe_split(estimator, x_data, y_data, indices, train_indices=None):\n \"\"\"Create subset of dataset and properly handle kernels.\"\"\"\n if _is_pairwise(estimator):\n if not hasattr(x_data, \"shape\"):\n raise ValueError(\"Precomputed kernels or affinity matrices have \"\n \"to be passed as arrays or sparse matrices.\")\n # x_data is a precomputed square kernel matrix\n if x_data.shape[0] != x_data.shape[1]:\n raise ValueError(\"x_data should be a square kernel matrix\")\n if train_indices is None:\n x_subset = x_data[np.ix_(indices, indices)]\n else:\n x_subset = x_data[np.ix_(indices, train_indices)]\n else:\n x_subset = _safe_indexing(x_data, indices)\n\n if y_data is not None:\n y_subset = _safe_indexing(y_data, indices)\n else:\n y_subset = None\n\n return (x_subset, y_subset)\n\n\ndef _fit_and_score_weighted(estimator, x_data, y_data, scorer, train, test,\n parameters, fit_params, error_score=np.nan,\n sample_weights=None):\n \"\"\"Expand :func:`sklearn.model_selection._validation._fit_and_score`.\"\"\"\n # Adjust length of sample weights\n fit_params = fit_params if fit_params is not None else {}\n fit_params = _check_fit_params(x_data, fit_params, train)\n\n if parameters is not None:\n # clone after setting parameters in case any parameters\n # are estimators (like pipeline steps)\n # because pipeline doesn't clone steps in fit\n cloned_parameters = {}\n for (key, val) in parameters.items():\n cloned_parameters[key] = clone(val, safe=False)\n\n estimator = estimator.set_params(**cloned_parameters)\n\n (x_train, y_train) = _safe_split(estimator, x_data, y_data, train)\n (x_test, y_test) = _safe_split(estimator, x_data, y_data, test, train)\n if sample_weights is not None:\n sample_weights_test = sample_weights[test]\n else:\n sample_weights_test = None\n\n try:\n if y_train is None:\n estimator.fit(x_train, **fit_params)\n else:\n estimator.fit(x_train, y_train, **fit_params)\n except Exception:\n if error_score == 'raise':\n raise\n if isinstance(error_score, numbers.Number):\n test_score = error_score\n warnings.warn(\"Estimator fit failed. The score on this train-test \"\n \"partition for these parameters will be set to %f. \"\n \"Details: \\n%s\" % (error_score, format_exc()),\n FitFailedWarning)\n else:\n raise ValueError(\"error_score must be the string 'raise' or a \"\n \"numeric value. (Hint: if using 'raise', please \"\n \"make sure that it has been spelled correctly.)\")\n else:\n test_score = _score_weighted(estimator, x_test, y_test, scorer,\n sample_weights=sample_weights_test)\n\n return test_score\n\n\ndef _get_fit_parameters(fit_kwargs, steps, cls):\n \"\"\"Retrieve fit parameters from ``fit_kwargs``.\"\"\"\n params = {name: {} for (name, step) in steps if step is not None}\n step_names = list(params.keys())\n for (param_name, param_val) in fit_kwargs.items():\n param_split = param_name.split('__', 1)\n if len(param_split) != 2:\n raise ValueError(\n f\"Fit parameters for {cls} have to be given in the form \"\n f\"'s__p', where 's' is the name of the step and 'p' the name \"\n f\"of the parameter, got '{param_name}'\")\n try:\n params[param_split[0]][param_split[1]] = param_val\n except KeyError:\n raise ValueError(\n f\"Expected one of {step_names} for step of fit parameter, got \"\n f\"'{param_split[0]}' for parameter '{param_name}'\")\n return params\n\n\ndef _score_weighted(estimator, x_test, y_test, scorer, sample_weights=None):\n \"\"\"Expand :func:`sklearn.model_selection._validation._score`.\"\"\"\n if y_test is None:\n score = scorer(estimator, x_test, sample_weight=sample_weights)\n else:\n score = scorer(estimator, x_test, y_test, sample_weight=sample_weights)\n\n error_msg = (\"Scoring must return a number, got %s (%s) instead. \"\n \"(scorer=%s)\")\n if hasattr(score, 'item'):\n with suppress(ValueError):\n # e.g. unwrap memmapped scalars\n score = score.item()\n if not isinstance(score, numbers.Number):\n raise ValueError(error_msg % (score, type(score), scorer))\n return score\n\n\ndef _split_fit_kwargs(fit_kwargs, train_idx, test_idx):\n \"\"\"Get split fit kwargs for single CV step.\"\"\"\n fit_kwargs_train = {}\n fit_kwargs_test = {}\n for (key, val) in fit_kwargs.items():\n if 'sample_weight' in key and 'sample_weight_eval_set' not in key:\n fit_kwargs_train[key] = deepcopy(val)[train_idx]\n fit_kwargs_test[key] = deepcopy(val)[test_idx]\n else:\n fit_kwargs_train[key] = deepcopy(val)\n fit_kwargs_test[key] = deepcopy(val)\n return (fit_kwargs_train, fit_kwargs_test)\n\n\ndef _rfe_single_fit(rfe, estimator, x_data, y_data, train, test, scorer,\n **fit_kwargs):\n \"\"\"Return the score for a fit across one fold.\"\"\"\n (x_train, y_train) = _safe_split(estimator, x_data, y_data, train)\n (x_test, y_test) = _safe_split(estimator, x_data, y_data, test, train)\n (fit_kwargs_train, fit_kwargs_test) = _split_fit_kwargs(fit_kwargs, train,\n test)\n if 'sample_weight' in fit_kwargs_test:\n fit_kwargs_test['sample_weights'] = fit_kwargs_test.pop(\n 'sample_weight')\n\n def step_score(estimator, features):\n \"\"\"Score for a single step in the recursive feature elimination.\"\"\"\n return _score_weighted(estimator, x_test[:, features], y_test, scorer,\n **fit_kwargs_test)\n\n return rfe._fit(x_train, y_train, step_score=step_score,\n **fit_kwargs_train).scores_\n\n\ndef _map_features(features, support):\n \"\"\"Map old features indices to new ones using boolean mask.\"\"\"\n feature_mapping = {}\n new_idx = 0\n for (old_idx, supported) in enumerate(support):\n if supported:\n val = new_idx\n new_idx += 1\n else:\n val = None\n feature_mapping[old_idx] = val\n new_features = []\n for feature in features:\n new_feature = feature_mapping[feature]\n if new_feature is not None:\n new_features.append(new_feature)\n return new_features\n\n\ndef _update_transformers_param(estimator, support):\n \"\"\"Update ``transformers`` argument of ``ColumnTransformer`` steps.\"\"\"\n all_params = estimator.get_params()\n params = []\n for key in all_params:\n if key.endswith('transformers'):\n params.append(key)\n if isinstance(estimator, (Pipeline, AdvancedPipeline)):\n step = estimator.named_steps[key.split('__')[0]]\n if not isinstance(step, ColumnTransformer):\n raise TypeError(\n f\"Found 'transformers' parameter ('{key}'), but the \"\n f\"corresponding pipeline step is not a \"\n f\"ColumnTransformer (got '{type(step)}')\")\n else:\n raise TypeError(\n f\"Found 'transformers' parameter ('{key}'), but the \"\n f\"corresponding estimator is not a Pipeline or \"\n f\"AdvancedPipeline\")\n new_params = {}\n for param in params:\n new_transformers = []\n for transformer in all_params[param]:\n new_columns = _map_features(transformer[2], support)\n new_transformers.append(\n (transformer[0], transformer[1], new_columns))\n new_params[param] = new_transformers\n estimator.set_params(**new_params)\n\n\ndef cross_val_score_weighted(estimator, x_data, y_data=None, groups=None,\n scoring=None, cv=None, n_jobs=None, verbose=0,\n fit_params=None, pre_dispatch='2*n_jobs',\n error_score=np.nan, sample_weights=None):\n \"\"\"Expand :func:`sklearn.model_selection.cross_val_score`.\"\"\"\n scorer = check_scoring(estimator, scoring=scoring)\n (x_data, y_data, groups) = indexable(x_data, y_data, groups)\n\n cv = check_cv(cv, y_data, classifier=is_classifier(estimator))\n\n # We clone the estimator to make sure that all the folds are\n # independent, and that it is pickle-able.\n parallel = Parallel(n_jobs=n_jobs, verbose=verbose,\n pre_dispatch=pre_dispatch)\n scores = parallel(\n delayed(_fit_and_score_weighted)(\n clone(estimator), x_data, y_data, scorer, train, test, None,\n fit_params, error_score=error_score, sample_weights=sample_weights)\n for train, test in cv.split(x_data, y_data, groups))\n return np.array(scores)\n\n\ndef get_rfecv_transformer(rfecv_estimator):\n \"\"\"Get transformer step of RFECV estimator.\"\"\"\n try:\n check_is_fitted(rfecv_estimator)\n except NotFittedError:\n raise NotFittedError(\n \"RFECV instance used to initialize FeatureSelectionTransformer \"\n \"must be fitted\")\n transformer = FeatureSelectionTransformer(\n grid_scores=rfecv_estimator.grid_scores_,\n n_features=rfecv_estimator.n_features_,\n ranking=rfecv_estimator.ranking_,\n support=rfecv_estimator.support_,\n )\n return transformer\n\n\ndef perform_efecv(estimator, x_data, y_data, **kwargs):\n \"\"\"Perform exhaustive feature selection.\"\"\"\n x_data, y_data = check_X_y(\n x_data, y_data, ensure_min_features=2, force_all_finite='allow-nan')\n n_all_features = x_data.shape[1]\n\n # Iterate over all possible feature combinations\n supports = list(itertools.product([False, True], repeat=n_all_features))\n supports.remove(tuple([False] * n_all_features))\n logger.info(\n \"Testing all %i possible feature combinations for exhaustive feature \"\n \"selection\", len(supports))\n grid_scores = []\n for support in supports:\n support = np.array(support)\n features = np.arange(n_all_features)[support]\n\n # Evaluate estimator on new subset of features\n new_estimator = clone(estimator)\n _update_transformers_param(new_estimator, support)\n scores = cross_val_score_weighted(new_estimator, x_data[:, features],\n y_data, **kwargs)\n grid_scores.append(np.mean(scores))\n logger.debug(\"Fitted estimator with %i features, CV score was %.5f\",\n support.sum(), np.mean(scores))\n\n # Final parameters\n grid_scores = np.array(grid_scores)\n best_idx = np.argmax(grid_scores)\n support = np.array(supports[best_idx])\n features = np.arange(n_all_features)[support]\n n_features = support.sum()\n ranking = np.where(support, 1, 2)\n transformer = FeatureSelectionTransformer(\n grid_scores=grid_scores, n_features=n_features, ranking=ranking,\n support=support)\n\n # Get final estimator\n best_estimator = clone(estimator)\n _update_transformers_param(best_estimator, support)\n best_estimator.fit(x_data[:, features], y_data,\n **kwargs.get('fit_params', {}))\n\n logger.info(\"Found optimal score %.5f for %i features\",\n grid_scores[best_idx], n_features)\n return (best_estimator, transformer)\n\n\nclass AdvancedPipeline(Pipeline):\n \"\"\"Expand :class:`sklearn.pipeline.Pipeline`.\"\"\"\n\n @property\n def coef_(self):\n \"\"\"numpy.ndarray: Model coefficients.\"\"\"\n return self.steps[-1][1].coef_\n\n @property\n def feature_importances_(self):\n \"\"\"numpy.ndarray: Feature importances.\"\"\"\n return self.steps[-1][1].feature_importances_\n\n def _check_final_step(self):\n \"\"\"Check type of final step of pipeline.\"\"\"\n final_step = self.steps[-1][1]\n if not isinstance(final_step, AdvancedTransformedTargetRegressor):\n raise TypeError(\n f\"Expected estimator of type \"\n f\"{AdvancedTransformedTargetRegressor} for final step of \"\n f\"pipeline, got {final_step.__class__}\")\n\n def fit_target_transformer_only(self, y_data, **fit_kwargs):\n \"\"\"Fit only ``transform`` step of of target regressor.\"\"\"\n self._check_final_step()\n reg = self.steps[-1][1]\n fit_params = _get_fit_parameters(fit_kwargs, self.steps,\n self.__class__)\n reg_fit_params = fit_params[self.steps[-1][0]]\n reg.fit_transformer_only(y_data, **reg_fit_params)\n\n def fit_transformers_only(self, x_data, y_data, **fit_kwargs):\n \"\"\"Fit only ``transform`` steps of Pipeline.\"\"\"\n fit_params = _get_fit_parameters(fit_kwargs, self.steps,\n self.__class__)\n return self._fit(x_data, y_data, **fit_params)\n\n def transform_only(self, x_data):\n \"\"\"Only perform ``transform`` steps of Pipeline.\"\"\"\n for (_, transformer) in self.steps[:-1]:\n x_data = transformer.transform(x_data)\n return x_data\n\n def transform_target_only(self, y_data):\n \"\"\"Only perform ``transform`` steps of target regressor.\"\"\"\n self._check_final_step()\n reg = self.steps[-1][1]\n if not hasattr(reg, 'transformer_'):\n raise NotFittedError(\n \"Transforming target not possible, final regressor is not \"\n \"fitted yet, call fit() or fit_target_transformer_only() \"\n \"first\")\n if y_data.ndim == 1:\n y_data = y_data.reshape(-1, 1)\n y_trans = reg.transformer_.transform(y_data)\n if y_trans.ndim == 2 and y_trans.shape[1] == 1:\n y_trans = y_trans.squeeze(axis=1)\n return y_trans\n\n\nclass AdvancedRFE(RFE):\n \"\"\"Expand :class:`sklearn.feature_selection.RFE`.\"\"\"\n\n def fit(self, x_data, y_data, **fit_kwargs):\n \"\"\"Expand :meth:`fit` to accept kwargs.\"\"\"\n return self._fit(x_data, y_data, **fit_kwargs)\n\n def _fit(self, x_data, y_data, step_score=None, **fit_kwargs):\n \"\"\"Expand :meth:`_fit` to accept kwargs.\"\"\"\n # Parameter step_score controls the calculation of self.scores_\n # step_score is not exposed to users\n # and is used when implementing AdvancedRFECV\n # self.scores_ will not be calculated when calling _fit through fit\n x_data, y_data = check_X_y(x_data, y_data, \"csc\",\n ensure_min_features=2,\n force_all_finite=False)\n\n # Initialization\n n_features = x_data.shape[1]\n if self.n_features_to_select is None:\n n_features_to_select = n_features // 2\n else:\n n_features_to_select = self.n_features_to_select\n\n if 0.0 < self.step < 1.0:\n step = int(max(1, self.step * n_features))\n else:\n step = int(self.step)\n if step <= 0:\n raise ValueError(\"Step must be >0\")\n\n support_ = np.ones(n_features, dtype=bool)\n ranking_ = np.ones(n_features, dtype=int)\n\n if step_score:\n self.scores_ = []\n\n # Elimination\n while np.sum(support_) > n_features_to_select:\n # Remaining features\n features = np.arange(n_features)[support_]\n\n # Rank the remaining features\n estimator = clone(self.estimator)\n if self.verbose > 0:\n print(\"Fitting estimator with %d features.\" % np.sum(support_))\n\n _update_transformers_param(estimator, support_)\n estimator.fit(x_data[:, features], y_data, **fit_kwargs)\n\n # Get coefs (hasattr(estimator, 'coef_') raises a KeyError for\n # XGBRegressor models\n try:\n coefs = estimator.coef_\n except (AttributeError, KeyError):\n coefs = getattr(estimator, 'feature_importances_', None)\n if coefs is None:\n raise RuntimeError(\"The classifier does not expose \"\n \"'coef_' or 'feature_importances_' \"\n \"attributes\")\n\n # Get ranks\n if coefs.ndim > 1:\n ranks = np.argsort(safe_sqr(coefs).sum(axis=0))\n else:\n ranks = np.argsort(safe_sqr(coefs))\n\n # Transformer steps that reduce number of features is not supported\n if len(ranks) != len(features):\n raise NotImplementedError(\n f\"Estimators that contain transforming steps that reduce \"\n f\"the number of features are not supported in \"\n f\"{self.__class__}, got {len(features):d} features for \",\n f\"fit(), but only {len(ranks):d} elements for 'coefs_' / \"\n f\"'feature_importances_' are provided. Estimator:\\n\"\n f\"{estimator}\")\n\n # for sparse case ranks is matrix\n ranks = np.ravel(ranks)\n\n # Eliminate the worse features\n threshold = min(step, np.sum(support_) - n_features_to_select)\n\n # Compute step score on the previous selection iteration\n # because 'estimator' must use features\n # that have not been eliminated yet\n if step_score:\n self.scores_.append(step_score(estimator, features))\n support_[features[ranks][:threshold]] = False\n ranking_[np.logical_not(support_)] += 1\n\n # Set final attributes\n features = np.arange(n_features)[support_]\n self.estimator_ = clone(self.estimator)\n _update_transformers_param(self.estimator_, support_)\n self.estimator_.fit(x_data[:, features], y_data, **fit_kwargs)\n\n # Compute step score when only n_features_to_select features left\n if step_score:\n self.scores_.append(step_score(self.estimator_, features))\n self.n_features_ = support_.sum()\n self.support_ = support_\n self.ranking_ = ranking_\n\n return self\n\n @if_delegate_has_method(delegate='estimator')\n def predict(self, x_data, **predict_kwargs):\n \"\"\"Expand :meth:`predict()` to accept kwargs.\"\"\"\n check_is_fitted(self)\n return self.estimator_.predict(self.transform(x_data),\n **predict_kwargs)\n\n\nclass AdvancedRFECV(AdvancedRFE):\n \"\"\"Expand :class:`sklearn.feature_selection.RFECV`.\"\"\"\n\n def __init__(self, estimator, step=1, min_features_to_select=1, cv=None,\n scoring=None, verbose=0, n_jobs=None):\n \"\"\"Original constructor of :class:`sklearn.feature_selection.RFECV`.\"\"\"\n self.estimator = estimator\n self.step = step\n self.min_features_to_select = min_features_to_select\n self.cv = cv\n self.scoring = scoring\n self.verbose = verbose\n self.n_jobs = n_jobs\n\n def fit(self, x_data, y_data, groups=None, **fit_kwargs):\n \"\"\"Expand :meth:`fit` to accept kwargs.\"\"\"\n x_data, y_data = check_X_y(\n x_data, y_data, \"csr\", ensure_min_features=2,\n force_all_finite=False)\n\n # Initialization\n cv = check_cv(self.cv, y_data,\n classifier=is_classifier(self.estimator))\n scorer = check_scoring(self.estimator, scoring=self.scoring)\n n_features = x_data.shape[1]\n\n if 0.0 < self.step < 1.0:\n step = int(max(1, self.step * n_features))\n else:\n step = int(self.step)\n if step <= 0:\n raise ValueError(\"Step must be >0\")\n\n # Build an AdvancedRFE object, which will evaluate and score each\n # possible feature count, down to self.min_features_to_select\n rfe = AdvancedRFE(estimator=self.estimator,\n n_features_to_select=self.min_features_to_select,\n step=self.step, verbose=self.verbose)\n\n # Determine the number of subsets of features by fitting across\n # the train folds and choosing the \"features_to_select\" parameter\n # that gives the least averaged error across all folds.\n\n # Note that joblib raises a non-picklable error for bound methods\n # even if n_jobs is set to 1 with the default multiprocessing\n # backend.\n # This branching is done so that to\n # make sure that user code that sets n_jobs to 1\n # and provides bound methods as scorers is not broken with the\n # addition of n_jobs parameter.\n\n if effective_n_jobs(self.n_jobs) == 1:\n (parallel, func) = (list, _rfe_single_fit)\n else:\n parallel = Parallel(n_jobs=self.n_jobs)\n func = delayed(_rfe_single_fit)\n\n scores = parallel(\n func(rfe, self.estimator, x_data, y_data, train, test, scorer,\n **fit_kwargs)\n for train, test in cv.split(x_data, y_data, groups))\n\n scores = np.sum(scores, axis=0)\n scores_rev = scores[::-1]\n argmax_idx = len(scores) - np.argmax(scores_rev) - 1\n n_features_to_select = max(\n n_features - (argmax_idx * step),\n self.min_features_to_select)\n\n # Re-execute an elimination with best_k over the whole set\n rfe = AdvancedRFE(estimator=self.estimator,\n n_features_to_select=n_features_to_select,\n step=self.step, verbose=self.verbose)\n\n rfe.fit(x_data, y_data, **fit_kwargs)\n\n # Set final attributes\n self.support_ = rfe.support_\n self.n_features_ = rfe.n_features_\n self.ranking_ = rfe.ranking_\n self.estimator_ = clone(self.estimator)\n _update_transformers_param(self.estimator_, self.support_)\n self.estimator_.fit(self.transform(x_data), y_data, **fit_kwargs)\n\n # Fixing a normalization error, n is equal to\n # get_n_splits(x_data, y_data) - 1 here, the scores are normalized by\n # get_n_splits(x_data, y_data)\n self.grid_scores_ = scores[::-1] / cv.get_n_splits(x_data, y_data,\n groups)\n return self\n\n\nclass AdvancedTransformedTargetRegressor(TransformedTargetRegressor):\n \"\"\"Expand :class:`sklearn.compose.TransformedTargetRegressor`.\"\"\"\n\n @property\n def coef_(self):\n \"\"\"numpy.ndarray: Model coefficients.\"\"\"\n return self.regressor_.coef_\n\n @property\n def feature_importances_(self):\n \"\"\"numpy.ndarray: Feature importances.\"\"\"\n return self.regressor_.feature_importances_\n\n def fit(self, x_data, y_data, **fit_kwargs):\n \"\"\"Expand :meth:`fit` to accept kwargs.\"\"\"\n (y_2d,\n regressor_kwargs) = self.fit_transformer_only(y_data, **fit_kwargs)\n\n # Transform y and convert back to 1d array if necessary\n y_trans = self.transformer_.transform(y_2d)\n if y_trans.ndim == 2 and y_trans.shape[1] == 1:\n y_trans = y_trans.squeeze(axis=1)\n\n # Perform linear regression if regressor is not given\n if self.regressor is None:\n self.regressor_ = LinearRegression()\n else:\n self.regressor_ = clone(self.regressor)\n\n # Fit regressor with kwargs\n self.regressor_.fit(x_data, y_trans, **regressor_kwargs)\n return self\n\n def fit_transformer_only(self, y_data, **fit_kwargs):\n \"\"\"Fit only ``transformer`` step.\"\"\"\n y_data = check_array(y_data,\n accept_sparse=False,\n force_all_finite=True,\n ensure_2d=False,\n dtype='numeric')\n self._training_dim = y_data.ndim\n\n # Process kwargs\n (_, regressor_kwargs) = self._get_fit_params(fit_kwargs)\n\n # Transformers are designed to modify X which is 2D, modify y_data\n # FIXME: Transformer does NOT use transformer_kwargs\n if y_data.ndim == 1:\n y_2d = y_data.reshape(-1, 1)\n else:\n y_2d = y_data\n self._fit_transformer(y_2d)\n return (y_2d, regressor_kwargs)\n\n def predict(self, x_data, always_return_1d=True, **predict_kwargs):\n \"\"\"Expand :meth:`predict()` to accept kwargs.\"\"\"\n check_is_fitted(self)\n if not hasattr(self, 'regressor_'):\n raise NotFittedError(\n f\"Regressor of {self.__class__} is not fitted yet, call fit() \"\n f\"first\")\n\n # Kwargs for returning variance or covariance\n if ('return_std' in predict_kwargs and 'return_std' in getfullargspec(\n self.regressor_.predict).args):\n raise NotImplementedError(\n f\"Using keyword argument 'return_std' for final regressor \"\n f\"{self.regressor_.__class__} is not supported yet, only \"\n f\"'return_var' is allowed. Expand the regressor to accept \"\n f\"'return_var' instead (see 'esmvaltool/diag_scripts/mlr\"\n f\"/models/gpr_sklearn.py' for an example)\")\n mlr.check_predict_kwargs(predict_kwargs)\n return_var = predict_kwargs.get('return_var', False)\n return_cov = predict_kwargs.get('return_cov', False)\n\n # Prediction\n prediction = self.regressor_.predict(x_data, **predict_kwargs)\n if return_var or return_cov:\n pred = prediction[0]\n else:\n pred = prediction\n if pred.ndim == 1:\n pred_trans = self.transformer_.inverse_transform(\n pred.reshape(-1, 1))\n else:\n pred_trans = self.transformer_.inverse_transform(pred)\n if self._to_be_squeezed(pred_trans, always_return_1d=always_return_1d):\n pred_trans = pred_trans.squeeze(axis=1)\n if not (return_var or return_cov):\n return pred_trans\n\n # Return scaled variance or covariance if desired\n err = prediction[1]\n if not hasattr(self.transformer_, 'scale_'):\n raise NotImplementedError(\n f\"Transforming of additional prediction output (e.g. by \"\n f\"'return_var' or 'return_cov') is not supported for \"\n f\"transformer {self.transformer_.__class__} yet, the \"\n f\"necessary attribute 'scale_' is missing\")\n scale = self.transformer_.scale_\n if scale is not None:\n err *= scale**2\n if self._to_be_squeezed(err, always_return_1d=always_return_1d):\n err = err.squeeze(axis=1)\n return (pred_trans, err)\n\n def _get_fit_params(self, fit_kwargs):\n \"\"\"Separate ``transformer`` and ``regressor`` kwargs.\"\"\"\n steps = [\n ('transformer', self.transformer),\n ('regressor', self.regressor),\n ]\n fit_params = _get_fit_parameters(fit_kwargs, steps, self.__class__)\n fit_params.setdefault('transformer', {})\n fit_params.setdefault('regressor', {})\n\n # FIXME\n if fit_params['transformer']:\n raise NotImplementedError(\n f\"Fit parameters {fit_params['transformer']} for transformer \"\n f\"{self.transformer.__class__} of {self.__class__} are not \"\n f\"supported at the moment\")\n\n return (fit_params['transformer'], fit_params['regressor'])\n\n def _fit_transformer(self, y_data):\n \"\"\"Check transformer and fit transformer.\"\"\"\n if (self.transformer is not None and\n (self.func is not None or self.inverse_func is not None)):\n raise ValueError(\"'transformer' and functions 'func'/\"\n \"'inverse_func' cannot both be set.\")\n if self.transformer is not None:\n self.transformer_ = clone(self.transformer)\n else:\n if self.func is not None and self.inverse_func is None:\n raise ValueError(\n \"When 'func' is provided, 'inverse_func' must also be \"\n \"provided\")\n self.transformer_ = FunctionTransformer(\n func=self.func, inverse_func=self.inverse_func, validate=True,\n check_inverse=self.check_inverse)\n self.transformer_.fit(y_data)\n if self.check_inverse:\n idx_selected = slice(None, None, max(1, y_data.shape[0] // 10))\n y_sel = _safe_indexing(y_data, idx_selected)\n y_sel_t = self.transformer_.transform(y_sel)\n if not np.allclose(y_sel,\n self.transformer_.inverse_transform(y_sel_t)):\n warnings.warn(\"The provided functions or transformer are \"\n \"not strictly inverse of each other. If \"\n \"you are sure you want to proceed regardless, \"\n \"set 'check_inverse=False'\", UserWarning)\n\n def _to_be_squeezed(self, array, always_return_1d=True):\n \"\"\"Check if ``array`` should be squeezed or not.\"\"\"\n squeeze = array.ndim == 2 and array.shape[1] == 1\n if not always_return_1d:\n squeeze = squeeze and self._training_dim == 1\n return squeeze\n\n\nclass FeatureSelectionTransformer(BaseEstimator, SelectorMixin):\n \"\"\"Transformer step of a feature selection estimator.\"\"\"\n\n def __init__(self, grid_scores, n_features, ranking, support):\n \"\"\"Initialize feature selection transformer.\"\"\"\n self.grid_scores = grid_scores\n self.n_features = n_features\n self.ranking = ranking\n self.support = support\n\n def fit(self, *_, **__):\n \"\"\"Empty method.\"\"\"\n return self\n\n def _get_support_mask(self):\n \"\"\"Get support mask.\"\"\"\n return self.support\n\n def _more_tags(self):\n \"\"\"Additional estimator tags.\"\"\"\n more_tags = deepcopy(_DEFAULT_TAGS)\n more_tags['allow_nan'] = True\n return more_tags\n",
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Use simple multi-model mean for predictions.\n\nDescription\n-----------\nThis diagnostic calculates the (unweighted) mean over all given datasets for a\ngiven target variable.\n\nAuthor\n------\nManuel Schlund (DLR, Germany)\n\nProject\n-------\nCRESCENDO\n\nConfiguration options in recipe\n-------------------------------\nconvert_units_to: str, optional\n Convert units of the input data. Can also be given as dataset option.\ndtype: str (default: 'float64')\n Internal data type which is used for all calculations, see\n `<https://docs.scipy.org/doc/numpy/user/basics.types.html>`_ for a list of\n allowed values.\nignore: list of dict, optional\n Ignore specific datasets by specifying multiple :obj:`dict` s of metadata.\nmlr_model_name: str, optional (default: 'MMM')\n Human-readable name of the MLR model instance (e.g used for labels).\nmmm_error_type: str, optional\n If given, additionally saves estimated squared MMM model error. If the\n option is set to ``'loo'``, the (constant) error is estimated as RMSEP\n using leave-one-out cross-validation. No other options are supported at the\n moment.\npattern: str, optional\n Pattern matched against ancestor file names.\nprediction_name: str, optional\n Default ``prediction_name`` of output cubes if no 'prediction_reference'\n dataset is given.\nweighted_samples: dict\n If specified, use weighted mean square error to estimate prediction error.\n The given keyword arguments are directly passed to\n :func:`esmvaltool.diag_scripts.mlr.get_all_weights` to calculate the sample\n weights. By default, area weights and time weights are used.\n\n\"\"\"\n\nimport logging\nimport os\nfrom copy import deepcopy\nfrom pprint import pformat\n\nimport iris\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import LeaveOneOut\n\nimport esmvaltool.diag_scripts.shared.iris_helpers as ih\nfrom esmvaltool.diag_scripts import mlr\nfrom esmvaltool.diag_scripts.shared import (\n ProvenanceLogger,\n get_diagnostic_filename,\n group_metadata,\n io,\n run_diagnostic,\n select_metadata,\n)\n\nlogger = logging.getLogger(os.path.basename(__file__))\n\n\ndef _add_dataset_attributes(cube, datasets, cfg):\n \"\"\"Add dataset-related attributes to cube.\"\"\"\n dataset_names = sorted(list({d['dataset'] for d in datasets}))\n projects = sorted(list({d['project'] for d in datasets}))\n start_years = list({d['start_year'] for d in datasets})\n end_years = list({d['end_year'] for d in datasets})\n cube.attributes['dataset'] = '|'.join(dataset_names)\n cube.attributes['description'] = 'MMM prediction'\n cube.attributes['end_year'] = min(end_years)\n cube.attributes['mlr_model_name'] = cfg['mlr_model_name']\n cube.attributes['mlr_model_type'] = 'mmm'\n cube.attributes['project'] = '|'.join(projects)\n cube.attributes['start_year'] = min(start_years)\n cube.attributes['var_type'] = 'prediction_output'\n\n\ndef _load_cube(cfg, dataset):\n \"\"\"Load single :class:`iris.cube.Cube`.\"\"\"\n path = dataset['filename']\n cube = iris.load_cube(path)\n cube.data = cube.core_data().astype(cfg['dtype'], casting='same_kind')\n convert_units(cfg, cube, dataset)\n return (cube, path)\n\n\ndef add_general_attributes(cube, **kwargs):\n \"\"\"Add general attributes to cube.\"\"\"\n for (key, val) in kwargs.items():\n if val is not None:\n cube.attributes[key] = val\n\n\ndef convert_units(cfg, cube, data):\n \"\"\"Convert units if desired.\"\"\"\n cfg_settings = cfg.get('convert_units_to')\n data_settings = data.get('convert_units_to')\n if cfg_settings or data_settings:\n units_to = cfg_settings\n if data_settings:\n units_to = data_settings\n logger.info(\"Converting units from '%s' to '%s'\", cube.units, units_to)\n cube.convert_units(units_to)\n\n\ndef get_loo_error_cube(cfg, label_datasets):\n \"\"\"Estimate prediction error using cross-validation.\"\"\"\n loo = LeaveOneOut()\n logger.info(\"Estimating prediction error using cross-validator %s\",\n str(loo.__class__))\n label_datasets = np.array(label_datasets)\n errors = []\n for (train_idx, test_idx) in loo.split(label_datasets):\n ref_cube = get_mmm_cube(cfg, label_datasets[test_idx])\n mmm_cube = get_mmm_cube(cfg, label_datasets[train_idx])\n\n # Apply mask\n mask = np.ma.getmaskarray(ref_cube.data).ravel()\n mask |= np.ma.getmaskarray(mmm_cube.data).ravel()\n\n y_true = ref_cube.data.ravel()[~mask]\n y_pred = mmm_cube.data.ravel()[~mask]\n weights = mlr.get_all_weights(ref_cube, **cfg['weighted_samples'])\n weights = weights.ravel()[~mask]\n\n # Calculate mean squared error\n error = mean_squared_error(y_true, y_pred, sample_weight=weights)\n errors.append(error)\n\n # Get error cube\n error_cube = get_mmm_cube(cfg, label_datasets)\n error_array = np.empty(error_cube.shape).ravel()\n mask = np.ma.getmaskarray(error_cube.data).ravel()\n error_array[mask] = np.nan\n error_array[~mask] = np.mean(errors)\n error_array = np.ma.masked_invalid(error_array)\n error_cube.data = error_array.reshape(error_cube.shape)\n\n # Cube metadata\n error_cube.attributes['error_type'] = 'loo'\n error_cube.attributes['squared'] = 1\n error_cube.attributes['var_type'] = 'prediction_output_error'\n error_cube.var_name += '_squared_mmm_error_estim'\n error_cube.long_name += ' (squared MMM error estimation using CV)'\n error_cube.units = mlr.units_power(error_cube.units, 2)\n return error_cube\n\n\ndef get_grouped_data(cfg, input_data=None):\n \"\"\"Get input files.\"\"\"\n if input_data is None:\n logger.debug(\"Loading input data from 'cfg' argument\")\n input_data = mlr.get_input_data(cfg,\n pattern=cfg.get('pattern'),\n ignore=cfg.get('ignore'))\n else:\n logger.debug(\"Loading input data from 'input_data' argument\")\n if not mlr.datasets_have_mlr_attributes(input_data, log_level='error'):\n raise ValueError(\"At least one input dataset does not have valid \"\n \"MLR attributes\")\n if not input_data:\n raise ValueError(\"No input data found\")\n paths = [d['filename'] for d in input_data]\n logger.debug(\"Found files\")\n logger.debug(pformat(paths))\n\n # Extract necessary data\n label_data = select_metadata(input_data, var_type='label')\n if not label_data:\n raise ValueError(\"No data with var_type 'label' found\")\n prediction_reference_data = select_metadata(\n input_data, var_type='prediction_reference')\n extracted_data = label_data + prediction_reference_data\n logger.debug(\"Found 'label' data\")\n logger.debug(pformat([d['filename'] for d in label_data]))\n logger.debug(\"Found 'prediction_reference' data\")\n logger.debug(pformat([d['filename'] for d in prediction_reference_data]))\n\n # Return grouped data\n return group_metadata(extracted_data, 'tag')\n\n\ndef get_mmm_cube(cfg, label_datasets):\n \"\"\"Get multi-model mean data.\"\"\"\n cubes = iris.cube.CubeList()\n paths = []\n (ref_cube, _) = _load_cube(cfg, label_datasets[0])\n for dataset in label_datasets:\n (cube, path) = _load_cube(cfg, dataset)\n ih.prepare_cube_for_merging(cube, path)\n cubes.append(cube)\n paths.append(path)\n mmm_cube = cubes.merge_cube()\n if len(paths) > 1:\n mmm_cube = mmm_cube.collapsed(['cube_label'], iris.analysis.MEAN)\n for aux_coord in ref_cube.coords(dim_coords=False):\n mmm_cube.add_aux_coord(aux_coord, ref_cube.coord_dims(aux_coord))\n mmm_cube.remove_coord('cube_label')\n _add_dataset_attributes(mmm_cube, label_datasets, cfg)\n return mmm_cube\n\n\ndef get_reference_dataset(datasets, tag):\n \"\"\"Get ``prediction_reference`` dataset.\"\"\"\n ref_datasets = select_metadata(datasets, var_type='prediction_reference')\n if not ref_datasets:\n logger.warning(\n \"Calculating residuals for '%s' not possible, no \"\n \"'prediction_reference' dataset given\", tag)\n return (None, None)\n if len(ref_datasets) > 1:\n filenames = [d['filename'] for d in ref_datasets]\n raise ValueError(\n f\"Expected at most one 'prediction_reference' dataset for \"\n f\"'{tag}', got {len(ref_datasets):d}:\\n{pformat(filenames)}\")\n return (ref_datasets[0], ref_datasets[0].get('prediction_name'))\n\n\ndef get_residual_cube(mmm_cube, ref_cube):\n \"\"\"Calculate residuals.\"\"\"\n if mmm_cube.shape != ref_cube.shape:\n raise ValueError(\n f\"Expected identical shapes for 'label' and \"\n f\"'prediction_reference' datasets, got {mmm_cube.shape} and \"\n f\"{ref_cube.shape}, respectively\")\n res_cube = ref_cube.copy()\n res_cube.data -= mmm_cube.data\n res_cube.attributes = mmm_cube.attributes\n res_cube.attributes['residuals'] = 'true minus predicted values'\n res_cube.attributes['var_type'] = 'prediction_residual'\n res_cube.var_name += '_residual'\n res_cube.long_name += ' (residual)'\n return res_cube\n\n\ndef save_error(cfg, label_datasets, mmm_path, **cube_attrs):\n \"\"\"Save estimated error of MMM.\"\"\"\n if len(label_datasets) < 2:\n logger.warning(\n \"Estimating MMM prediction error not possible, at least 2 'label' \"\n \"datasets are needed, only %i is given\", len(label_datasets))\n return\n error_type = cfg['mmm_error_type']\n allowed_error_types = ['loo']\n logger.info(\"Calculating error using error type '%s'\", error_type)\n if error_type == 'loo':\n err_cube = get_loo_error_cube(cfg, label_datasets)\n else:\n raise NotImplementedError(\n f\"mmm_error_type '{error_type}' is currently not supported, \"\n f\"supported types are {allowed_error_types}\")\n add_general_attributes(err_cube, **cube_attrs)\n err_path = mmm_path.replace('_prediction', '_squared_prediction_error')\n io.iris_save(err_cube, err_path)\n write_provenance(cfg, err_path,\n [d['filename'] for d in label_datasets],\n f\"{err_cube.long_name} of MMM model \"\n f\"{cfg['mlr_model_name']} using error type {error_type}.\")\n\n\ndef save_residuals(cfg, mmm_cube, ref_dataset, label_datasets, **cube_attrs):\n \"\"\"Save residuals.\"\"\"\n logger.info(\"Calculating residuals\")\n (ref_cube, _) = _load_cube(cfg, ref_dataset)\n res_cube = get_residual_cube(mmm_cube, ref_cube)\n add_general_attributes(res_cube, **cube_attrs)\n mmm_path = mmm_cube.attributes['filename']\n res_path = mmm_path.replace('_prediction', '_prediction_residual')\n io.iris_save(res_cube, res_path)\n ancestors = ([d['filename'] for d in label_datasets] +\n [ref_dataset['filename']])\n caption = (f\"Residuals of predicted {res_cube.long_name} of MMM model \"\n f\"{cfg['mlr_model_name']}\")\n if 'prediction_name' in cube_attrs:\n caption += f\" for prediction {cube_attrs['prediction_name']}\"\n caption += '.'\n write_provenance(cfg, res_path, ancestors, caption)\n\n\ndef write_provenance(cfg, netcdf_path, ancestors, caption):\n \"\"\"Write provenance information.\"\"\"\n record = {\n 'ancestors': ancestors,\n 'authors': ['schlund_manuel'],\n 'caption': caption,\n 'references': ['schlund20jgr'],\n }\n with ProvenanceLogger(cfg) as provenance_logger:\n provenance_logger.log(netcdf_path, record)\n\n\ndef main(cfg, input_data=None, description=None):\n \"\"\"Run the diagnostic.\"\"\"\n cfg = deepcopy(cfg)\n cfg.setdefault('dtype', 'float64')\n cfg.setdefault('mlr_model_name', 'MMM')\n cfg.setdefault('weighted_samples',\n {'area_weighted': True, 'time_weighted': True})\n\n # Get data\n grouped_data = get_grouped_data(cfg, input_data=input_data)\n description = '' if description is None else f'_for_{description}'\n\n # Loop over all tags\n for (tag, datasets) in grouped_data.items():\n logger.info(\"Processing label '%s'\", tag)\n\n # Get label datasets and reference dataset if possible\n label_datasets = select_metadata(datasets, var_type='label')\n (ref_dataset, pred_name) = get_reference_dataset(datasets, tag)\n if pred_name is None:\n pred_name = cfg.get('prediction_name')\n\n # Calculate multi-model mean\n logger.info(\"Calculating multi-model mean\")\n mmm_cube = get_mmm_cube(cfg, label_datasets)\n add_general_attributes(mmm_cube, tag=tag, prediction_name=pred_name)\n mmm_path = get_diagnostic_filename(\n f\"mmm_{tag}_prediction{description}\", cfg)\n io.iris_save(mmm_cube, mmm_path)\n write_provenance(cfg, mmm_path,\n [d['filename'] for d in label_datasets],\n f\"Predicted {mmm_cube.long_name} of MMM model \"\n f\"{cfg['mlr_model_name']}.\")\n\n # Estimate prediction error using cross-validation\n if 'mmm_error_type' in cfg:\n save_error(cfg, label_datasets, mmm_path, tag=tag,\n prediction_name=pred_name)\n\n # Calculate residuals\n if ref_dataset is not None:\n save_residuals(cfg, mmm_cube, ref_dataset, label_datasets, tag=tag,\n prediction_name=pred_name)\n\n\n# Run main function when this script is called\nif __name__ == '__main__':\n with run_diagnostic() as config:\n main(config)\n",
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Catchment specific water flux plots.\n\n###############################################################\nrunoff_et/catchment_analysis.py\nAuthors ESMValToolV1 Version\n Philipp Sommer ([email protected])\n Stefan Hagemann ([email protected])\n Alexander Loew\nPort to ESMValTool Version 2\n Tobias Stacke ([email protected])\n###############################################################\n\nDescription\n-----------\n Plots temporal and spatial averages of precipitation, runoff and\n evaporation for specific land surface catchments. Additionally,\n relations of runoff coefficient to relative precipitation bias\n and runoff coefficient to evaporation coefficient are computed.\n\n Default reference data are included in this routine (default class)\n but can be replaced with other datasets. In case a custom catchment\n mask is used, the default class (catchment names, IDs, reference data)\n has to be adapted.\n\n###############################################################\n\n\"\"\"\nimport calendar\nimport logging\nimport os\nfrom itertools import cycle\n\nimport iris\nimport iris.coord_categorisation\nimport numpy as np\n\nimport esmvaltool.diag_scripts.shared as diag\n\nlogger = logging.getLogger(os.path.basename(__file__))\n\n\ndef get_defaults():\n \"\"\"Return default reference values for predefined catchments.\n\n The entries are used in the routine analysecatchments. Catchments and\n reference values are specific for the default catchment mask. All reference\n values are given in mm a-1. Precip data is based on WFDEI, runoff is based\n on GRDC, ET is derived as the difference of both. The values are updated\n and differ slightly from the ESMValTool 1 version.\n Dictionary entries are\n catchments\n mrro\n pr\n evspsbl\n \"\"\"\n defaults = {\n 'catchments': {\n # Catchments with name as used in make_catchment_plots and\n # associated ID used in the catchment mask netCDF file\n \"Amazon\": 94,\n \"Parana\": 98,\n \"Mackenzie\": 76,\n \"Mississippi\": 86,\n \"Danube\": 14,\n \"Congo\": 68,\n \"Niger_Malanville\": 65,\n \"Nile\": 60,\n \"Lena\": 40,\n \"Yangtze-Kiang\": 52,\n \"Ganges-Brahmaputra\": 54,\n \"Murray\": 100,\n },\n 'mrro': {\n 'Amazon': 1194.63,\n 'Congo': 365.45,\n 'Danube': 250.75,\n 'Ganges-Brahmaputra': 672.11,\n 'Lena': 199.61,\n 'Mackenzie': 173.87,\n 'Mississippi': 182.12,\n 'Murray': 8.20,\n 'Niger_Malanville': 31.49,\n 'Nile': 48.72,\n 'Parana': 202.87,\n 'Yangtze-Kiang': 531.33,\n },\n 'pr': {\n 'Amazon': 2210.25,\n 'Congo': 1571.41,\n 'Danube': 808.04,\n 'Ganges-Brahmaputra': 1405.84,\n 'Lena': 387.01,\n 'Mackenzie': 450.16,\n 'Mississippi': 897.18,\n 'Murray': 474.62,\n 'Niger_Malanville': 437.90,\n 'Nile': 655.62,\n 'Parana': 1314.66,\n 'Yangtze-Kiang': 1074.79,\n },\n 'evspsbl': {\n 'Amazon': 1015.62,\n 'Congo': 1205.96,\n 'Danube': 557.29,\n 'Ganges-Brahmaputra': 733.73,\n 'Lena': 187.40,\n 'Mackenzie': 276.29,\n 'Mississippi': 715.06,\n 'Murray': 466.42,\n 'Niger_Malanville': 406.41,\n 'Nile': 606.90,\n 'Parana': 1111.80,\n 'Yangtze-Kiang': 543.46,\n }\n }\n\n return defaults\n\n\ndef format_coef_plot(my_ax):\n \"\"\"Move axis from border to center, adapts ticks and labels accordingly.\n\n Parameters\n ----------\n my_ax : object\n plot axis object\n \"\"\"\n # Add infos to axis\n my_ax.xaxis.set_label_coords(0.5, -0.025)\n my_ax.yaxis.set_label_coords(-0.025, 0.5)\n # Adapt axis range to center zero\n xmax = np.ceil(\n (np.absolute(np.array(my_ax.get_xlim())).max() + 5) / 10.0) * 10 - 5\n my_ax.set_xlim(xmax * -1, xmax)\n ymax = np.ceil(\n (np.absolute(np.array(my_ax.get_ylim())).max() + 5) / 10.0) * 10 - 5\n my_ax.set_ylim(ymax * -1, ymax)\n # remove 0 from y and x axis\n for key in ['x', 'y']:\n ticks = list(getattr(my_ax, 'get_%sticks' % key)())\n try:\n ticks.remove(0)\n except ValueError:\n pass\n getattr(my_ax, 'set_%sticks' % key)(ticks)\n\n # Move left y-axis and bottim x-axis to centre, passing through (0,0)\n my_ax.spines['left'].set_position('center')\n my_ax.spines['bottom'].set_position('center')\n # Eliminate upper and right axes\n my_ax.spines['right'].set_color('none')\n my_ax.spines['top'].set_color('none')\n # Show ticks in the left and lower axes only\n my_ax.xaxis.set_ticks_position('bottom')\n my_ax.yaxis.set_ticks_position('left')\n\n\ndef data2file(cfg, filename, title, filedata):\n \"\"\"Write data dictionary into ascii file.\n\n Parameters\n ----------\n cfg : dict\n Configuration dictionary of the recipe\n filename : str\n String containing the file name\n title : str\n String containing the file header\n filedata : dict\n Dictionary of catchment averages per river\n \"\"\"\n # Write experiment data\n filepath = os.path.join(cfg[diag.names.WORK_DIR], filename)\n with open(filepath, 'w') as out:\n out.write(title + '\\n\\n')\n for river, value in sorted(filedata.items()):\n out.write('{:25} : {:8.2f}\\n'.format(river, value))\n\n\ndef write_plotdata(cfg, plotdata, catchments):\n \"\"\"Write catchment averaged values for all datasets.\n\n Parameters\n ----------\n cfg : dict\n Configuration dictionary of the recipe\n plotdata : dict\n Dictionary containing the catchment averages\n catchments : dict\n Dictionary containing infomation about catchment mask,\n grid cell size, and reference values\n \"\"\"\n ref_vars = []\n metric = \"catchment averages\"\n unit = \"[mm a-1]\"\n\n for var in plotdata.keys():\n for identifier in plotdata[var].keys():\n # Write experiment data\n filename = '_'.join([var, identifier]) + '.txt'\n title = \" \".join(identifier.split(' ') + [var, metric, unit])\n filedata = plotdata[var][identifier]\n data2file(cfg, filename, title, filedata)\n # Write reference data\n if var not in ref_vars:\n filename = '_'.join([var, 'reference']) + '.txt'\n title = \" \".join([catchments['refname'], metric, unit])\n filedata = catchments[var]\n data2file(cfg, filename, title, filedata)\n ref_vars.append(var)\n\n\ndef get_expdata(expdict, refdict):\n \"\"\"Get list with catchment averages for experiment and reference.\n\n Parameters\n ----------\n expdict : dict\n the catchment averages experiments dictionary\n refdict : dict\n the catchment averages reference dictionary\n \"\"\"\n expdata, refdata, rivers = [], [], []\n for riv, ref in sorted(refdict.items()):\n rivers.append(riv)\n refdata.append(ref)\n for riv in rivers:\n expdata.append(expdict[riv])\n return rivers, np.array(refdata), np.array(expdata)\n\n\ndef compute_diags(plotdata, identifier, catchments):\n \"\"\"Compute diagnostics for all variables of an experiment.\n\n Parameters\n ----------\n plotdata : dict\n Dictionary containing the catchment averages\n identifier : str\n Dataset name\n catchments : dict\n Dictionary containing infomation about catchment mask,\n grid cell size, and reference values\n \"\"\"\n diags = {'ref': {}, 'exp': {}, 'abs': {}, 'rel': {}}\n # 1. Absolute and relative variable biases\n for var in plotdata.keys():\n diags['riv'], diags['ref'][var], diags['exp'][var] = get_expdata(\n plotdata[var][identifier], catchments[var])\n diags['abs'][var] = diags['exp'][var] - diags['ref'][var]\n diags['rel'][var] = diags['exp'][var] / diags['ref'][var] * 100\n diags['xrv'] = range(len(diags['riv']))\n\n # 2. Coefficients\n diags['prbias'] = diags['abs']['pr'] / diags['ref']['pr'] * 100\n diags['rocoef'] = (diags['exp']['mrro'] / diags['exp']['pr'] * 100) - (\n diags['ref']['mrro'] / diags['ref']['pr'] * 100)\n diags['etcoef'] = (diags['exp']['evspsbl'] / diags['exp']['pr'] * 100) - (\n diags['ref']['evspsbl'] / diags['ref']['pr'] * 100)\n\n return diags\n\n\ndef setup_pdf(pltdir, identifier, outtype):\n \"\"\"Prepare pdf output.\n\n Parameters\n ----------\n pltdir : str\n Output directory for pdf plot\n identifier : str\n Dataset name\n outtype : str\n Plot file type [pdf,other]\n \"\"\"\n from matplotlib.backends.backend_pdf import PdfPages\n\n if outtype == 'pdf':\n filepath = os.path.join(pltdir, identifier + \".pdf\")\n pdf = PdfPages(filepath)\n else:\n pdf = None\n return pdf\n\n\ndef prep_barplot(diags, defs, identifier, var, pdf):\n \"\"\"Prepare barplot.\n\n Parameters\n ----------\n diags : dict\n Dictionary containing all metrics for plotting\n defs : dict\n Dictionary containing plot settings\n identifier : str\n Dataset name\n var : str\n short name of the actual variable\n pdf : obj\n pdf oject is pdf output is chosen, None otherwise\n \"\"\"\n import matplotlib.pyplot as plt\n\n fig, my_axs = plt.subplots(nrows=1, ncols=2, sharex=False)\n fig.suptitle(identifier.upper() + ' vs ' + defs['refname'].upper())\n fig.subplots_adjust(bottom=0.35)\n plottitle = ['\\nBias for ', '\\nRelative bias for ']\n ylabel = [var.upper() + ' [mm a-1]', 'Relative bias [%]']\n\n # Setup both plot axis\n for iax, axs in enumerate(my_axs.tolist()):\n axs.set_title(plottitle[iax] + var.upper())\n axs.set_ylabel(ylabel[iax])\n axs.set_xlabel('Catchment')\n axs.set_xticks(diags['xrv'])\n axs.set_xticklabels((diags['riv']), fontsize='small')\n for tick in axs.get_xticklabels():\n tick.set_rotation(90)\n axs.axhline(c='black', lw=2)\n\n # Plot absolut bias for every catchment\n my_axs[0].bar(diags['xrv'], diags['abs'][var], color=\"C{}\".format(0))\n # Plot relative bias for every catchment\n my_axs[1].bar(diags['xrv'], diags['ref'][var], color=\"C{}\".format(1))\n # Finish plot\n finish_plot(fig, defs['pltdir'], identifier + '_' + var + '-bias', pdf)\n\n\ndef prep_scatplot(coeftype, diags, defs, identifier, pdf):\n \"\"\"Prepare scatterplot for different coefficients.\n\n Parameters\n ----------\n coeftype : str\n string indicting plot type [prbias,etcoef]\n diags : dict\n Dictionary containing all metrics for plotting\n defs : dict\n Dictionary containing plot settings\n identifier : str\n Dataset name\n pdf : obj\n pdf oject is pdf output is chosen, None otherwise\n \"\"\"\n import matplotlib.pyplot as plt\n\n fig, axs = plt.subplots(nrows=1, ncols=1, sharex=False)\n axs.set_title(identifier.upper() + ' vs ' + defs['refname'].upper())\n axs.set_ylabel('Bias of runoff coefficient [%]')\n\n marker = cycle(defs['markerlist'])\n\n if coeftype == 'prbias':\n for prbias, rocoef in zip(diags['prbias'], diags['rocoef']):\n axs.scatter(prbias, rocoef, marker=next(marker))\n axs.set_xlabel('Relative bias of precipitation [%]')\n tag = '_pr-vs-ro'\n elif coeftype == 'etcoef':\n for etcoef, rocoef in zip(diags['etcoef'], diags['rocoef']):\n axs.scatter(etcoef, rocoef, marker=next(marker))\n axs.set_xlabel('Bias of ET coefficient [%]')\n tag = '_et-vs-ro'\n else:\n raise ValueError('Unexpected coefficient combination in prep_scatplot')\n\n format_coef_plot(axs)\n add_legend(fig, diags['riv'], defs['markerlist'])\n finish_plot(fig, defs['pltdir'], identifier + tag, pdf)\n\n\ndef add_legend(fig, rivers, markerlist):\n \"\"\"Add scatter plot legend with separate axis.\n\n Parameters\n ----------\n fig : obj\n plot figure object\n rivers : list\n list of river catchment names\n markerlist : list\n list of marker strings for scatterplot legend\n \"\"\"\n # Define legend\n fig.subplots_adjust(bottom=0.30)\n marker = cycle(markerlist)\n caxe = fig.add_axes([0.05, 0.01, 0.9, 0.20])\n for label in rivers:\n caxe.scatter([], [], marker=next(marker), label=label)\n caxe.legend(ncol=3, numpoints=1, loc=\"lower center\", mode=\"expand\")\n caxe.set_axis_off()\n\n\ndef finish_plot(fig, pltdir, name, pdf):\n \"\"\"Save actual figure to either png or pdf.\n\n Parameters\n ----------\n fig : obj\n actual figure\n pltdir : str\n target directory to store plots\n name : str\n filename for png output without extension\n pdf : obj\n pdf object collection all pages in case of pdf output\n \"\"\"\n import matplotlib.pyplot as plt\n if '-bias' in name:\n plt.tight_layout()\n if pdf is None:\n filepath = os.path.join(pltdir, name + \".png\")\n fig.savefig(filepath)\n else:\n fig.savefig(pdf, dpi=80, format='pdf')\n plt.close()\n\n\ndef make_catchment_plots(cfg, plotdata, catchments):\n \"\"\"Plot catchment averages for different metrics.\n\n Parameters\n ----------\n cfg : dict\n Configuration dictionary of the recipe\n plotdata : dict\n Dictionary containing the catchment averages\n catchments : dict\n Dictionary containing infomation about catchment mask,\n grid cell size, and reference values\n \"\"\"\n import matplotlib.pyplot as plt\n\n # Get colorscheme from recipe\n defs = {\n 'colorscheme': cfg.get('colorscheme', 'default'),\n 'markerlist': ('s', '+', 'o', '*', 'x', 'D'),\n 'pltdir': cfg[diag.names.PLOT_DIR],\n 'plttype': cfg.get('output_file_type', 'png'),\n 'refname': catchments['refname']\n }\n plt.style.use(defs['colorscheme'])\n\n # Loop over datasets\n for identifier in plotdata[list(plotdata.keys())[0]].keys():\n # Prepare pdf file if output type chosen\n pdf = setup_pdf(defs['pltdir'], identifier, defs['plttype'])\n\n # Compute diagnostics for plots\n diags = compute_diags(plotdata, identifier, catchments)\n\n # Barplots for single variables\n for var in plotdata.keys():\n prep_barplot(diags, defs, identifier, var, pdf)\n\n # Runoff coefficient vs relative precipitation bias\n prep_scatplot('prbias', diags, defs, identifier, pdf)\n\n # Runoff coefficient vs evaporation coefficient bias\n prep_scatplot('etcoef', diags, defs, identifier, pdf)\n\n # Finish pdf if it is the chosen output\n if pdf is not None:\n pdf.close()\n\n\ndef get_catchment_data(cfg):\n \"\"\"Read and prepare catchment mask.\n\n Parameters\n ----------\n cfg : dict\n Configuration dictionary of the recipe\n \"\"\"\n catchments = get_defaults()\n catchments['refname'] = 'default'\n if not cfg.get('catchmentmask'):\n raise ValueError('A catchment mask file needs to be specified in the '\n 'recipe (see recipe description for details)')\n catchment_filepath = os.path.join(cfg['auxiliary_data_dir'],\n cfg.get('catchmentmask'))\n if not os.path.isfile(catchment_filepath):\n raise IOError('Catchment file {} not found'.format(catchment_filepath))\n catchments['cube'] = iris.load_cube(catchment_filepath)\n if catchments['cube'].coord('latitude').bounds is None:\n catchments['cube'].coord('latitude').guess_bounds()\n if catchments['cube'].coord('longitude').bounds is None:\n catchments['cube'].coord('longitude').guess_bounds()\n catchments['area'] = iris.analysis.cartography.area_weights(\n catchments['cube'])\n\n return catchments\n\n\ndef get_sim_data(cfg, datapath, catchment_cube):\n \"\"\"Read and postprocess netcdf data from experiments.\n\n Check units, aggregate to long term mean yearly sum and\n regrid to resolution of catchment mask.\n\n Parameters\n ----------\n cfg : dict\n Configuration dictionary of the recipe.\n dataset_path : str\n Path to the netcdf file\n catchment_cube : obj\n iris cube object containing simulation data\n \"\"\"\n datainfo = diag.Datasets(cfg).get_dataset_info(path=datapath)\n identifier = \"_\".join(\n [datainfo['dataset'].upper(), datainfo['exp'], datainfo['ensemble']])\n # Load data into iris cube\n new_cube = iris.load(datapath, diag.Variables(cfg).standard_names())[0]\n # Check for expected unit\n if new_cube.units != 'kg m-2 s-1':\n raise ValueError('Unit [kg m-2 s-1] is expected for ',\n new_cube.long_name.lower(), ' flux')\n # Convert to unit mm per month\n timelist = new_cube.coord('time')\n daypermonth = []\n for mydate in timelist.units.num2date(timelist.points):\n daypermonth.append(calendar.monthrange(mydate.year, mydate.month)[1])\n new_cube.data *= 86400.0\n for i, days in enumerate(daypermonth):\n new_cube.data[i] *= days\n # Aggregate over year --> unit mm per year\n iris.coord_categorisation.add_year(new_cube, 'time')\n year_cube = new_cube.aggregated_by('year', iris.analysis.SUM)\n year_cube.units = \"mm a-1\"\n # Compute long term mean\n mean_cube = year_cube.collapsed([diag.names.TIME], iris.analysis.MEAN)\n # Regrid to catchment data grid --> maybe use area_weighted instead?\n if mean_cube.coord('latitude').bounds is None:\n mean_cube.coord('latitude').guess_bounds()\n if mean_cube.coord('longitude').bounds is None:\n mean_cube.coord('longitude').guess_bounds()\n m_grid = [iris.analysis.Linear(), iris.analysis.AreaWeighted()]\n mean_cube_regrid = mean_cube.regrid(catchment_cube, m_grid[1])\n\n return datainfo['short_name'], identifier, mean_cube_regrid\n\n\ndef get_catch_avg(catchments, sim_cube):\n \"\"\"Compute area weighted averages for river catchments.\n\n Parameters\n ----------\n catchments : dict\n Dictionary containing infomation about catchment mask,\n grid cell size, and reference values\n sim_cube : obj\n iris cube object containing the simulation data\n \"\"\"\n avg = {}\n for river, rid in catchments['catchments'].items():\n data_catch = np.ma.masked_where(\n catchments['cube'].data.astype(np.int) != rid, sim_cube.data)\n area_catch = np.ma.masked_where(\n catchments['cube'].data.astype(np.int) != rid,\n catchments['area'].data)\n avg[river] = (data_catch * (area_catch / area_catch.sum())).sum()\n return avg\n\n\ndef update_reference(catchments, model, rivervalues, var):\n \"\"\"Update reference catchment averages.\n\n Parameters\n ----------\n catchments : dict\n Dictionary containing infomation about catchment mask,\n grid cell size, and reference values\n model : str\n name of the data set\n rivervalues : dict\n dictionary of river catchment averages\n var : str\n short name of the variable\n \"\"\"\n if catchments['refname'] != model and catchments['refname'] != 'default':\n raise ValueError('Reference must be the same for all variables!')\n catchments[var] = rivervalues\n catchments['refname'] = model\n\n\ndef update_plotdata(identifier, plotdata, rivervalues, var):\n \"\"\"Update simulation catchment averages.\n\n Parameters\n ----------\n identifier : str\n string consisting of dataset, experiment and ensemble information\n plotdata : dict\n river catchment averages for different variables and datasets\n rivervalues : dict\n river catchment averages for different variables\n var : str\n short name of the variable\n \"\"\"\n if var not in plotdata.keys():\n plotdata[var] = {}\n if identifier in plotdata[var].keys():\n raise ValueError('Variable', var, 'already exists in plot dict')\n else:\n plotdata[var][identifier] = rivervalues\n\n\ndef main(cfg):\n \"\"\"Run the diagnostic.\n\n Parameters\n ----------\n cfg : dict\n Configuration dictionary of the recipe.\n \"\"\"\n # Get dataset and variable information\n logging.debug(\"Found datasets in recipe:\\n%s\", diag.Datasets(cfg))\n logging.debug(\"Found variables in recipe:\\n%s\", diag.Variables(cfg))\n\n # Check for correct variables\n if not diag.Variables(cfg).vars_available('pr', 'mrro', 'evspsbl'):\n raise ValueError(\n \"Diagnostic requires precipitation, runoff and evaporation data\")\n\n # Read catchmentmask\n # to check: Correct way to read auxillary data using recipes?\n my_catch = get_catchment_data(cfg)\n\n # Read data, convert units and compute long term means\n # to check: Shouldn't this be part of preprocessing?\n # to check: How to regrid onto catchment_cube grid\n # with preproc recipe statements\n # instead of using regrid here?\n allcubes = {}\n plotdata = {}\n for datapath in diag.Datasets(cfg):\n # Get simulation data\n var, identifier, cube = get_sim_data(cfg, datapath, my_catch['cube'])\n # Get river catchment averages\n rivervalues = get_catch_avg(my_catch, cube)\n # Sort into data dictionaries\n datainfo = diag.Datasets(cfg).get_dataset_info(path=datapath)\n model = datainfo['dataset']\n if model == datainfo.get('reference_dataset', None):\n update_reference(my_catch, model, rivervalues, var)\n else:\n update_plotdata(identifier, plotdata, rivervalues, var)\n\n # Append to cubelist for temporary output\n if model not in allcubes.keys():\n allcubes[model] = []\n allcubes[model].append(cube)\n\n # Write regridded and temporal aggregated netCDF data files (one per model)\n # to do: update attributes, something fishy with unlimited dimension\n for model, mcube in allcubes.items():\n filepath = os.path.join(cfg[diag.names.WORK_DIR],\n '_'.join(['postproc', model]) + '.nc')\n iris.save(mcube, filepath)\n logger.info(\"Writing %s\", filepath)\n\n # Write plotdata as ascii files for user information\n write_plotdata(cfg, plotdata, my_catch)\n\n # Plot catchment data\n make_catchment_plots(cfg, plotdata, my_catch)\n\n\nif __name__ == '__main__':\n\n with diag.run_diagnostic() as config:\n main(config)\n",
"\"\"\"Align the target model with the CMIP ensemble.\"\"\"\nimport logging\nfrom pathlib import Path\nfrom itertools import product\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport xarray as xr\n\nfrom esmvaltool.diag_scripts.shared import (get_diagnostic_filename,\n get_plot_filename, run_diagnostic,\n select_metadata, ProvenanceLogger)\n\nlogger = logging.getLogger(Path(__file__).name)\n\n\ndef create_provenance_record(ancestor_files):\n \"\"\"Create a provenance record.\"\"\"\n record = {\n 'caption':\n \"Match temperature anomaly in target model to CMIP ensemble\",\n 'domains': ['global'],\n 'authors': [\n 'kalverla_peter',\n 'alidoost_sarah',\n 'rol_evert',\n ],\n 'ancestors': ancestor_files,\n }\n return record\n\n\ndef mean_of_target_models(metadata):\n \"\"\"Get the average delta T of the target model ensemble members.\"\"\"\n target_model_data = select_metadata(metadata, variable_group='tas_target')\n files = [\n tmd['filename'] for tmd in target_model_data\n if 'MultiModel' not in tmd['dataset']\n ]\n datasets = xr.open_mfdataset(files, combine='nested', concat_dim='ens')\n provenance = create_provenance_record(files)\n return datasets.tas.mean(dim='ens'), provenance\n\n\ndef get_cmip_dt(metadata, year, percentile):\n \"\"\"Compute target delta T for KNMI scenarios.\"\"\"\n attribute = f'MultiModel{percentile}'\n multimodelstat = select_metadata(metadata, alias=attribute)[0]\n dataset = xr.open_dataset(multimodelstat['filename'])\n return dataset.tas.sel(time=str(year)).values[0]\n\n\ndef get_resampling_period(target_dts, cmip_dt):\n \"\"\"Return 30-year time bounds of the resampling period.\n\n This is the period for which the target model delta T\n matches the cmip delta T for a specific year.\n Uses a 30-year rolling window to get the best match.\n \"\"\"\n target_dts = target_dts.rolling(time=30, center=True,\n min_periods=30).mean()\n time_idx = abs(target_dts - cmip_dt).argmin(dim='time').values\n year = target_dts.isel(time=time_idx).year.values.astype(int)\n target_dt = target_dts.isel(time=time_idx).values.astype(float)\n return [year - 14, year + 15], target_dt\n\n\ndef _timeline(axes, yloc, interval):\n \"\"\"Plot an interval near the bottom of the plot.\"\"\"\n xmin, xmax = interval\n\n # Later years should be located slightly higher:\n # yloc is relative to the axes, not in data coordinates.\n yloc = 0.05 + yloc / 20\n\n plot_args = dict(transform=axes.get_xaxis_transform(),\n linewidth=2,\n color='red')\n\n axes.plot([xmin, xmax], [yloc] * 2, **plot_args, label='Selected periods')\n axes.plot([xmin] * 2, [yloc - 0.01, yloc + 0.01], **plot_args)\n axes.plot([xmax] * 2, [yloc - 0.01, yloc + 0.01], **plot_args)\n\n\ndef make_plot(metadata, scenarios, cfg, provenance):\n \"\"\"Make figure 3, left graph.\n\n Multimodel values as line, reference value in black square,\n steering variables in dark dots.\n \"\"\"\n fig, axes = plt.subplots()\n for member in select_metadata(metadata, variable_group='tas_cmip'):\n filename = member['filename']\n dataset = xr.open_dataset(filename)\n if 'MultiModel' not in filename:\n axes.plot(dataset.time.dt.year,\n dataset.tas.values,\n c='grey',\n alpha=0.3,\n lw=.5,\n label='CMIP members')\n else:\n # Only display stats for the future period:\n dataset = dataset.sel(time=slice('2010', None, None))\n axes.plot(dataset.time.dt.year,\n dataset.tas.values,\n color='k',\n linewidth=2,\n label='CMIP ' + Path(filename).stem.split('_')[0][10:])\n\n for member in select_metadata(metadata, variable_group='tas_target'):\n filename = member['filename']\n dataset = xr.open_dataset(filename)\n if 'MultiModel' not in filename:\n axes.plot(dataset.time.dt.year,\n dataset.tas.values,\n color='blue',\n linewidth=1,\n label=member['dataset'])\n\n # Add the scenario's with dots at the cmip dt and bars for the periods\n for i, scenario in enumerate(scenarios):\n axes.scatter(scenario['year'],\n scenario['cmip_dt'],\n s=50,\n zorder=10,\n color='r',\n label=r\"Scenarios' steering $\\Delta T_{CMIP}$\")\n _timeline(axes, i, scenario['period_bounds'])\n\n handles, labels = plt.gca().get_legend_handles_labels()\n by_label = dict(zip(labels, handles)) # dict removes dupes\n axes.legend(by_label.values(), by_label.keys())\n axes.set_xlabel('Year')\n axes.set_ylabel(r'Global mean $\\Delta T$ (K) w.r.t. reference period')\n\n # Save figure\n filename = get_plot_filename('global_matching', cfg)\n fig.savefig(filename, bbox_inches='tight', dpi=300)\n with ProvenanceLogger(cfg) as provenance_logger:\n provenance_logger.log(filename, provenance)\n\n\ndef save(output, cfg, provenance):\n \"\"\"Save the output as csv file.\"\"\"\n scenarios = pd.DataFrame(output)\n filename = get_diagnostic_filename('scenarios', cfg, extension='csv')\n scenarios.to_csv(filename)\n print(scenarios.round(2))\n print(f\"Output written to {filename}\")\n with ProvenanceLogger(cfg) as provenance_logger:\n provenance_logger.log(filename, provenance)\n\n\ndef main(cfg):\n \"\"\"Return scenarios tables.\"\"\"\n # A list of dictionaries describing all datasets passed on to the recipe\n metadata = cfg['input_data'].values()\n\n # Get the average delta T of the target model\n target_dts, provenance = mean_of_target_models(metadata)\n\n # Define the different scenario's\n scenarios = []\n combinations = product(cfg['scenario_years'], cfg['scenario_percentiles'])\n for year, percentile in combinations:\n cmip_dt = get_cmip_dt(metadata, year, percentile)\n bounds, target_dt = get_resampling_period(target_dts, cmip_dt)\n\n scenario = {\n 'year': year,\n 'percentile': percentile,\n 'cmip_dt': cmip_dt,\n 'period_bounds': bounds,\n 'target_dt': float(target_dt),\n 'pattern_scaling_factor': cmip_dt / target_dt\n }\n scenarios.append(scenario)\n\n # Save scenarios tables as csv file\n save(scenarios, cfg, provenance)\n\n # Plot the results\n make_plot(metadata, scenarios, cfg, provenance)\n\n\nif __name__ == '__main__':\n with run_diagnostic() as config:\n main(config)\n",
"# -*- coding: utf-8 -*-\n\"\"\"Script to calculate Arctic Ocean diagnostics.\n\nDescription\n-----------\nThe main focus of this diagnostics is evaluation of ocean components\n of climate models in the Arctic Ocean, however most of the diagnostics\n are implemented in a way that can be easily expanded to other parts\n of the World Ocean. Most of the diagnostics aim at model comparison\n to climatological data (PHC3), so we target historical CMIP simulations.\n However scenario runs also can be analysed to have an impression\n of how Arcti Ocean hydrography will chnage in the future.\n\nAuthor\n------\nNikolay Koldunov (MARUM/AWI, Germany)\n\nProject\n-------\nTRR181/APPLICATE\n\nConfiguration options in recipe\n-------------------------------\nSee documentation\n\n\"\"\"\n\nimport itertools\nimport logging\nimport os\nfrom collections import OrderedDict\n\nimport cartopy.crs as ccrs\nfrom matplotlib import cm\nimport numpy as np\n\nfrom esmvaltool.diag_scripts.arctic_ocean.getdata import (aw_core, hofm_data,\n transect_data,\n tsplot_data)\nfrom esmvaltool.diag_scripts.arctic_ocean.plotting import (\n hofm_plot, plot2d_bias, plot2d_original_grid, plot_aw_core_stat,\n plot_profile, transect_map, transect_plot, tsplot_plot)\nfrom esmvaltool.diag_scripts.arctic_ocean.utils import (\n find_observations_name, get_clim_model_filenames, get_cmap,\n get_fx_filenames, timmean)\nfrom esmvaltool.diag_scripts.shared import run_diagnostic\n\n\nlogger = logging.getLogger(os.path.basename(__file__))\n\n\ndef run_hofm_data(cfg):\n \"\"\"Extract data for Hovmoeller diagrams.\n\n Parameters\n ----------\n cfg: dict\n configuration dictionary ESMValTool format.\n areacello_fx : dict\n configuration dictionary with names of the areacello_fx\n files associated to dataset names.\n diagworkdir: str\n path to the diagnostic work directory.\n \"\"\"\n logger.info(\"The `hofm_data` is True, going \\\n to extract monthly values for `hofm_regions`\")\n\n logger.info(\"`hofm_vars` are: %s\", cfg['hofm_vars'])\n # doing the loop for every variable\n for hofm_var in cfg['hofm_vars']:\n logger.info(\"Processing %s\", hofm_var)\n # get dictionary with model names as key and path to the\n # preprocessed file as a value\n model_filenames = get_clim_model_filenames(cfg, hofm_var)\n model_filenames = OrderedDict(\n sorted(model_filenames.items(), key=lambda t: t[0]))\n # loop over regions and models\n for mmodel, region in itertools.product(model_filenames,\n cfg['hofm_regions']):\n # actual extraction of the data for specific model and region\n hofm_data(cfg, model_filenames, mmodel, hofm_var, region)\n\n\ndef hofm_plot_params(cfg, hofm_var, var_number, observations):\n \"\"\"Prepeare configuration for Hovmoeller plot.\"\"\"\n\n model_filenames = get_clim_model_filenames(cfg, hofm_var)\n model_filenames = OrderedDict(\n sorted(model_filenames.items(), key=lambda t: t[0]))\n # remove \"model\" that contain observations,\n # since there will be no monthly data\n model_filenames = model_filenames.copy()\n if observations:\n del model_filenames[observations]\n # set the color map if not default\n if cfg['hofm_cmap']:\n cmap = get_cmap(cfg['hofm_cmap'][var_number])\n else:\n cmap = get_cmap('Spectral_r')\n # set the number of columns in the output figure\n # if defined\n if cfg['hofm_ncol']:\n ncols = cfg['hofm_ncol']\n else:\n ncols = 3\n # get the levels for plots of this variable\n vmin, vmax, sstep, roundlimit = cfg['hofm_limits'][var_number]\n plot_params = {}\n plot_params['variable'] = hofm_var\n plot_params['model_filenames'] = model_filenames\n plot_params['cmap'] = cmap\n plot_params['ncols'] = ncols\n plot_params['levels'] = np.round(np.linspace(vmin, vmax, sstep),\n roundlimit)\n plot_params['observations'] = observations\n\n return plot_params\n\n\ndef run_hofm_plot(cfg, observations):\n \"\"\"Plot Hovmoeller diagrams for each variable.\n\n Parameters\n ----------\n cfg: dict\n configuration dictionary ESMValTool format.\n observations: str\n name of the observation data set\n \"\"\"\n # loop over variables\n for var_number, hofm_var in enumerate(cfg['hofm_vars']):\n plot_params = hofm_plot_params(cfg, hofm_var, var_number, observations)\n\n # loop over models and regions\n for region in cfg['hofm_regions']:\n logger.info(\"Plotting Hovmoeller: for Region: %s, Variable %s\",\n region, hofm_var)\n plot_params['region'] = region\n hofm_plot(cfg, plot_params)\n\n\ndef run_mean(cfg, observations):\n \"\"\"Create time mean.\n\n Parameters\n ----------\n cfg: dict\n configuration dictionary ESMValTool format.\n observations: str\n name of the observation data set\n \"\"\"\n # loop over variables\n for hofm_var in cfg['hofm_vars']:\n model_filenames = get_clim_model_filenames(\n cfg,\n hofm_var,\n )\n model_filenames = OrderedDict(\n sorted(model_filenames.items(), key=lambda t: t[0]))\n # loop over models\n for model in model_filenames:\n timmean(cfg,\n model_filenames,\n model,\n hofm_var,\n observations=observations)\n\n\ndef plot_profile_params(cfg, hofm_var, observations):\n \"\"\"Prepeare configuration for profile plot.\"\"\"\n\n model_filenames = get_clim_model_filenames(cfg, hofm_var)\n model_filenames = OrderedDict(\n sorted(model_filenames.items(), key=lambda t: t[0]))\n\n plot_params = {}\n\n plot_params['variable'] = hofm_var\n plot_params['model_filenames'] = model_filenames\n plot_params['cmap'] = cm.Set2\n plot_params['dpi'] = 100\n plot_params['observations'] = observations\n\n return plot_params\n\n\ndef run_profiles(cfg, observations):\n \"\"\"Plot average vertical profiles for regions.\n\n Parameters\n ----------\n cfg: dict\n configuration dictionary ESMValTool format.\n observations: str\n name of the observation data set\n \"\"\"\n # loop over variables\n for hofm_var in cfg['hofm_vars']:\n plot_params = plot_profile_params(cfg, hofm_var, observations)\n # loop over regions\n for region in cfg['hofm_regions']:\n plot_params['region'] = region\n plot_profile(cfg, plot_params)\n\n\ndef plot2d_params(cfg, plot2d_var, var_number):\n \"\"\"Prepeare configuration for plot2d.\"\"\"\n\n model_filenames = get_clim_model_filenames(cfg, plot2d_var)\n model_filenames = OrderedDict(\n sorted(model_filenames.items(), key=lambda t: t[0]))\n # set the color map\n if cfg['plot2d_cmap']:\n cmap = get_cmap(cfg['plot2d_cmap'][var_number])\n else:\n cmap = get_cmap('Spectral_r')\n # set the number of columns in the plot\n if cfg['plot2d_ncol']:\n ncols = cfg['plot2d_ncol']\n else:\n ncols = 4\n # create color limits for the plot\n vmin, vmax, sstep, roundlimit = cfg['plot2d_limits'][var_number]\n # loop over depths\n plot_params = {}\n plot_params['variable'] = plot2d_var\n plot_params['model_filenames'] = model_filenames\n plot_params['cmap'] = cmap\n plot_params['ncols'] = ncols\n plot_params['levels'] = np.round(np.linspace(vmin, vmax, sstep),\n roundlimit)\n plot_params['dpi'] = 100\n plot_params['explicit_depths'] = None\n plot_params['projection'] = ccrs.NorthPolarStereo()\n plot_params['bbox'] = (-180, 180, 60, 90)\n\n return plot_params\n\n\ndef run_plot2d(cfg):\n \"\"\"Plot 2d maps on original grid.\n\n Parameters\n ----------\n cfg: dict\n configuration dictionary ESMValTool format.\n \"\"\"\n # loop over variables\n for var_number, plot2d_var in enumerate(cfg['plot2d_vars']):\n\n plot_params = plot2d_params(cfg, plot2d_var, var_number)\n\n for depth in cfg['plot2d_depths']:\n plot_params['depth'] = depth\n plot2d_original_grid(cfg, plot_params)\n\n\ndef plot2d_bias_params(cfg, plot2d_bias_var, var_number, observations):\n \"\"\"Prepeare configuration for plot2d bias.\"\"\"\n\n model_filenames = get_clim_model_filenames(cfg, plot2d_bias_var)\n model_filenames = OrderedDict(\n sorted(model_filenames.items(), key=lambda t: t[0]))\n # setup the color map\n if cfg['plot2d_bias_cmap']:\n cmap = get_cmap(cfg['plot2d_bias_cmap'][var_number])\n else:\n cmap = get_cmap('Spectral_r')\n # setup the number of columns\n if cfg['plot2d_bias_ncol']:\n ncols = cfg['plot2d_bias_ncol']\n else:\n ncols = 3\n # setup color limits\n vmin, vmax, sstep, roundlimit = cfg['plot2d_bias_limits'][var_number]\n\n plot_params = {}\n plot_params['variable'] = plot2d_bias_var\n plot_params['model_filenames'] = model_filenames\n plot_params['cmap'] = cmap\n plot_params['ncols'] = ncols\n plot_params['levels'] = np.round(np.linspace(vmin, vmax, sstep),\n roundlimit)\n plot_params['dpi'] = 100\n plot_params['observations'] = observations\n plot_params['projection'] = ccrs.NorthPolarStereo()\n plot_params['bbox'] = (-180, 180, 60, 90)\n return plot_params\n\n\ndef run_plot2d_bias(cfg, observations):\n \"\"\"Plot model biases over depth.\n\n Parameters\n ----------\n cfg: dict\n configuration dictionary ESMValTool format.\n observations: str\n name of the observation data set\n \"\"\"\n # loop over variables\n for var_number, plot2d_bias_var in enumerate(cfg['plot2d_bias_vars']):\n\n plot_params = plot2d_bias_params(cfg, plot2d_bias_var, var_number,\n observations)\n\n # loop over depths\n for depth in cfg['plot2d_bias_depths']:\n plot_params['depth'] = depth\n plot2d_bias(cfg, plot_params)\n\n\ndef transect_plot_params(cfg, trans_var, var_number):\n \"\"\"Prepeare configuration for transect plot.\"\"\"\n\n model_filenames = get_clim_model_filenames(cfg, trans_var)\n model_filenames = OrderedDict(\n sorted(model_filenames.items(), key=lambda t: t[0]))\n # loop over regions\n for mmodel, region in itertools.product(model_filenames,\n cfg['transects_regions']):\n # ploting a transect\n transect_data(cfg, mmodel, trans_var, region)\n # setup a color map\n if cfg['transects_cmap']:\n cmap = get_cmap(cfg['transects_cmap'][var_number])\n else:\n cmap = get_cmap('Spectral_r')\n # setup number of columns\n if cfg['transects_ncol']:\n ncols = cfg['transects_ncol']\n else:\n ncols = 3\n # setup color limits\n vmin, vmax, sstep, roundlimit = cfg['transects_limits'][var_number]\n\n plot_params = {}\n plot_params['variable'] = trans_var\n plot_params['model_filenames'] = model_filenames\n plot_params['cmap'] = cmap\n plot_params['ncols'] = ncols\n plot_params['levels'] = np.round(np.linspace(vmin, vmax, sstep),\n roundlimit)\n plot_params['dpi'] = 100\n plot_params['projection'] = ccrs.NorthPolarStereo()\n plot_params['bbox'] = (-180, 180, 60, 90)\n\n return plot_params\n\n\ndef run_transects(cfg):\n \"\"\"Plot transects.\n\n Parameters\n ----------\n cfg: dict\n configuration dictionary ESMValTool format.\n \"\"\"\n # First plot the map woth transect points for each \"region\"\n for region in cfg['transects_regions']:\n transect_map(cfg,\n region,\n projection=ccrs.NorthPolarStereo(),\n bbox=[-180, 180, 60, 90],\n mult=2)\n # loop over variables\n for var_number, trans_var in enumerate(cfg['transects_vars']):\n\n plot_params = transect_plot_params(cfg, trans_var, var_number)\n\n # loop over regions\n for region in cfg['transects_regions']:\n plot_params['region'] = region\n transect_plot(cfg, plot_params)\n\n\ndef run_aw_core(cfg):\n \"\"\"Calculate depth and temperature of the Atlantic Water core.\n\n Parameters\n ----------\n cfg: dict\n configuration dictionary ESMValTool format.\n \"\"\"\n model_filenames = get_clim_model_filenames(cfg, 'thetao')\n model_filenames = OrderedDict(\n sorted(model_filenames.items(), key=lambda t: t[0]))\n aw_core_parameters = aw_core(model_filenames, cfg['work_dir'], 'EB',\n 'thetao')\n plot_aw_core_stat(aw_core_parameters, cfg['plot_dir'])\n return aw_core_parameters\n\n\ndef run_aw_core_2d(cfg, aw_core_parameters):\n \"\"\"Plot temperature spatial distribution at AW core depth.\n\n Parameters\n ----------\n cfg: dict\n configuration dictionary ESMValTool format.\n aw_core_parameters: dict\n dictionary that contain AW core parameters generated\n by run_aw_core function.\n \"\"\"\n model_filenames = get_clim_model_filenames(cfg, 'thetao')\n model_filenames = OrderedDict(\n sorted(model_filenames.items(), key=lambda t: t[0]))\n aw_core_parameters = aw_core(model_filenames, cfg['work_dir'], 'EB',\n 'thetao')\n # this is now just using plot2d_original_grid with\n # additional `explicit_depths` parameter\n plot_params = {}\n plot_params['variable'] = 'thetao'\n plot_params['model_filenames'] = model_filenames\n plot_params['depth'] = 0\n plot_params['cmap'] = cm.Spectral_r\n plot_params['ncols'] = 4\n plot_params['levels'] = np.round(np.linspace(-2, 2.3, 41), 1)\n plot_params['dpi'] = 100\n plot_params['explicit_depths'] = aw_core_parameters\n plot_params['projection'] = ccrs.NorthPolarStereo()\n plot_params['bbox'] = (-180, 180, 60, 90)\n\n plot2d_original_grid(cfg, plot_params)\n\n\ndef tsdiag_plot_parameters(cfg):\n \"\"\"Prepeare configuration for TS plots.\"\"\"\n\n # get the dictionary with model file names\n model_filenames = get_clim_model_filenames(cfg, 'thetao')\n model_filenames = OrderedDict(\n sorted(model_filenames.items(), key=lambda t: t[0]))\n # setting the number of columns for the plot\n if cfg['tsdiag_ncol']:\n ncols = cfg['tsdiag_ncol']\n else:\n ncols = 3\n\n plot_params = {}\n plot_params['model_filenames'] = model_filenames\n plot_params['ncols'] = ncols\n plot_params['cmap'] = cm.Set1\n return plot_params\n\n\ndef run_tsdiag(cfg, observations):\n \"\"\"Plot TS diagrams.\n\n Parameters\n ----------\n cfg: dict\n configuration dictionary ESMValTool format.\n observations: str\n name of the observation data set\n \"\"\"\n plot_params = tsdiag_plot_parameters(cfg)\n # loop over models and regions\n for mmodel, region in itertools.product(plot_params['model_filenames'],\n cfg['tsdiag_regions']):\n # this function will generate files with T and S points\n # selected from the region untill `tsdiag_depth` for\n # every model.\n tsplot_data(cfg, mmodel, region, observations=observations)\n\n # actually plot TS diagrams\n for region in cfg['tsdiag_regions']:\n plot_params['region'] = region\n tsplot_plot(cfg, plot_params)\n\n\ndef main(cfg):\n \"\"\"Compute the time average for each input model.\"\"\"\n # for debuging save the configuration in a pickle file\n # with open('cfg_NK.joblib', 'wb') as handle:\n # pickle.dump(cfg, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n logger.info(\"Starting APPLICATE/TRR Arctic Ocean diagnostics\")\n\n # find the name of the observational dataset\n observations = find_observations_name(cfg)\n logger.info(\"Name of the Observations: %s{}\", observations)\n\n # get the names of fx filenames (for now are the same for\n # all variables (this is why \"thetao\" is hardcoded))\n areacello_fx = get_fx_filenames(cfg, 'areacello')\n logger.info(\"areacello_fx files: %s\", areacello_fx)\n\n # Extract data for Hovmoeller diagrams\n run_hofm_data(cfg)\n\n # # Plot Hovmoeller diagrams for each variable\n run_hofm_plot(cfg, observations)\n\n # # Create timemean\n run_mean(cfg, observations)\n\n # Plot average vertical profiles for regions\n run_profiles(cfg, observations)\n\n # Plot 2d maps on original grid\n run_plot2d(cfg)\n\n # Plot model biases over depth\n run_plot2d_bias(cfg, observations)\n\n # Plot transects\n run_transects(cfg)\n\n # Calculate depth and temperature of the Atlantic Water core\n # and make plots.\n aw_core_parameters = run_aw_core(cfg)\n\n # Plot temperature spatial distribution at the depth of the\n # atlantic water core in different models\n run_aw_core_2d(cfg, aw_core_parameters)\n\n # # Plot TS diagrams\n run_tsdiag(cfg, observations)\n\n\nif __name__ == '__main__':\n\n with run_diagnostic() as config:\n main(config)\n"
] | [
[
"numpy.array_equal"
],
[
"sklearn.utils.validation.check_is_fitted",
"numpy.asarray",
"sklearn.exceptions.NotFittedError",
"sklearn.base.clone",
"sklearn.utils.safe_sqr",
"numpy.mean",
"numpy.where",
"numpy.ix_",
"sklearn.utils.check_X_y",
"scipy.sparse.issparse",
"numpy.arange",
"numpy.argmax",
"sklearn.base.is_classifier",
"numpy.ravel",
"sklearn.utils.metaestimators.if_delegate_has_method",
"numpy.logical_not",
"sklearn.metrics.check_scoring",
"sklearn.utils.fixes.parse_version",
"numpy.array",
"numpy.sum",
"sklearn.preprocessing.FunctionTransformer",
"sklearn.utils.check_array",
"numpy.ones",
"sklearn.utils.indexable",
"numpy.isscalar",
"sklearn.linear_model.LinearRegression"
],
[
"numpy.ma.getmaskarray",
"sklearn.model_selection.LeaveOneOut",
"sklearn.metrics.mean_squared_error",
"numpy.ma.masked_invalid",
"numpy.mean",
"numpy.array",
"numpy.empty"
],
[
"matplotlib.backends.backend_pdf.PdfPages",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.close",
"numpy.array",
"matplotlib.pyplot.style.use"
],
[
"matplotlib.pyplot.gca",
"matplotlib.pyplot.subplots",
"pandas.DataFrame"
],
[
"numpy.linspace"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Shirshakk-P/ControlSystems | [
"2a6b147aa583cf5329ce9c84b0d84d72aba2bda4"
] | [
"x11/massSpringParam1.py"
] | [
"#Mass Spring Damper system Parameter File\r\nimport numpy as np\r\nimport control as cnt\r\nimport sys\r\nsys.path.append('..') #add parent directory\r\nimport massSpringParam as P\r\n\r\nTs = P.Ts\r\nbeta = P.beta\r\ntau_max = P.tau_max\r\nm = P.m\r\nk = P.k\r\nb = P.b\r\n\r\n#tuning parameters\r\n#tr=1.6 #previous homework was done on the basis of tr=1.6 and step input is taken from this homework onwards\r\ntr = 1.5\r\nzeta = 0.7\r\n\r\n#State Space Equations\r\n# xdot = A*x + B*u\r\n# y = C*x\r\nA = np.array([[0.0, 1.0],\r\n [-P.k/P.m, -P.b/P.m]])\r\nB = np.array([[0.0],\r\n [1.0/P.m]])\r\nC = np.array([[1.0, 0.0]])\r\n\r\n#gain calculation\r\nwn = 2.2/tr #natural frequency\r\ndes_char_poly = [1, 2*zeta*wn, wn**2]\r\ndes_poles = np.roots(des_char_poly)\r\n\r\n#Compute the gains if the system is controllable\r\nif np.linalg.matrix_rank(cnt.ctrb(A, B)) != 2:\r\n print(\"The system is not controllable\")\r\nelse:\r\n #.A just turns K matrix into a numpy array\r\n K = (cnt.acker(A, B, des_poles)).A\r\n kr = -1.0/(C @ np.linalg.inv(A - B @ K) @ B)\r\n \r\nprint('K: ', K)\r\nprint('kr: ', kr)\r\n"
] | [
[
"numpy.roots",
"numpy.array",
"numpy.linalg.inv"
]
] | [
{
"matplotlib": [],
"numpy": [
"1.10",
"1.12",
"1.11",
"1.19",
"1.24",
"1.13",
"1.16",
"1.9",
"1.18",
"1.23",
"1.21",
"1.22",
"1.20",
"1.7",
"1.15",
"1.14",
"1.17",
"1.8"
],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
gobaRules/eo-learn | [
"25174e5e0759e35b616712423f01b03527a4b227",
"25174e5e0759e35b616712423f01b03527a4b227"
] | [
"visualization/eolearn/visualization/eoexecutor_visualization.py",
"visualization/eolearn/visualization/xarray_utils.py"
] | [
"\"\"\"\nModule with utilities for vizualizing EOExecutor\n\"\"\"\n\nimport os\nimport inspect\nimport warnings\nimport base64\nimport copy\n\ntry:\n import matplotlib.pyplot as plt\nexcept ImportError:\n import matplotlib\n matplotlib.use('agg')\n import matplotlib.pyplot as plt\n\nimport graphviz\nimport pygments\nimport pygments.lexers\nfrom pygments.formatters.html import HtmlFormatter\nfrom jinja2 import Environment, FileSystemLoader\n\n\nclass EOExecutorVisualization:\n \"\"\" Class handling EOExecutor visualizations, particularly creating reports\n \"\"\"\n\n def __init__(self, eoexecutor):\n \"\"\"\n :param eoexecutor: An instance of EOExecutor\n :type eoexecutor: EOExecutor\n \"\"\"\n self.eoexecutor = eoexecutor\n\n def make_report(self):\n \"\"\" Makes a html report and saves it into the same folder where logs are stored.\n \"\"\"\n if self.eoexecutor.execution_stats is None:\n raise RuntimeError('Cannot produce a report without running the executor first, check EOExecutor.run '\n 'method')\n\n if os.environ.get('DISPLAY', '') == '':\n plt.switch_backend('Agg')\n\n try:\n dependency_graph = self._create_dependency_graph()\n except graphviz.backend.ExecutableNotFound as ex:\n dependency_graph = None\n warnings.warn(\"{}.\\nPlease install the system package 'graphviz' (in addition \"\n \"to the python package) to have the dependency graph in the final report!\".format(ex),\n Warning, stacklevel=2)\n\n task_descriptions = self._get_task_descriptions()\n\n formatter = HtmlFormatter(linenos=True)\n task_source = self._render_task_source(formatter)\n execution_stats = self._render_execution_errors(formatter)\n\n template = self._get_template()\n\n html = template.render(dependency_graph=dependency_graph,\n task_descriptions=task_descriptions,\n task_source=task_source,\n execution_stats=execution_stats,\n execution_logs=self.eoexecutor.execution_logs,\n code_css=formatter.get_style_defs())\n\n if not os.path.isdir(self.eoexecutor.report_folder):\n os.mkdir(self.eoexecutor.report_folder)\n\n with open(self.eoexecutor.get_report_filename(), 'w') as fout:\n fout.write(html)\n\n def _create_dependency_graph(self):\n \"\"\" Provides an image of dependecy graph\n \"\"\"\n dot = self.eoexecutor.workflow.dependency_graph()\n return base64.b64encode(dot.pipe()).decode()\n\n def _get_task_descriptions(self):\n \"\"\" Prepares a list of task names and their initialization parameters\n \"\"\"\n descriptions = []\n\n for task_id, dependency in self.eoexecutor.workflow.uuid_dict.items():\n task = dependency.task\n\n init_args = {key: value.replace('<', '<').replace('>', '>') for key, value in\n task.private_task_config.init_args.items()}\n\n desc = {\n 'title': \"{}_{} ({})\".format(task.__class__.__name__, task_id[:6], task.__module__),\n 'args': init_args\n }\n descriptions.append(desc)\n\n return descriptions\n\n def _render_task_source(self, formatter):\n \"\"\" Collects source code of each costum task\n \"\"\"\n lexer = pygments.lexers.get_lexer_by_name(\"python\", stripall=True)\n sources = {}\n\n for dep in self.eoexecutor.workflow.dependencies:\n task = dep.task\n if task.__module__.startswith(\"eolearn\"):\n continue\n\n key = \"{} ({})\".format(task.__class__.__name__, task.__module__)\n if key in sources:\n continue\n\n try:\n source = inspect.getsource(task.__class__)\n source = pygments.highlight(source, lexer, formatter)\n except TypeError:\n # Jupyter notebook does not have __file__ method to collect source code\n # StackOverflow provides no solutions\n # Could be investigated further by looking into Jupyter Notebook source code\n source = 'Cannot collect source code of a task which is not defined in a .py file'\n\n sources[key] = source\n\n return sources\n\n def _render_execution_errors(self, formatter):\n \"\"\" Renders stack traces of those executions which failed\n \"\"\"\n tb_lexer = pygments.lexers.get_lexer_by_name(\"py3tb\", stripall=True)\n\n executions = []\n\n for orig_execution in self.eoexecutor.execution_stats:\n execution = copy.deepcopy(orig_execution)\n\n if self.eoexecutor.STATS_ERROR in execution:\n execution[self.eoexecutor.STATS_ERROR] = pygments.highlight(execution[self.eoexecutor.STATS_ERROR],\n tb_lexer, formatter)\n\n executions.append(execution)\n\n return executions\n\n def _get_template(self):\n \"\"\" Loads and sets up a template for report\n \"\"\"\n templates_dir = os.path.join(os.path.dirname(__file__), 'report_templates')\n env = Environment(loader=FileSystemLoader(templates_dir))\n env.filters['datetime'] = self._format_datetime\n env.globals.update(timedelta=self._format_timedelta)\n template = env.get_template(self.eoexecutor.REPORT_FILENAME)\n\n return template\n\n @staticmethod\n def _format_datetime(value):\n \"\"\" Method for formatting datetime objects into report\n \"\"\"\n return value.strftime('%X %x %Z')\n\n @staticmethod\n def _format_timedelta(value1, value2):\n \"\"\" Method for formatting time delta into report\n \"\"\"\n return str(value2 - value1)\n",
"\"\"\"\nThis module implements conversion from/to xarray DataArray/Dataset\n\"\"\"\n\nimport re\nimport numpy as np\nimport xarray as xr\n\nfrom sentinelhub import BBox\n\nfrom eolearn.core import FeatureTypeSet, FeatureParser\n\n\ndef string_to_variable(string, extension=None):\n \"\"\"\n\n :param string: string to be used as python variable name\n :type string: str\n :param extension: string to be appended to string\n :type extension: str\n :return: valid python variable name\n :rtype: str\n \"\"\"\n\n string = re.sub('[^0-9a-zA-Z_]', '', string)\n string = re.sub('^[^a-zA-Z_]+', '', string)\n if extension:\n string += extension\n\n return string\n\n\ndef _get_spatial_coordinates(bbox, data, feature_type):\n \"\"\" Returns spatial coordinates (dictionary) for creating xarray DataArray/Dataset\n Makes sense for data\n\n :param bbox: eopatch bbox\n :type bbox: EOPatch BBox\n :param data: values for calculating number of coordinates\n :type data: numpy array\n :param feature_type: type of the feature\n :type feature_type: FeatureType\n :return: spatial coordinates\n :rtype: dict {'x':, 'y':}\n \"\"\"\n if not (feature_type.is_spatial() and feature_type.is_raster()):\n raise ValueError('Data should be raster and have spatial dimension')\n index_x, index_y = 2, 1\n if feature_type.is_timeless():\n index_x, index_y = 1, 0\n pixel_width = (bbox.max_x - bbox.min_x)/data.shape[index_x]\n pixel_height = (bbox.max_y - bbox.min_y)/data.shape[index_y]\n\n return {'x': np.linspace(bbox.min_x+pixel_width/2, bbox.max_x-pixel_width/2, data.shape[index_x]),\n 'y': np.linspace(bbox.max_y-pixel_height/2, bbox.min_y+pixel_height/2, data.shape[index_y])}\n\n\ndef _get_temporal_coordinates(timestamps):\n \"\"\" Returns temporal coordinates dictionary for creating xarray DataArray/Dataset\n\n :param timestamps: timestamps\n :type timestamps: EOpatch.timestamp\n :return: temporal coordinates\n :rtype: dict {'time': }\n \"\"\"\n return {'time': timestamps}\n\n\ndef _get_depth_coordinates(feature_name, data, names_of_channels=None):\n \"\"\" Returns band/channel/dept coordinates for xarray DataArray/Dataset\n\n :param feature_name: name of feature of EOPatch\n :type feature_name: FeatureType\n :param data: data of EOPatch\n :type data: numpy.array\n :param names_of_channels: coordinates for the last (band/dept/chanel) dimension\n :type names_of_channels: list\n :return: depth/band coordinates\n :rtype: dict\n \"\"\"\n coordinates = {}\n depth = string_to_variable(feature_name, '_dim')\n if names_of_channels:\n coordinates[depth] = names_of_channels\n elif isinstance(data, np.ndarray):\n coordinates[depth] = np.arange(data.shape[-1])\n\n return coordinates\n\n\ndef get_coordinates(eopatch, feature, crs):\n \"\"\" Creates coordinates for xarray DataArray\n\n :param eopatch: eopatch\n :type eopatch: EOPatch\n :param feature: feature of eopatch\n :type feature: (FeatureType, str)\n :param crs: convert spatial coordinates to crs\n :type crs: sentinelhub.crs\n :return: coordinates for xarry DataArray/Dataset\n :rtype: dict\n \"\"\"\n\n features = list(FeatureParser(feature))\n feature_type, feature_name = features[0]\n original_crs = eopatch.bbox.crs\n if crs and original_crs != crs:\n bbox = eopatch.bbox.transform(crs)\n else:\n bbox = eopatch.bbox\n data = eopatch[feature_type][feature_name]\n timestamps = eopatch.timestamp\n\n if feature_type in FeatureTypeSet.RASTER_TYPES_4D:\n return {**_get_temporal_coordinates(timestamps),\n **_get_spatial_coordinates(bbox, data, feature_type),\n **_get_depth_coordinates(data=data, feature_name=feature_name)}\n if feature_type in FeatureTypeSet.RASTER_TYPES_2D:\n return {**_get_temporal_coordinates(timestamps),\n **_get_depth_coordinates(data=data, feature_name=feature_name)}\n if feature_type in FeatureTypeSet.RASTER_TYPES_3D:\n return {**_get_spatial_coordinates(bbox, data, feature_type),\n **_get_depth_coordinates(data=data, feature_name=feature_name)}\n return _get_depth_coordinates(data=data, feature_name=feature_name)\n\n\ndef get_dimensions(feature):\n \"\"\" Returns list of dimensions for xarray DataArray/Dataset\n\n :param feature: eopatch feature\n :type feature: (FeatureType, str)\n :return: dimensions for xarray DataArray/Dataset\n :rtype: list(str)\n \"\"\"\n features = list(FeatureParser(feature))\n feature_type, feature_name = features[0]\n depth = string_to_variable(feature_name, '_dim')\n if feature_type in FeatureTypeSet.RASTER_TYPES_4D:\n return ['time', 'y', 'x', depth]\n if feature_type in FeatureTypeSet.RASTER_TYPES_2D:\n return ['time', depth]\n if feature_type in FeatureTypeSet.RASTER_TYPES_3D:\n return ['y', 'x', depth]\n return [depth]\n\n\ndef array_to_dataframe(eopatch, feature, remove_depth=True, crs=None):\n \"\"\" Converts one feature of eopatch to xarray DataArray\n\n :param eopatch: eopatch\n :type eopatch: EOPatch\n :param feature: feature of eopatch\n :type feature: (FeatureType, str)\n :param remove_depth: removes last dimension if it is one\n :type remove_depth: bool\n :param crs: converts dimensions to crs\n :type crs: sentinelhub.crs\n :return: dataarray\n :rtype: xarray DataArray\n \"\"\"\n features = list(FeatureParser(feature))\n feature_type, feature_name = features[0]\n bbox = eopatch.bbox\n data = eopatch[feature_type][feature_name]\n if isinstance(data, xr.DataArray):\n data = data.values\n dimensions = get_dimensions(feature)\n coordinates = get_coordinates(eopatch, feature, crs=crs)\n dataframe = xr.DataArray(data=data,\n coords=coordinates,\n dims=dimensions,\n attrs={'crs': str(bbox.crs),\n 'feature_type': feature_type,\n 'feature_name': feature_name},\n name=string_to_variable(feature_name))\n\n if remove_depth and dataframe.values.shape[-1] == 1:\n dataframe = dataframe.squeeze()\n dataframe = dataframe.drop(feature_name + '_dim')\n\n return dataframe\n\n\ndef eopatch_to_dataset(eopatch, remove_depth=True):\n \"\"\"\n Converts eopatch to xarray Dataset\n\n :param eopatch: eopathc\n :type eopatch: EOPatch\n :param remove_depth: removes last dimension if it is one\n :type remove_depth: bool\n :return: dataset\n :rtype: xarray Dataset\n \"\"\"\n dataset = xr.Dataset()\n for feature in eopatch.get_feature_list():\n if not isinstance(feature, tuple):\n continue\n feature_type = feature[0]\n feature_name = feature[1]\n if feature_type.is_raster():\n dataframe = array_to_dataframe(eopatch, (feature_type, feature_name), remove_depth)\n dataset[feature_name] = dataframe\n\n return dataset\n\n\ndef new_coordinates(data, crs, new_crs):\n \"\"\" Returns coordinates for xarray DataArray/Dataset in new crs.\n\n :param data: data for converting coordinates for\n :type data: xarray.DataArray or xarray.Dataset\n :param crs: old crs\n :type crs: sentinelhub.CRS\n :param new_crs: new crs\n :type new_crs: sentinelhub.CRS\n :return: new x and y coordinates\n :rtype: (float, float)\n \"\"\"\n x_values = data.coords['x'].values\n y_values = data.coords['y'].values\n bbox = BBox((x_values[0], y_values[0], x_values[-1], y_values[-1]), crs=crs)\n bbox = bbox.transform(new_crs)\n xmin, ymin = bbox.get_lower_left()\n xmax, ymax = bbox.get_upper_right()\n new_xs = np.linspace(xmin, xmax, len(x_values))\n new_ys = np.linspace(ymin, ymax, len(y_values))\n\n return new_xs, new_ys\n"
] | [
[
"matplotlib.pyplot.switch_backend",
"matplotlib.use"
],
[
"numpy.arange",
"numpy.linspace"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
rubyshamir/cDC | [
"c4ebef2ff96e65e197c6c995fb896f72d50de747"
] | [
"continuous_Dice_coefficient.py"
] | [
"import numpy as np\r\n\r\n'''\r\nImplementation of the continuous Dice Coefficient (https://www.biorxiv.org/content/10.1101/306977v1.full.pdf)\r\n\"Continuous Dice Coefficient: a Method for Evaluating Probabilistic Segmentations\"\r\nReuben R Shamir,Yuval Duchin, Jinyoung Kim, Guillermo Sapiro, and Noam Harel\r\n\r\nInput:\r\nA - ground-truth or gold-standard binary segmentation (expert labeled data; assumes values are 0 or 1)\r\nB - segmentation probabilistic map (your algorithm's output; assumes values are between 0-1)\r\n\r\nAuthor: Ruby Shamir (feedback is welcome at shamir.ruby at gmail)\r\n'''\r\n\r\ndef continous_Dice_coefficient(A_binary, B_probability_map):\r\n\r\n AB = A_binary * B_probability_map\r\n c = np.sum(AB)/max(np.size(AB[AB>0]), 1)\r\n cDC = 2*(np.sum(AB))/(c*np.sum(A_binary) + np.sum(B_probability_map))\r\n\r\n return cDC\r\n\r\ndef Dice_coefficient(A_binary, B_binary):\r\n\r\n AB = A_binary * B_binary\r\n DC = 2*(np.sum(AB))/(np.sum(A_binary) + np.sum(B_binary))\r\n\r\n return DC\r\n\r\ndef simulate_probablistic_segmentation (start, end):\r\n x, y = np.meshgrid(np.linspace(start, end, 100), np.linspace(start, end, 100))\r\n d = np.array(np.sqrt(x * x + y * y))\r\n mu = 0.0\r\n sigma = 2.0\r\n segmentation_result = np.exp(-((d - mu) * (d - mu) / (2.0 * sigma * sigma)))\r\n segmentation_result[segmentation_result<0.01] = 0\r\n return segmentation_result\r\n\r\n\r\n## compare Dice and continous Dice under simulated error #########\r\nif __name__ == '__main__':\r\n\r\n # in this example we simulate a ground truth segmentation (circle) and probabilistic segmentation results (gaussian)\r\n # the we demonstrate the cDC is less sensitive for shifts in segmentation than Dice Coefficient\r\n\r\n all_cDice = list()\r\n all_Dice = list()\r\n\r\n start = -10\r\n end = 10\r\n segmentation_result = simulate_probablistic_segmentation (start, end)\r\n\r\n ground_truth_simulated = np.ones_like(segmentation_result)\r\n ground_truth_simulated[segmentation_result < 0.01] = 0\r\n\r\n cDC = continous_Dice_coefficient(ground_truth_simulated, segmentation_result)\r\n all_cDice.append(cDC)\r\n binary_segmentation_result = np.zeros_like(segmentation_result)\r\n binary_segmentation_result[segmentation_result > 0.01] = 1\r\n DC = Dice_coefficient(ground_truth_simulated, binary_segmentation_result)\r\n all_Dice.append(DC)\r\n step = 2\r\n for shift in range(0, 4):\r\n segmentation_result = np.hstack((segmentation_result, np.zeros((segmentation_result.shape[0],step))))\r\n segmentation_result = np.delete(segmentation_result, range(0, step),1)\r\n\r\n cDC = continous_Dice_coefficient(ground_truth_simulated, segmentation_result)\r\n all_cDice.append(cDC)\r\n\r\n binary_segmentation_result = np.zeros_like(segmentation_result)\r\n binary_segmentation_result[segmentation_result>0.01] = 1\r\n # when the input is binary continues Dice Coefficient returns the Dice Coefficient.\r\n DC = Dice_coefficient(ground_truth_simulated, binary_segmentation_result)\r\n all_Dice.append(DC)\r\n\r\n all_cDice = [str(round(val,2)) for val in all_cDice]\r\n all_Dice = [str(round(val, 2)) for val in all_Dice]\r\n\r\n print ('Shift errors of: (mm)')\r\n print ([str(round(i,2)) for i in range(0, 10, 2)])\r\n print('Reduced the continues Dice:')\r\n print (all_cDice)\r\n print('And the original Dice is:')\r\n print (all_Dice)\r\n\r\n"
] | [
[
"numpy.ones_like",
"numpy.sqrt",
"numpy.linspace",
"numpy.size",
"numpy.zeros_like",
"numpy.exp",
"numpy.zeros",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
DilipJainDj/Flower-Image-Classifier | [
"ab7c47d176b12bae51ee33e427f3d95c57d07416"
] | [
"predict.py"
] | [
"\"\"\"\n@author: Dilip Jain\n@title: Image Classifier training file\n\"\"\"\n\nimport argparse\nimport json\nimport PIL\nimport torch\nimport numpy as np\n\nfrom math import ceil\nfrom train import check_gpu\nfrom torchvision import models\n\n# ------------------------------------------------------------------------------- #\n# Function Definitions\n# ------------------------------------------------------------------------------- #\n# Function arg_parser() parses keyword arguments from the command line\ndef arg_parser():\n # Define a parser\n parser = argparse.ArgumentParser(description=\"Neural Network Settings\")\n\n # Point towards image for prediction\n parser.add_argument('--image', type=str, help='Point to impage file for prediction.',required=True)\n\n # Load checkpoint created by train.py\n parser.add_argument('--checkpoint', type=str, help='Point to checkpoint file as str.',required=True)\n \n # Specify top-k\n parser.add_argument('--top_k', type=int, help='Choose top K matches as int.')\n \n # Import category names\n parser.add_argument('--category_names', type=str, help='Mapping from categories to real names.')\n\n # Add GPU Option to parser\n parser.add_argument('--gpu', action=\"store_true\", help='Use GPU + Cuda for calculations')\n\n # Parse args\n args = parser.parse_args()\n \n return args\n\n# Function load_checkpoint(checkpoint_path) loads our saved deep learning model from checkpoint\ndef load_checkpoint(checkpoint_path):\n # Load the saved file\n checkpoint = torch.load(\"my_checkpoint.pth\")\n \n # Load Defaults if none specified\n if checkpoint['architecture'] == 'vgg16':\n model = models.vgg16(pretrained=True)\n model.name = \"vgg16\"\n else: \n exec(\"model = models.{}(pretrained=True)\".checkpoint['architecture'])\n model.name = checkpoint['architecture']\n \n # Freeze parameters so we don't backprop through them\n for param in model.parameters(): param.requires_grad = False\n \n # Load stuff from checkpoint\n model.class_to_idx = checkpoint['class_to_idx']\n model.classifier = checkpoint['classifier']\n model.load_state_dict(checkpoint['state_dict'])\n \n return model\n\n# Function process_image(image_path) performs cropping, scaling of image for our model\ndef process_image(image_path):\n test_image = PIL.Image.open(image_path)\n\n # Get original dimensions\n orig_width, orig_height = test_image.size\n\n # Find shorter size and create settings to crop shortest side to 256\n if orig_width < orig_height: resize_size=[256, 256**600]\n else: resize_size=[256**600, 256]\n \n test_image.thumbnail(size=resize_size)\n\n # Find pixels to crop on to create 224x224 image\n center = orig_width/4, orig_height/4\n left, top, right, bottom = center[0]-(244/2), center[1]-(244/2), center[0]+(244/2), center[1]+(244/2)\n test_image = test_image.crop((left, top, right, bottom))\n\n # Converrt to numpy - 244x244 image w/ 3 channels (RGB)\n np_image = np.array(test_image)/255 # Divided by 255 because imshow() expects integers (0:1)!!\n\n # Normalize each color channel\n normalise_means = [0.485, 0.456, 0.406]\n normalise_std = [0.229, 0.224, 0.225]\n np_image = (np_image-normalise_means)/normalise_std\n \n # Set the color to the first channel\n np_image = np_image.transpose(2, 0, 1)\n \n return np_image\n\n\ndef predict(image_tensor, model, device, cat_to_name, top_k):\n ''' Predict the class (or classes) of an image using a trained deep learning model.\n \n image_path: string. Path to image, directly to image and not to folder.\n model: pytorch neural network.\n top_k: integer. The top K classes to be calculated\n \n returns top_probabilities(k), top_labels\n '''\n \n # check top_k\n if type(top_k) == type(None):\n top_k = 5\n print(\"Top K not specified, assuming K=5.\")\n \n # Set model to evaluate\n model.eval();\n\n # Convert image from numpy to torch\n torch_image = torch.from_numpy(np.expand_dims(image_tensor, \n axis=0)).type(torch.FloatTensor)\n\n model=model.cpu()\n\n # Find probabilities (results) by passing through the function (note the log softmax means that its on a log scale)\n log_probs = model.forward(torch_image)\n\n # Convert to linear scale\n linear_probs = torch.exp(log_probs)\n\n # Find the top 5 results\n top_probs, top_labels = linear_probs.topk(top_k)\n \n # Detatch all of the details\n top_probs = np.array(top_probs.detach())[0] # This is not the correct way to do it but the correct way isnt working thanks to cpu/gpu issues so I don't care.\n top_labels = np.array(top_labels.detach())[0]\n \n # Convert to classes\n idx_to_class = {val: key for key, val in \n model.class_to_idx.items()}\n top_labels = [idx_to_class[lab] for lab in top_labels]\n top_flowers = [cat_to_name[lab] for lab in top_labels]\n \n return top_probs, top_labels, top_flowers\n\n\ndef print_probability(probs, flowers):\n \"\"\"\n Converts two lists into a dictionary to print on screen\n \"\"\"\n \n for i, j in enumerate(zip(flowers, probs)):\n print (\"Rank {}:\".format(i+1),\n \"Flower: {}, liklihood: {}%\".format(j[1], ceil(j[0]*100)))\n \n\n# =============================================================================\n# Main Function\n# =============================================================================\n\ndef main():\n \"\"\"\n Executing relevant functions\n \"\"\"\n \n # Get Keyword Args for Prediction\n args = arg_parser()\n \n # Load categories to names json file\n with open(args.category_names, 'r') as f:\n \tcat_to_name = json.load(f)\n\n # Load model trained with train.py\n model = load_checkpoint(args.checkpoint)\n \n # Process Image\n image_tensor = process_image(args.image)\n \n # Check for GPU\n device = check_gpu(gpu_arg=args.gpu);\n \n # Use `processed_image` to predict the top K most likely classes\n top_probs, top_labels, top_flowers = predict(image_tensor, model, \n device, cat_to_name,\n args.top_k)\n \n # Print out probabilities\n print_probability(top_flowers, top_probs)\n\n# =============================================================================\n# Run Program\n# =============================================================================\nif __name__ == '__main__': main()\n"
] | [
[
"torch.exp",
"numpy.array",
"numpy.expand_dims",
"torch.load"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
pbattaglia/scenesim | [
"6ff41c1428a32c078104332431906f4faa0990db"
] | [
"scenesim/display/geometry.py"
] | [
"\"\"\"\n``scenesim.display.geometry``\n=============================\n\nFunctions for manipulating graphics geometry.\n\n\"\"\"\nimport numpy as np\n\n\ndef zbuffer_to_z(zb, near, far):\n \"\"\"Inputs Z-buffer image and returns each pixel's distance from the\n camera along the Z-axis.\n\n Args:\n zb (numpy.ndarray, 2D): Z-buffer image.\n near (float): Distance of near camera plane.\n far (float): Distance of far camera plane.\n\n Return:\n (numpy.ndarray, 2D): Z-distance of each pixel.\n\n \"\"\"\n z = far * near / (far - zb * (far - near))\n return z\n\n\ndef img_to_d(xi, yi, zb, near, far):\n \"\"\"Inputs image X, Y coordinates and Z-buffer image, and returns\n Euclidean distance from the camera's position to each point.\n\n Args:\n xi, yi (numpy.ndarray, 2D): X-, Y-coordinates of each pixel.\n zb (numpy.ndarray, 2D): Z-buffer image.\n near (float): Distance of near camera plane.\n far (float): Distance of far camera plane.\n\n Return:\n (numpy.ndarray, 2D): Euclidean distance of each pixel.\n\n \"\"\"\n z = zbuffer_to_z(zb, near, far)\n phi = np.arctan2(np.sqrt(xi ** 2 + yi ** 2), near)\n d = z / np.cos(phi)\n return d\n\n\ndef img_to_xyz(xi, yi, zb, near, far):\n \"\"\"Inputs image X, Y coordinates and Z-buffer image, and returns the\n pixels' X, Y, Z coordinates in 3D.\n\n Args:\n xi, yi (numpy.ndarray, 2D): X-, Y-coordinates of each pixel.\n zb (numpy.ndarray, 2D): Z-buffer image.\n near (float): Distance of near camera plane.\n far (float): Distance of far camera plane.\n\n Return:\n (numpy.ndarray, 3x2D): X-, Y-, Z-coordinates of each pixel.\n\n \"\"\"\n z = zbuffer_to_z(zb, near, far)\n x = xi * z / near\n y = yi * z / near\n xyz = np.array((x, y, z))\n return xyz\n\n\ndef get_projection_mat(camera):\n \"\"\"Projection matrix of camera.\n\n Args:\n camera (panda3d.core.NodePath): Camera NodePath.\n\n Return:\n (numpy.matrix, 4x4): Projection matrix (homogeneous).\n \n \"\"\"\n lens = camera.node().getLens()\n frust_mat = np.matrix(lens.getProjectionMat())\n cam_mat = np.matrix(camera.getNetTransform().getMat())\n proj_mat = cam_mat.I * frust_mat\n return proj_mat\n\n\ndef extrude(point2d, proj_mat):\n \"\"\"Compute the 3D inverse perspective projection of a 2D point.\n\n Args:\n point2d (numpy.ndarray, Nx2): Array of 2D points.\n proj_mat (numpy.matrix, 4x4): Projection matrix (homogeneous).\n\n Return:\n (numpy.ndarray, Nx3): Array of inverse projected 3D points.\n\n \"\"\"\n # Inverse projection matrix\n proj_mat_inv = np.linalg.inv(proj_mat)\n # calculate the near and far points\n hp2 = np.array(((point2d[0], point2d[1], -1., 1.),\n (point2d[0], point2d[1], 1., 1.)))\n hp3 = np.dot(hp2, proj_mat_inv)\n scale = hp3[:, [3]].copy()\n thresh = 0.00001\n scale[(scale > 0) & (scale < thresh)] = thresh\n scale[(scale < 0) & (scale > -thresh)] = -thresh\n point3d = np.array(hp3[:, :3] / scale)\n return point3d\n\n\ndef project(point3d, proj_mat):\n \"\"\" Compute the 2D perspective projection of 3D point(s).\n\n Args:\n point3d (numpy.ndarray, Nx{3,4}): Array of 3D (or 4D, if homogeneous) points.\n proj_mat (numpy.matrix, 4x4): Projection matrix (homogeneous).\n\n Return:\n (numpy.ndarray, Nx2): Array of inverse projected 2D points.\n \n (numpy.ndarray, N): Indicates points that are behind the camera.\n \n \"\"\"\n # Cast to np.array\n point3d = np.array(point3d)\n if point3d.ndim == 1:\n # Add dimension in front, if necessary\n point3d = point3d[None, :]\n # Make homogeneous coordinates from point3d\n d1len = point3d.shape[1]\n if d1len == 3:\n hp3 = np.hstack((point3d, np.ones(point3d.shape[0])[:, None]))\n elif d1len == 4:\n hp3 = point3d\n else:\n raise ValueError(\"point3d must be either Nx{3,4}, but it is %i\" %\n d1len)\n # Compute the linear portion of the projection\n hp2 = np.dot(hp3, proj_mat)\n # Compute z-scaling\n point2d = np.array(hp2[:, :2] / hp2[:, [3]])\n f_behind = hp2[:, 2] < 0\n return point2d, f_behind\n\n\ndef plane_intersection(line3, point3, normal3):\n \"\"\" Compute point of intersection between a line and a plane.\n\n Args:\n line3 (numpy.ndarray, 2x3): 3D line defined by endpoints.\n point3 (numpy.ndarray, 3): 3D point on the plane.\n normal3 (numpy.ndarray, 3): 3D normal to the plane.\n\n Return:\n (numpy.ndarray, 3): 3D intersection point.\n \n \"\"\"\n # Line ray\n ray = np.diff(line3, axis=0).ravel()\n # https://en.wikipedia.org/wiki/Line-plane_intersection\n d = np.dot(point3 - line3[0], normal3) / np.dot(ray, normal3)\n # Intersection point\n p3 = d * ray + line3[0]\n return p3\n"
] | [
[
"numpy.dot",
"numpy.sqrt",
"numpy.linalg.inv",
"numpy.cos",
"numpy.ones",
"numpy.diff",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
NickWilkinson37/voxseg | [
"6402a67c0b4ee68115070b6aa870199d1f43c5a2"
] | [
"voxseg/run_cnnlstm.py"
] | [
"# Module for running CNN-BiLSTM vad model,\n# may also be run directly as a script\n# Author: Nick Wilkinson 2021\nimport argparse\nimport os\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom typing import Tuple\nfrom tensorflow.keras import models\nfrom voxseg import utils\nfrom scipy.signal import medfilt\n\ngpus = tf.config.experimental.list_physical_devices('GPU')\nif gpus:\n # Restrict TensorFlow to only use the first GPU, quick enough for decoding\n try:\n tf.config.experimental.set_visible_devices(gpus[0], 'GPU')\n except RuntimeError as e:\n # Visible devices must be set before GPUs have been initialized\n print(e)\nsession_conf = tf.compat.v1.ConfigProto(intra_op_parallelism_threads=10,inter_op_parallelism_threads=10)\nsess = tf.compat.v1.Session(config=session_conf)\n\n\ndef decode(targets: pd.DataFrame, speech_thresh: float = 0.5, speech_w_music_thresh: float = 0.5, filt: int = 1) -> pd.DataFrame:\n '''Function for converting target sequences within a pd.DataFrame to endpoints.\n\n Args:\n targets: A pd.DataFrame containing predicted targets (in array form) and metadata.\n speech_thresh (optional): A decision threshold between 0 and 1 for the speech class, lower values\n result in more frames being classified as speech. (Default: 0.5)\n speech_w_music_thresh (optional): A decision threshold between 0 and 1 for the speech_with_music class.\n Setting this threshold higher will filter out more music which may be desirable for ASR. (Default: 0.5)\n filt (optional): a kernel size for the median filter to apply to the output labels for smoothing. (Default: 1)\n\n Returns:\n A pd.DataFrame containing speech segment endpoints and metadata.\n '''\n\n targets = targets.copy()\n if targets['predicted-targets'].iloc[0].shape[-1] == 4:\n prior = np.array([(1-speech_thresh) * speech_w_music_thresh,\n speech_thresh * speech_w_music_thresh,\n (1-speech_thresh) * (1-speech_w_music_thresh),\n (1-speech_thresh) * speech_w_music_thresh])\n temp = pd.concat([_targets_to_endpoints(medfilt([0 if (j*prior).argmax() == 1 else 1 for j in i], filt), 0.32) \\\n for i in targets['predicted-targets']], ignore_index=True)\n elif targets['predicted-targets'].iloc[0].shape[-1] == 2:\n prior = np.array([speech_thresh,\n 1-speech_thresh])\n temp = pd.concat([_targets_to_endpoints(medfilt([0 if (j*prior).argmax() == 0 else 1 for j in i], filt), 0.32) \\\n for i in targets['predicted-targets']], ignore_index=True)\n else:\n print(f'ERROR: model provided has {targets[\"predicted-targets\"].iloc[0].shape[-1]} outputs. Model expected to have 2 or 4 outputs.')\n if 'start' in targets.columns:\n targets['end'] = targets['start'] + temp['end']\n targets['start'] = targets['start'] + temp['start']\n else:\n targets['start'] = temp['start']\n targets['end'] = temp['end']\n targets = targets.drop(['predicted-targets'], axis=1)\n targets = targets.apply(pd.Series.explode).reset_index(drop=True)\n targets['utterance-id'] = targets['recording-id'].astype(str) + '_' + \\\n ((targets['start'] * 100).astype(int)).astype(str).str.zfill(7) + '_' + \\\n ((targets['end'] * 100).astype(int)).astype(str).str.zfill(7)\n return targets\n\n\ndef predict_targets(model: tf.keras.Model, features: pd.DataFrame) -> pd.DataFrame:\n '''Function for applying a pretrained model to predict targets from features.\n\n Args:\n model: A pretrained tf.keras model.\n features: A pd.DataFrame containing features and metadata.\n\n Returns:\n A pd.DataFrame containing predicted targets and metadata. \n '''\n\n targets = features.drop(['normalized-features'], axis=1)\n print('------------------- Running VAD -------------------')\n targets['predicted-targets'] = _predict(model, features['normalized-features'])\n return targets\n \n\ndef to_data_dir(endpoints: pd.DataFrame, out_dir: str) -> None:\n '''A function for generating a Kaldi-style data directory output of the dicovered speech segments.\n \n Args:\n endpoints: A pd.DataFrame containing speech segment endpoints and metadata.\n out_dir: A path to an output directory where data files will be placed.\n '''\n\n if not os.path.exists(out_dir):\n print(f'Directory {out_dir} does not exist, creating it.')\n os.mkdir(out_dir)\n endpoints[['recording-id', 'extended filename']].drop_duplicates().to_csv(\n f'{out_dir}/wav.scp',sep=' ', index=False, header=False)\n pd.concat([endpoints[['utterance-id', 'recording-id']], endpoints[['start', 'end']].astype(float).round(3)],\n axis=1).to_csv(f'{out_dir}/segments', sep=' ', index=False, header=False)\n\n\ndef _predict(model: tf.keras.Model, col: pd.Series) -> pd.Series:\n '''Auxiliary function used by predict_targets(). Applies a pretrained model to \n each feature set in the 'normalized-features' or 'features' column of a pd.DataFrame\n containing features and metadata.\n\n Args:\n model: A pretrained tf.keras model.\n col: A column of a pd.DataFrame containing features.\n\n Returns:\n A pd.Series containing the predicted target sequences. \n '''\n\n targets = []\n for features in col:\n #temp = model.predict(utils.time_distribute(features, 15)[:,:,:,:,np.newaxis])\n temp = model.predict(features[np.newaxis,:,:,:,np.newaxis])\n targets.append(temp.reshape(-1, temp.shape[-1]))\n return pd.Series(targets)\n\n\ndef _targets_to_endpoints(targets: np.ndarray, frame_length: float) -> pd.DataFrame:\n '''Auxilory function used by decode() for converting a target sequence to endpoints.\n\n Args:\n targets: A binary np.ndarray of speech/nonspeech targets where 1 indicates the presence of speech.\n frame_length: The length of each target in seconds.\n\n Returns:\n A pd.DataFrame, containing the speech segment start and end boundaries in arrays.\n '''\n \n starts = []\n ends = []\n state = 0\n for n, i in enumerate(targets):\n state, emmision = _update_fst(state, i)\n if emmision == 'start':\n starts.append(n)\n elif emmision == 'end':\n ends.append(n)\n state, emmision = _update_fst(state, None)\n if emmision == 'start':\n starts.append(n)\n elif emmision == 'end':\n ends.append(n + 1)\n starts = np.around(np.array([i * frame_length for i in starts]), 3)\n ends = np.around(np.array([i * frame_length for i in ends]), 3)\n return pd.DataFrame({'start': [starts],'end': [ends]})\n\n\ndef _update_fst(state: int, transition: int) -> Tuple[int, str]:\n '''Auxiliary function used by _targets_to_endpoints() for updating finite state\n transducer.\n\n Args:\n state: The current state.\n transition: The input (the next binary target).\n\n Returns:\n A tuple consisting of the new state and the output ('start', 'end' or None,\n representing a start, end or no endpoint detections respectively).\n '''\n\n if state == 0:\n if transition == 0:\n state = 1\n return state, None\n elif transition == 1:\n state = 2\n return state, 'start'\n elif state == 1:\n if transition == 0:\n return state, None\n elif transition == 1:\n state = 2\n return state, 'start'\n elif transition is None:\n state = 3\n return state, None\n elif state == 2:\n if transition == 0:\n state = 1\n return state, 'end'\n elif transition == 1:\n return state, None\n elif transition is None:\n state = 3\n return state, 'end'\n\n\n# Handle args when run directly\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(prog='run_cnnlstm.py',\n description='Run a trained voice activity detector on extracted feature set.')\n \n parser.add_argument('-s', '--speech_thresh', type=float,\n help='a decision threshold value between (0,1) for speech vs non-speech, defaults to 0.5')\n\n parser.add_argument('-m', '--speech_w_music_thresh', type=float,\n help='a decision threshold value between (0,1) for speech_with_music vs non-speech, defaults to 0.5, \\\n increasing will remove more speech_with_music, useful for downsteam ASR')\n \n parser.add_argument('-f', '--median_filter_kernel', type=int,\n help='a kernel size for a median filter to smooth the output labels, defaults to 1 (no smoothing)')\n\n parser.add_argument('-M', '--model_path', type=str,\n help='a path to a trained vad model saved as in .h5 format, overrides default pretrained model')\n\n parser.add_argument('feat_dir', type=str,\n help='a path to a directory containing a feats.h5 file with extracted features')\n \n parser.add_argument('out_dir', type=str,\n help='a path to an output directory where the output segments will be saved')\n\n args = parser.parse_args()\n if args.speech_thresh is not None:\n speech_thresh = args.speech_thresh\n else:\n speech_thresh = 0.5\n if args.speech_w_music_thresh is not None:\n speech_w_music_thresh = args.speech_w_music_thresh \n else:\n speech_w_music_thresh = 0.5\n if args.median_filter_kernel is not None:\n filt = args.median_filter_kernel \n else:\n filt = 1\n feats = pd.read_hdf(f'{args.feat_dir}/feats.h5')\n if args.model_path is not None:\n model = models.load_model(args.model_path)\n else:\n model = models.load_model(f'{os.path.dirname(os.path.realpath(__file__))}/models/cnn_bilstm.h5')\n targets = predict_targets(model, feats)\n endpoints = decode(targets, speech_thresh, speech_w_music_thresh, filt)\n to_data_dir(endpoints, args.out_dir)\n"
] | [
[
"tensorflow.keras.models.load_model",
"pandas.read_hdf",
"tensorflow.compat.v1.ConfigProto",
"pandas.Series",
"tensorflow.config.experimental.list_physical_devices",
"pandas.DataFrame",
"tensorflow.compat.v1.Session",
"numpy.array",
"tensorflow.config.experimental.set_visible_devices"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
EverLookNeverSee/BTS_DP_MRI | [
"c4e36c766c3ccf2ddea7c935f81df79ed8b72247"
] | [
"train.py"
] | [
"\"\"\"\n Training 3D U-Net Model\n @author: Milad Sadeghi DM - EverLookNeverSee@GitHub\n\"\"\"\n\n\nimport os\nimport argparse\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom model import build_unet_model\nfrom sklearn.model_selection import KFold\nfrom tensorflow.keras.optimizers import Adam\nfrom image_data_generator import image_generator\nfrom tensorflow.keras.callbacks import TensorBoard, CSVLogger\nfrom segmentation_models_3D.metrics import IOUScore\nfrom segmentation_models_3D.losses import DiceLoss, CategoricalFocalLoss\n\n\n# Initializing cli argument parser\nparser = argparse.ArgumentParser()\n# Adding arguments\nparser.add_argument(\"-d\", \"--dataset\", help=\"Path to .npy files directory\")\nparser.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"Level of verbosity\")\nparser.add_argument(\"-l\", \"--learning_rate\", help=\"Learning rate\", type=float, default=0.001)\nparser.add_argument(\"-b\", \"--batch_size\", help=\"Batch size\", type=int, default=2)\nparser.add_argument(\"-e\", \"--epochs\", help=\"Number of epochs\", type=int, default=100)\nparser.add_argument(\"-s\", \"--save\", help=\"Path to save trained model\", default=os.getcwd())\n\n# Parsing the arguments\nargs = parser.parse_args()\n\n\nkf = KFold(n_splits=8) # Configuring kfold cross validation\nfold_counter = 1 # Initializing fold counter\n\nfor train, valid in kf.split(range(34)): # 33 is the number of samples\n print(f\"Fold Number {fold_counter}\")\n train_data_generator = image_generator(path=args.dataset, indexes=train, batch_size=2)\n valid_data_generator = image_generator(path=args.dataset, indexes=valid, batch_size=2)\n\n # Calculating class weights\n columns = [\"0\", \"1\", \"2\"]\n df = pd.DataFrame(columns=columns)\n mask_list = list()\n for index in train:\n mask_list.append(f\"{args.dataset}/{index}/mask_{index}.npy\")\n for img in range(len(mask_list)):\n tmp_image = np.load(mask_list[img])\n tmp_image = np.argmax(tmp_image, axis=3)\n val, counts = np.unique(tmp_image, return_counts=True)\n zipped = zip(columns, counts)\n counts_dict = dict(zipped)\n df = df.append(counts_dict, ignore_index=True)\n\n label_0 = df['0'].sum()\n label_1 = df['1'].sum()\n label_2 = df['2'].sum()\n total_labels = label_0 + label_1 + label_2\n n_classes = 3\n wt0 = round((total_labels / (n_classes * label_0)), 2)\n wt1 = round((total_labels / (n_classes * label_1)), 2)\n wt2 = round((total_labels / (n_classes * label_2)), 2)\n\n dice_loss = DiceLoss(class_weights=np.array([wt0, wt1, wt2]))\n focal_loss = CategoricalFocalLoss()\n # Combining loss functions in order to create better total loss function\n total_loss = dice_loss + (1 * focal_loss)\n\n # Setting accuracy and IntersectionOverUnion as metrics\n metrics = [\"accuracy\", \"TruePositives\", \"TrueNegatives\", \"FalsePositives\", \"FalseNegatives\",\n \"Precision\", \"Recall\", IOUScore(threshold=0.5)]\n\n # Building the model\n model = build_unet_model(64, 64, 16, 2, 3)\n\n # Defining callback objects\n tensorboard_callback = TensorBoard(log_dir=\"./tb_logs\", histogram_freq=1, write_graph=True,\n write_images=True, update_freq=\"epoch\")\n # Defining logger callback\n logger_callback = CSVLogger(\"log_file.csv\", separator=\",\", append=True)\n\n # Compiling the model\n model.compile(optimizer=Adam(learning_rate=args.learning_rate), loss=total_loss, metrics=metrics)\n n_training_samples = len(train)\n n_validating_samples = len(valid)\n # Setting training process\n history = model.fit(\n train_data_generator,\n steps_per_epoch=n_training_samples//2,\n validation_data=valid_data_generator,\n validation_steps=n_validating_samples//2,\n shuffle=True,\n epochs=args.epochs,\n verbose=args.verbose,\n callbacks=[tensorboard_callback, logger_callback]\n )\n\n # Saving the trained model\n model.save(filepath=f\"{args.save}/BTS_DP_MRI_fold_0{fold_counter}.hdf5\", overwrite=True)\n\n if args.verbose:\n # Plotting model history\n loss = history.history[\"loss\"]\n val_loss = history.history[\"val_loss\"]\n epochs = range(1, len(loss) + 1)\n plt.plot(epochs, loss, \"y\", label=\"Training Loss\")\n plt.plot(epochs, val_loss, \"r\", label=\"Validation Loss\")\n plt.title(\"Training and validation loss\")\n plt.xlabel(\"Epochs\")\n plt.ylabel(\"Loss\")\n plt.legend()\n plt.savefig(fname=f\"./tv_loss_0{fold_counter}.png\", dpi=960)\n plt.show()\n\n iou_score = history.history[\"iou_score\"]\n val_iou_score = history.history[\"val_iou_score\"]\n plt.plot(epochs, iou_score, 'y', label='Training IOU Score')\n plt.plot(epochs, val_iou_score, 'r', label='Validation IOU Score')\n plt.title('Training and validation IOU Score')\n plt.xlabel('Epochs')\n plt.ylabel('IOU Score')\n plt.legend()\n plt.savefig(fname=f\"./tv_iou_score_0{fold_counter}.png\", dpi=960)\n plt.show()\n\n acc = history.history['accuracy']\n val_acc = history.history['val_accuracy']\n plt.plot(epochs, acc, 'y', label='Training accuracy')\n plt.plot(epochs, val_acc, 'r', label='Validation accuracy')\n plt.title('Training and validation accuracy')\n plt.xlabel('Epochs')\n plt.ylabel('Accuracy')\n plt.legend()\n plt.savefig(fname=f\"./tv_acc_0{fold_counter}.png\", dpi=960)\n plt.show()\n\n fold_counter += 1\n"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"numpy.unique",
"sklearn.model_selection.KFold",
"pandas.DataFrame",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.savefig",
"numpy.argmax",
"tensorflow.keras.callbacks.CSVLogger",
"matplotlib.pyplot.xlabel",
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.callbacks.TensorBoard",
"numpy.load",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
}
] |
kadrlica/obztak | [
"d24a8fe0659f2602f5d87cdfd99ebcf5224e418c"
] | [
"obztak/seeing.py"
] | [
"#!/usr/bin/env python\n\"\"\"\nGeneric python script.\n\"\"\"\n__author__ = \"Alex Drlica-Wagner\"\nfrom collections import OrderedDict as odict\nimport logging\nimport copy\n\nimport numpy as np\nimport pandas as pd\nimport dateutil.parser\nimport ephem\n\nfrom obztak.utils import fileio\nfrom obztak.utils.date import datestring\nfrom obztak.utils.database import Database\n\n\n# These are nominal transformation values from Eric Neilsen\n# WAVE[x] = (lambda[x]/lambda[i])**0.2\nWAVE = odict([\n ( 'u' , 0.86603 ), # u (380nm) -> i (780nm)\n ( 'g' , 0.9067 ), # g (480nm) -> i (780nm)\n ( 'r' , 0.9609 ), # r (640nm) -> i (780nm)\n ( 'i' , 1.0 ), # i (780nm) -> i (780nm)\n ( 'z' , 1.036 ), # z (920nm) -> i (780nm)\n ( 'Y' , 1.0523 ), # Y (990nm) -> i (780nm)\n ('dimm', 1/1.0916 ), # dimm (500 nm)->i (780nm)\n ('VR' , 0.9551 ), # VR (620 nm)->i (780nm)\n])\nWAVE_DF = pd.DataFrame({'filter':WAVE.keys(),'trans':WAVE.values()})\nDECAMINST = 0.5 # DECam instrumental contribution to the PSF [arcsec]\nDIMMINST = 0.0 # DIMM instrumental contribution to the PSF [arcsec]\n\ndef convert(fwhm_1,\n band_1='dimm', airmass_1=1.0, inst_1=DIMMINST,\n band_2='i', airmass_2=1.0, inst_2=DECAMINST):\n\n \"\"\"\n Convert observed seeing value to another band and airmass.\n\n Parameters:\n -----------\n fwhm_1 : input fwhm [arcsec]\n band_1 : input band ['g','r','i','z','Y','dimm']\n airmass_1: input airmass\n inst_1 : instrumental contribution to the observed psf [arcsec]\n\n band_2 : output band ['g','r','i','z','Y','dimm']\n airmass_2 : output airmass\n inst_2 : instrumental contribution to the output psf [arcsec]\n\n Returns:\n --------\n fwhm_2 : output fwhm [arcsec]\n \"\"\"\n fwhm = np.sqrt(fwhm_1**2 - inst_1**2)\n if np.isscalar(band_1):\n wave_1 = WAVE[band_1]\n else:\n wave_1 = WAVE_DF.merge(pd.DataFrame({'filter':band_1}), on='filter').to_records()['trans']\n\n if np.isscalar(band_2):\n wave_2 = WAVE[band_2]\n else:\n wave_2 = WAVE_DF.merge(pd.DataFrame({'filter':band_2}), on='filter').to_records()['trans']\n\n fwhm_2 = fwhm * (wave_1/wave_2) * (airmass_2/airmass_1)**(0.6)\n\n return np.hypot(fwhm_2, inst_2)\n\nclass Seeing():\n \"\"\"Class to manage seeing data. Seeign data is stored in two member variables:\n\n self.raw : the raw data before transformation\n self.data: seeing data transformed atmospheric i-band zenith\n\n The two values differ in that self.raw can have any source and\n includes the instrumental contribution. In contrast, self.data is\n the \"atmospheric\" i-band FWHM (arcsec). To get a prediction of the\n observed PSF, use `get_fwhm`.\n \"\"\"\n DTYPE = [('date','<M8[ns]'),('fwhm',float),('airmass',float),('filter','S4')]\n\n def __init__(self, date=None, db='fnal', filename=None):\n self.set_date(date)\n self.df = self.read_file(filename)\n self.db = 'db-'+db\n\n def set_date(self, date):\n if date is None:\n #NOOP (consistent with Tactician)\n return\n elif date == 'now':\n self.date = dateutil.parser.parse(datestring(ephem.now()))\n else:\n self.date = dateutil.parser.parse(date)\n\n\n def get_fwhm(self, timedelta='15m', band='i', airmass=1.0, inst=DECAMINST):\n \"\"\"Calculate the predict PSF FWHM (arcsec).\n\n Parameters:\n -----------\n date : date to estimate the psf (defualt: now)\n timedelta : time range to use to estimate the psf\n band : output band\n airmass : output airmass\n inst : output instrument contribution\n\n Returns:\n --------\n fwhm : predicted fwhm (arcsec)\n \"\"\"\n timedelta = pd.Timedelta(timedelta)\n\n self.load_data(timedelta=max(3*timedelta,pd.Timedelta('1h')))\n\n dt = pd.DatetimeIndex(self.data['date'])\n previous = slice(-1,None) # most recent exposure\n recent = (dt < self.date) & (dt > (self.date - timedelta))\n ancient = (dt < (self.date - timedelta)) & (dt > (self.date - 2*timedelta))\n\n # Nominal atmospheric psf i-band zenith fwhm = 0.9\"\n xmu = np.log10(0.74833) # sqrt(0.9**2 - 0.5**2)\n\n if not len(self.data):\n # No data, use the mean and print a warning\n logging.warn(\"No fwhm data available; using DECam median\")\n xpred = xmu\n elif np.any(recent) and np.any(ancient):\n # Weighted median of recent and ancient exposures\n logging.debug(\"Seeing from recent and ancient exposures\")\n # Log of the observed atmospheric psf i-band zenith\n x = np.log10([np.median(self.data[recent]['fwhm']),\n np.median(self.data[ancient]['fwhm'])])\n\n # Predicted log of the atmospheric psf\n # NB: These constants were derived for timedelta=5min\n # they may not hold for arbitrary time windows.\n xpred = xmu + 0.8 * (x[0] - xmu) + 0.14 * (x[1] - xmu)\n elif np.any(recent):\n # Median of the log of the observed atmospheric psf i-band zenith\n logging.debug(\"Seeing from recent exposures\")\n xpred = np.log10(np.median(self.data[recent]['fwhm']))\n else:\n # Log of the i-band zenith fwhm from the previous exposure\n logging.debug(\"Seeing from previous exposure\")\n xpred = np.log10(np.median(self.data[previous]['fwhm']))\n\n fwhm_pred = convert(10**xpred,\n band_1='i' , airmass_1=1.0 , inst_1=0.0,\n band_2=band, airmass_2=airmass, inst_2=inst)\n #import pdb; pdb.set_trace()\n return fwhm_pred\n\n\nclass DimmSeeing(Seeing):\n \"\"\"Estimate seeing from the DIMM.\"\"\"\n\n @classmethod\n def read_file(cls, filename):\n if filename is None: return None\n df = pd.read_csv(filename,names=['date','fwhm'],\n parse_dates=['date'],index_col=['date'])\n return df\n\n def get_data(self, date=None, timedelta='30m'):\n self.set_date(date)\n tmax = self.date\n tmin = self.date - pd.Timedelta(timedelta)\n if self.df is None:\n # Don't want to create the DB each time?\n db = Database(self.db)\n db.connect()\n query =\"\"\"\n select date, dimm2see as fwhm from exposure\n where date > '%s' and date < '%s'\n and dimm2see is not NULL\n \"\"\"%(tmin, tmax)\n logging.debug(query)\n raw = db.query2rec(query)\n else:\n sel = (self.df.index > tmin) & (self.df.index < tmax)\n raw = self.df[sel].to_records()\n return raw\n\n def load_data(self, date=None, timedelta='30m'):\n raw = self.get_data(date, timedelta)\n\n # Save the raw dimm values\n self.raw = np.recarray(len(raw),dtype=self.DTYPE)\n self.raw['date'] = raw['date']\n self.raw['fwhm'] = raw['fwhm']\n self.raw['airmass'] = 1.0\n self.raw['filter'] = 'dimm'\n\n # Convert to i-band zenith\n self.data = copy.deepcopy(self.raw)\n self.data['filter'] = 'i'\n self.data['airmass'] = 1.0\n\n kwargs = dict(band_1='dimm', inst_1=DIMMINST, airmass_1=self.raw['airmass'])\n kwargs.update(band_2='i', inst_2=0.0 , airmass_2=self.data['airmass'])\n self.data['fwhm'] = convert(self.raw['fwhm'],**kwargs)\n\n return self.data\n\nclass QcSeeing(Seeing):\n \"\"\"Estimate seeing from the DECam QC values.\"\"\"\n\n @classmethod\n def read_file(cls, filename):\n if filename is None: return None\n df = pd.read_csv(filename,names=['date','fwhm','airmass','filter'],\n parse_dates=['date'],index_col=['date'])\n return df\n\n def get_data(self, date=None, timedelta='30m'):\n self.set_date(date)\n tmax = self.date\n tmin = self.date - pd.Timedelta(timedelta)\n if self.df is None:\n # Don't want to create the DB each time?\n try: \n db = Database()\n db.connect()\n query =\"\"\"\n select date, qc_fwhm as fwhm, airmass, filter from exposure\n where date > '%s' and date < '%s'\n --and filter != 'VR' and qc_fwhm is not NULL\n and qc_fwhm is not NULL and qc_fwhm > 0\n \"\"\"%(tmin, tmax)\n logging.debug(query)\n raw = db.query2rec(query)\n except Exception as e:\n logging.warn(\"Couldn't connect to database:\\n%s\"%str(e))\n dtype=[('date', '<M8[ns]'), ('fwhm', '<f8'),\n ('airmass', '<f8'), ('filter', 'S4')]\n raw = np.recarray(0,dtype=dtype)\n else:\n sel = (self.df.index > tmin) & (self.df.index < tmax)\n raw = self.df[sel].to_records()\n\n return raw\n\n def load_data(self, date=None, timedelta='30m'):\n raw = self.get_data(date,timedelta)\n\n # Save the raw dimm values\n self.raw = np.recarray(len(raw),dtype=self.DTYPE)\n self.raw['date'] = raw['date']\n self.raw['fwhm'] = raw['fwhm']\n self.raw['airmass'] = raw['airmass']\n self.raw['filter'] = raw['filter']\n\n # Convert to i-band zenith\n self.data = copy.deepcopy(self.raw)\n self.data['filter'] = 'i'\n self.data['airmass'] = 1.0\n\n kwargs = dict(band_1=self.raw['filter'], inst_1=DECAMINST, airmass_1=self.raw['airmass'])\n kwargs.update(band_2='i', inst_2=0.0 , airmass_2=self.data['airmass'])\n self.data['fwhm'] = convert(self.raw['fwhm'],**kwargs)\n\n return self.data\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser(description=__doc__)\n args = parser.parse_args()\n"
] | [
[
"pandas.read_csv",
"numpy.sqrt",
"numpy.median",
"pandas.DatetimeIndex",
"pandas.Timedelta",
"pandas.DataFrame",
"numpy.log10",
"numpy.any",
"numpy.isscalar",
"numpy.recarray",
"numpy.hypot"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
SIAAAAAA/MMT-PSM | [
"0835c01c5010d3337778f452e9d96416e0f8a11a",
"0835c01c5010d3337778f452e9d96416e0f8a11a",
"0835c01c5010d3337778f452e9d96416e0f8a11a"
] | [
"maskrcnn_benchmark/structures/segmentation_mask.py",
"maskrcnn_benchmark/engine/MTtrainer.py",
"maskrcnn_benchmark/utils/visual.py"
] | [
"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\nimport torch\n\nimport pycocotools.mask as mask_utils\nfrom pycocotools import mask as maskUtils\nimport numpy as np\n# from maskrcnn_benchmark.utils.miscellaneous\n# transpose\nFLIP_LEFT_RIGHT = 0\nFLIP_TOP_BOTTOM = 1\n\n\nclass Mask(object):\n \"\"\"\n This class is unfinished and not meant for use yet\n It is supposed to contain the mask for an object as\n a 2d tensor\n \"\"\"\n\n def __init__(self, masks, size, mode):\n self.masks = masks\n self.size = size\n self.mode = mode\n\n def transpose(self, method):\n if method not in (FLIP_LEFT_RIGHT, FLIP_TOP_BOTTOM):\n raise NotImplementedError(\n \"Only FLIP_LEFT_RIGHT and FLIP_TOP_BOTTOM implemented\"\n )\n\n width, height = self.size\n if method == FLIP_LEFT_RIGHT:\n dim = width\n idx = 2\n elif method == FLIP_TOP_BOTTOM:\n dim = height\n idx = 1\n\n flip_idx = list(range(dim)[::-1])\n flipped_masks = self.masks.index_select(dim, flip_idx)\n return Mask(flipped_masks, self.size, self.mode)\n\n def crop(self, box):\n w, h = box[2] - box[0], box[3] - box[1]\n\n cropped_masks = self.masks[:, box[1] : box[3], box[0] : box[2]]\n return Mask(cropped_masks, size=(w, h), mode=self.mode)\n\n def resize(self, size, *args, **kwargs):\n pass\n\n\nclass Polygons(object):\n \"\"\"\n This class holds a set of polygons that represents a single instance\n of an object mask. The object can be represented as a set of\n polygons\n \"\"\"\n\n def __init__(self, polygons, size, mode):\n # assert isinstance(polygons, list), '{}'.format(polygons)\n if isinstance(polygons, list):\n polygons = [torch.as_tensor(p, dtype=torch.float32) for p in polygons]\n elif isinstance(polygons, Polygons):\n polygons = polygons.polygons\n\n self.polygons = polygons\n self.size = size\n self.mode = mode\n\n def transpose(self, method):\n if method not in (FLIP_LEFT_RIGHT, FLIP_TOP_BOTTOM):\n raise NotImplementedError(\n \"Only FLIP_LEFT_RIGHT and FLIP_TOP_BOTTOM implemented\"\n )\n\n flipped_polygons = []\n width, height = self.size\n if method == FLIP_LEFT_RIGHT:\n dim = width\n idx = 0\n elif method == FLIP_TOP_BOTTOM:\n dim = height\n idx = 1\n\n for poly in self.polygons:\n p = poly.clone()\n TO_REMOVE = 1\n p[idx::2] = dim - poly[idx::2] - TO_REMOVE\n flipped_polygons.append(p)\n\n return Polygons(flipped_polygons, size=self.size, mode=self.mode)\n\n def crop(self, box):\n w, h = box[2] - box[0], box[3] - box[1]\n\n # TODO chck if necessary\n w = max(w, 1)\n h = max(h, 1)\n\n cropped_polygons = []\n for poly in self.polygons:\n p = poly.clone()\n p[0::2] = p[0::2] - box[0] # .clamp(min=0, max=w)\n p[1::2] = p[1::2] - box[1] # .clamp(min=0, max=h)\n cropped_polygons.append(p)\n\n return Polygons(cropped_polygons, size=(w, h), mode=self.mode)\n\n def resize(self, size, *args, **kwargs):\n ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(size, self.size))\n if ratios[0] == ratios[1]:\n ratio = ratios[0]\n scaled_polys = [p * ratio for p in self.polygons]\n return Polygons(scaled_polys, size, mode=self.mode)\n\n ratio_w, ratio_h = ratios\n scaled_polygons = []\n for poly in self.polygons:\n p = poly.clone()\n p[0::2] *= ratio_w\n p[1::2] *= ratio_h\n scaled_polygons.append(p)\n\n return Polygons(scaled_polygons, size=size, mode=self.mode)\n\n def convert(self, mode):\n width, height = self.size\n if mode == \"mask\":\n rles = mask_utils.frPyObjects(\n [p.numpy() for p in self.polygons], height, width\n )\n rle = mask_utils.merge(rles)\n mask = mask_utils.decode(rle)\n mask = torch.from_numpy(mask)\n # TODO add squeeze?\n return mask\n\n def __repr__(self):\n s = self.__class__.__name__ + \"(\"\n s += \"num_polygons={}, \".format(len(self.polygons))\n s += \"image_width={}, \".format(self.size[0])\n s += \"image_height={}, \".format(self.size[1])\n s += \"mode={})\".format(self.mode)\n return s\n\n\nclass SegmentationMask(object):\n \"\"\"\n This class stores the segmentations for all objects in the image\n \"\"\"\n\n def __init__(self, polygons, size, mode=None):\n \"\"\"\n Arguments:\n polygons: a list of list of lists of numbers. The first\n level of the list correspond to individual instances,\n the second level to all the polygons that compose the\n object, and the third level to the polygon coordinates.\n \"\"\"\n # print(polygons)\n assert isinstance(polygons, list)\n if not isinstance(polygons[0], np.ndarray):\n self.polygons = [Polygons(p, size, mode) for p in polygons]\n else:\n self.polygons = []\n self.mask = polygons\n\n\n\n self.size = size\n self.mode = mode\n\n def decode(self, h, w):\n # covnert mask object to binary mask numpy array\n # RLES = []\n binary_mask = np.zeros((h,w))\n for segm in self.polygons:\n mask = segm.convert('mask')\n binary_mask = binary_mask + mask.numpy()\n return binary_mask\n\n\n def transpose(self, method):\n if method not in (FLIP_LEFT_RIGHT, FLIP_TOP_BOTTOM):\n raise NotImplementedError(\n \"Only FLIP_LEFT_RIGHT and FLIP_TOP_BOTTOM implemented\"\n )\n\n flipped = []\n for polygon in self.polygons:\n flipped.append(polygon.transpose(method))\n return SegmentationMask(flipped, size=self.size, mode=self.mode)\n\n def crop(self, box):\n if isinstance(self.polygons[0], Polygons):\n w, h = box[2] - box[0], box[3] - box[1]\n cropped = []\n for polygon in self.polygons:\n cropped.append(polygon.crop(box))\n return SegmentationMask(cropped, size=(w, h), mode=self.mode)\n else:\n cropped = []\n w, h = box[2] - box[0], box[3] - box[1]\n for mask in self.mask:\n mask = mask[box[1]:box[3], box[0]:box[2]]\n cropped.append(mask)\n return SegmentationMask(cropped, size = (w,h), mode =\n self.mode)\n\n def resize(self, size, *args, **kwargs):\n scaled = []\n\n for polygon in self.polygons:\n scaled.append(polygon.resize(size, *args, **kwargs))\n return SegmentationMask(scaled, size=size, mode=self.mode)\n\n def to(self, *args, **kwargs):\n return self\n\n def __getitem__(self, item):\n if isinstance(item, (int, slice)):\n selected_polygons = [self.polygons[item]]\n else:\n # advanced indexing on a single dimension\n selected_polygons = []\n if isinstance(item, torch.Tensor) and item.dtype == torch.uint8:\n item = item.nonzero()\n item = item.squeeze(1) if item.numel() > 0 else item\n item = item.tolist()\n for i in item:\n # print(self.polygons[i])\n\n selected_polygons.append(self.polygons[i])\n return SegmentationMask(selected_polygons, size=self.size, mode=self.mode)\n\n\n\n def __iter__(self):\n return iter(self.polygons)\n\n def __repr__(self):\n s = self.__class__.__name__ + \"(\"\n s += \"num_instances={}, \".format(len(self.polygons))\n s += \"image_width={}, \".format(self.size[0])\n s += \"image_height={})\".format(self.size[1])\n return s\n",
"import datetime\nimport logging\nimport time\nfrom maskrcnn_benchmark.solver.build import make_lr_scheduler\nimport torch\nimport torch.distributed as dist\nimport pdb\nfrom maskrcnn_benchmark.utils.comm import get_world_size\nfrom maskrcnn_benchmark.utils.metric_logger import MetricLogger\nfrom maskrcnn_benchmark.utils.miscellaneous import sigmoid_rampdown,sigmoid_rampup\nimport numpy as np\nfrom collections import Counter\nfrom functools import partial\n\n\ndef reduce_loss_dict(loss_dict):\n \"\"\"\n Reduce the loss dictionary from all processes so that process with rank\n 0 has the averaged results. Returns a dict with the same fields as\n loss_dict, after reduction.\n \"\"\"\n world_size = get_world_size()\n if world_size < 2:\n reduced_losses = {}\n with torch.no_grad():\n for k, v in loss_dict.items():\n reduced_losses[k] = v\n return reduced_losses\n with torch.no_grad():\n loss_names = []\n all_losses = []\n for k, v in loss_dict.items():\n loss_names.append(k)\n all_losses.append(v)\n all_losses = torch.stack(all_losses, dim=0)\n dist.reduce(all_losses, dst=0)\n if dist.get_rank() == 0:\n # only main process gets accumulated, so only divide by\n # world_size in this case\n all_losses /= world_size\n reduced_losses = {k: v for k, v in zip(loss_names, all_losses)}\n return reduced_losses\n\ndef _gather_data_from_loaders(source, nolabel):\n # (images_s1,targets_s, _) = source\n (images_s1,targets_s, _) = source\n (images_nl_list,_) = nolabel\n return images_nl_list,images_s1, targets_s\n\ndef init_teacher_weight(model_s, model_t):\n\n for ema_param, param in zip(model_t.parameters(),\n model_s.parameters()):\n\n ema_param.data.mul_(0.).add_(1, param.data)\n\ndef accumulate_loss_dict(losses):\n c = Counter()\n for loss in losses:\n c.update(loss)\n c = dict(c)\n for k in c.keys():\n c[k] = c[k]/len(losses)\n return c\n\n\ndef weight_sum_losses(loss_dict, step, rampup_length,\n rampdown_length, total_length,\n l = 1,\n balanced =None, start_mt = 1000):\n '''\n :param loss_dict: losses from model\n :param step: current iter\n :param rampup_length: steps for consistency loss start from\n 0 to 1\n :param rampdown_length: steps for consistency loss from 1 to 0\n at the end of training\n :param total_length: training iters\n :param l: lambda_value to balance supervised and consistency loss\n :param balanced: the weight for each loss term\n :param start_mt: start the mean teacher framework when the\n student model is relative stable.\n :return: weighted loss\n\n loss = sup_loss[i] * balanced[i] + weight(Time) * (consist_loss[\n j]*balanced[j] )\n\n '''\n if (step - start_mt) < rampup_length and (step -start_mt)>0:\n weight = l * sigmoid_rampup(step-start_mt, rampup_length)\n elif (total_length - step)< rampdown_length:\n weight = l * sigmoid_rampdown(total_length - step, rampup_length)\n else:\n weight = l\n # pdb.set_trace()\n loss = {}\n # pdb.set_trace()\n for k,v in loss_dict.items():\n if 'mt' in k:\n # mean teacher loss\n loss.update({k: weight * v})\n else:\n loss.update({k: v})\n for k,v in loss.items():\n try:\n loss.update({k:v * balanced[k]})\n except:\n continue\n return loss\n\nclass MTtrainer(object):\n def __init__(self,model_s, model_t, data_loader, optimizer,\n scheduler,ckpt_s, ckpt_t,checkpoint_period, cfg):\n super(MTtrainer, self).__init__()\n self.cfg = cfg\n self.logger = logging.getLogger(\"maskrcnn_benchmark.trainer\")\n self.scheduler = scheduler\n self.meters = MetricLogger(delimiter=\" \")\n self.max_iter = len(data_loader['source'])\n self.start_iter = 0\n\n self.student = model_s\n self.student_bs = cfg.MT.AUG_S\n self.teacher = model_t\n self.teacher_bs = cfg.MT.AUG_K\n # pdb.set_trace()\n self.device_s = torch.device('cuda:0')\n self.device_t = torch.device('cuda:0')\n self.checkpoint_period = checkpoint_period\n self.ckpt_s = ckpt_s\n self.ckpt_t = ckpt_t\n self.optimizer = optimizer\n # mt hyperparameter\n self.lambda_value = cfg.MT.LAMBDA\n self.alpha = cfg.MT.ALPHA\n self.alpha_rampup = cfg.MT.ALPHA_RAMPUP\n self.rampup_step = cfg.MT.RAMPUP_STEP\n self.rampdown_step = cfg.MT.RAMPDOWN_STEP\n self.start_mt = cfg.MT.START_MT\n #loss weight\n self.balanced_weight = {\n 'mt_classifier': (cfg.MT.CLS_LOSS),\n 'nms_loss': cfg.MODEL.RELATION_NMS.LOSS,\n 'mt_fg_loss':cfg.MT.FG_HINT,\n }\n\n self.dataloader_s = data_loader['source']\n if self.cfg.DATASETS.NO_LABEL:\n self.dataloader_u = data_loader['no_label']\n if cfg.DATASETS.SYN:\n # todo: add in training\n self.dataloader_syn = data_loader['synthesis']\n self.n_step_unlabel = cfg.MT.N_STEP_UNLABEL\n self.weight_sum_loss = partial(weight_sum_losses,\n rampup_length\n =self.rampup_step,\n rampdown_length =\n self.rampdown_step,\n total_length = self.max_iter,\n l = self.lambda_value,\n balanced =\n self.balanced_weight,\n start_mt = self.start_mt)\n\n def train(self):\n self.student.train()\n self.teacher.eval()\n start_training_time = time.time()\n # pdb.set_trace()\n end = time.time()\n\n for iteration, data_source in enumerate(self.dataloader_s,self.start_iter):\n # if iteration>self.start_mt:\n # self.checkpoint_period = 50\n data_s, target_s, _ = data_source\n loss_dict = self.forward_source(data_s,target_s)\n if iteration> self.start_mt and self.lambda_value>0 and self.cfg.DATASETS.NO_LABEL:\n unlabel_loss_dict = self.forward_unlabel()\n loss_dict.update(unlabel_loss_dict)\n\n # calculate losses\n self.scheduler.step()\n losses_dict = self.weight_sum_loss(loss_dict, iteration)\n losses = sum(loss for k, loss in losses_dict.items())\n # reduce losses over all GPUs for logging purposes\n # todo add loss weight to different loss\n loss_dict_reduced = reduce_loss_dict(losses_dict)\n losses_reduced = sum(\n loss for loss in loss_dict_reduced.values())\n self.meters.update(loss=losses_reduced, **loss_dict_reduced)\n self.optimizer.zero_grad()\n losses.backward()\n self.optimizer.step()\n # update teacher\n if self.lambda_value > 0 and iteration>(self.start_mt-10):\n self.update_teacher(iteration-(self.start_mt-10))\n\n batch_time = time.time() - end\n end = time.time()\n self.meters.update(time=batch_time)\n\n eta_seconds = self.meters.time.global_avg * (self.max_iter - iteration)\n eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))\n if iteration % 20 == 0 or iteration == self.max_iter:\n self.logger.info(\n self.meters.delimiter.join(\n [\n \"eta: {eta}\",\n \"iter: {iter}\",\n \"{meters}\",\n \"lr: {lr:.6f}\",\n \"max mem: {memory:.0f}\",\n ]\n ).format(\n eta=eta_string,\n iter=iteration,\n meters=str(self.meters),\n lr=self.optimizer.param_groups[0][\"lr\"],\n memory=torch.cuda.max_memory_allocated() / 1024.0 / 1024.0,\n )\n )\n if iteration % self.checkpoint_period == 0:\n self.save_model(iteration)\n if iteration == self.max_iter:\n self.save_model(final = True)\n total_training_time = time.time() - start_training_time\n total_time_str = str(datetime.timedelta(seconds=total_training_time))\n self.logger.info(\"Total training time: {} ({:.4f} s / it)\"\n .format(total_time_str, total_training_time / (self.max_iter)))\n\n def save_model(self, iteration=0, final = False):\n if iteration > 0 and not final:\n self.ckpt_s.save(\"model_{:07d}\".format(iteration))\n if iteration > self.start_mt:\n self.ckpt_t.save(\"t_model_{:07d}\".format(iteration))\n if final:\n self.ckpt_s.save(\"model_final\".format(iteration))\n if iteration > self.start_mt:\n self.ckpt_t.save(\"t_model_final\".format(iteration))\n\n def forward_source(self, image, target):\n image = image.to(self.device_s)\n target = [t.to(self.device_s) for t in target]\n losses_dict = self.student(image, target)\n return losses_dict\n\n def forward_unlabel(self):\n # image list has N augmented images\n unlabel_loss_dict = []\n loss_dict = {}\n for _ in range(self.n_step_unlabel):\n data_unlabel = next(iter(self.dataloader_u))\n data_u_list, _ = data_unlabel\n teacher_list = data_u_list[:self.teacher_bs]\n student = data_u_list[-self.student_bs:]\n teacher_list = [f.to(self.device_t) for f in teacher_list]\n student =[ s.to(self.device_s) for s in student]\n with torch.no_grad():\n try:\n teacher_results = self.teacher.forward_teacher(\n teacher_list)\n except:\n self.logger.info(\n 'teacher bug, may because no bbox, skip this pair')\n continue\n loss_dict = self.student.forward_student(student,\n teacher_results)\n unlabel_loss_dict.append(loss_dict)\n # average the unlabel_loss\n if unlabel_loss_dict == []:\n # skip this iter\n self.optimizer.zero_grad()\n return loss_dict\n loss_dict = accumulate_loss_dict(unlabel_loss_dict)\n return loss_dict\n\n def update_teacher(self, iter):\n alpha = min(1 - 1 / (iter + 1), self.alpha)\n for ema_param, param in zip(self.teacher.parameters(),\n self.student.parameters()):\n ema_param.data.mul_(alpha).add_(1 - alpha, param.data)\n\n\n\n",
"import cv2\nimport sys\nimport os\nsys.path.append('..')\nimport numpy as np\nfrom maskrcnn_benchmark.structures.bounding_box import BoxList\nfrom preprocess.colors import get_colors\nfrom maskrcnn_benchmark.structures.image_list import ImageList\nfrom maskrcnn_benchmark.structures.segmentation_mask import SegmentationMask, Polygons\nfrom maskrcnn_benchmark.structures.bounding_box import BoxList\nfrom pycocotools import mask as maskUtils\nimport openslide as ops\nimport random\nimport itertools\nfrom maskrcnn_benchmark.utils.miscellaneous import maskToPolygons\nimport pdb\n\ndef vis_bbox(bboxlist, imagelist, normalize = [102.9801, 115.9465, 122.7717] ):\n if isinstance(imagelist, ImageList):\n images = []\n for i, bbox in enumerate(bboxlist):\n if bbox.mode != 'xyxy':\n bbox = bbox.convert('xyxy')\n\n image = imagelist.tensors[i].numpy()\n image = np.squeeze(image)\n image = np.transpose(image,(1,2,0))\n image +=normalize\n\n image = image.copy()\n for j in range(bbox.bbox.shape[0]):\n box_coordinate = bbox.bbox[j].numpy().astype(np.int32)\n color = get_colors(j)\n image = cv2.rectangle(image,tuple(box_coordinate[:2]),tuple(box_coordinate[2:]), color=color.tuple(),thickness=3)\n images.append(image)\n else:\n bbox = bboxlist\n image = imagelist\n\n if bbox.mode != 'xyxy':\n bbox = bbox.convert('xyxy')\n image = image.copy()\n\n for j in range(bbox.bbox.shape[0]):\n box_coordinate = bbox.bbox[j].numpy().astype(np.int32)\n color = get_colors(j)\n image = cv2.rectangle(image, tuple(box_coordinate[:2]), tuple(box_coordinate[2:]), color=color.tuple(),\n thickness=3)\n images =cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n return images\n\ndef vis_mask(masklist, image, normalize =[102.9801, 115.9465, 122.7717] ):\n\n if isinstance(masklist, SegmentationMask):\n for i, polygon in enumerate(SegmentationMask):\n poly = polygon[0].polygons\n mask = np.asarray(poly[0])\n mask = np.reshape(mask, (int(len(mask) / 2), 2)).astype(\n np.int32)\n color = get_colors(i)\n image = np.asarray(image)\n cv2.polylines(np.asarray(image), [mask], 1, color.tuple(), 3)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n else:\n for j, mask in enumerate(masklist):\n mask = np.asarray(mask[0])\n mask = np.reshape(mask,(int(len(mask)/2),2)).astype(np.int32)\n color = get_colors(j)\n image = np.asarray(image)\n cv2.polylines(np.asarray(image),[mask], 1, color.tuple(),3)\n image =cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n return image\n\n\n\n\n\n\ndef vis_predict(dataset, gt, dt, name, show_gt =True):\n # input: list of dicts\n def convert_to_np(x):\n rle = x['segmentation']\n arr = maskUtils.decode(rle)\n return arr\n dt = map(convert_to_np, dt)\n name, w, h = name.split('~')\n # img = dataset._imgpath%name\n img = os.path.join(dataset.root, name + '.png' )\n img = ops.open_slide(img)\n img = img.read_region((int(w),int(h)), 0, (dataset.maxWS, dataset.maxWS)).convert(\"RGB\")\n img = np.asarray(img)\n canvas = np.zeros_like(img, dtype = np.uint8)\n\n\n for idx, d in enumerate(dt):\n if d.shape != (1000, 1000):\n import pdb;\n pdb.set_trace()\n r,g,b = get_colors(idx)\n canvas[:, :, 0] = canvas[:, :, 0] + b * d\n canvas[:, :, 1] = canvas[:, :, 1] + g * d\n canvas[:, :, 2] = canvas[:, :, 2] + r * d\n\n canvas2 = np.zeros_like(img, dtype = np.uint8)\n if show_gt:\n gt = map(convert_to_np, gt)\n\n for idx, ins in enumerate(gt):\n if ins.shape != (1000, 1000):\n import pdb;\n pdb.set_trace()\n r, g, b = get_colors(idx )\n canvas2[:, :, 0] = canvas2[:, :, 0] + b * ins\n canvas2[:, :, 1] = canvas2[:, :, 1] + g * ins\n canvas2[:, :, 2] = canvas2[:, :, 2] + r * ins\n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n add_img = cv2.addWeighted(img,0.5, canvas,0.5,0 )\n add_img2 = cv2.addWeighted(img,0.5, canvas2,0.5,0 )\n return add_img,add_img2\n\n# def vis_mask(masklist, imagelist, normalize =[102.9801, 115.9465, 122.7717] ):\n# if isinstance(masklist, SegmentationMask):\n# for i, polygon in enumerate(SegmentationMask):\n# poly = polygon[0].convert('mask')\n#\n#\n# else:\n# image = imagelist\n# for j, mask in enumerate(masklist):\n# mask = np.asarray(mask[0])\n# mask = np.reshape(mask,(int(len(mask)/2),2)).astype(np.int32)\n# color = get_colors(j)\n# image = np.asarray(image)\n# cv2.polylines(np.asarray(image),[mask], 1, color.tuple(),3)\n# image =cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n#\n# return image\n\n\n\ndef display_instance(dataset, image_name, gt, dt ,show_masks = False, show_bbox = True, show_gt = True, alpha = 0.5, show_caption = True ):\n '''\n\n :param image: h,w,c\n :param dt, gt : dict\n :param title: (optional) Figure title\n :param figsize:(optional) the size of the image\n :param color: (optional) An array or colors to use with each object\n :param captions:(optional) A list of strings to use as captions for each object\n :return:\n '''\n # input: list of dicts\n def convert_seg_to_np(x):\n rle = x['segmentation']\n arr = maskUtils.decode(rle)\n return arr\n\n seg_dt = list(map(convert_seg_to_np, dt))\n\n name, w, h = image_name.split('~')\n # img = dataset._imgpath%name\n try:\n img = os.path.join(dataset.root, name + '.png')\n img = ops.open_slide(img)\n except:\n img = os.path.join(dataset.root,'image', name + '.png')\n img = ops.open_slide(img)\n # pdb.set_trace()\n # img = img.read_region(0, 0, 0, (3152, 2760)).convert(\"RGB\")\n img = img.read_region((int(w),int(h)), 0, (dataset.maxWS, dataset.maxWS)).convert(\"RGB\")\n img = np.asarray(img)\n img1 = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\n img2 = img1.copy()\n # canvas = np.zeros_like(img, dtype = np.uint8)\n # 1. draw masks\n # pdb.set_trace()\n if show_masks:\n for idx, d in enumerate(seg_dt):\n r,g,b = get_colors(idx)\n # visualize masks\n # convert list to numpy\n img1[:, :, 0] = img1[:, :, 0] * ( d == 0 ) + ( d > 0 ) * ((b * d * alpha) + img1[:, :, 0] * (1 - alpha))\n img1[:, :, 1] = img1[:, :, 1] * ( d == 0 ) + ( d > 0 ) * ((g * d * alpha) + img1[:, :, 1] * (1 - alpha))\n img1[:, :, 2] = img1[:, :, 2] * ( d == 0 ) + ( d > 0 ) * ((r * d * alpha) + img1[:, :, 2] * (1 - alpha))\n # 2. show others\n # pdb.set_trace()\n for idx, d in enumerate(seg_dt):\n r,g,b = get_colors(idx)\n # visualize masks\n contour_list = maskToPolygons(d)\n cv2.polylines(img1, contour_list, True, (b,g,r), thickness= 1)\n if show_bbox:\n bbox = dt[idx]['bbox']\n cv2.rectangle(img1, (round(bbox[0]),round( bbox[1])),\n (round(bbox[2]), round(bbox[3])), (b,g,r), thickness= 1)\n # add information\n class_id = dt[idx]['category_id'][0]\n score = dt[idx]['score']\n if show_caption:\n x = random.randint(int(bbox[1]), round((bbox[1] + bbox[3])/2))\n caption = \"{} {:.3f}\".format(class_id, score)\n cv2.putText(img1, caption, (round(bbox[0]), x),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (b,g,r),1, cv2.LINE_AA )\n # canvas2 = np.zeros_like(img, dtype = np.uint8)\n # img2 = None\n if show_gt:\n # 1. show masks\n pdb.set_trace()\n seg_gt = list(map(convert_seg_to_np, gt))\n if show_masks:\n for idx, ins in enumerate(seg_gt):\n r, g, b = get_colors(idx )\n img2[:, :, 0] =img2[:, :, 0] * ( ins == 0 ) + ( ins > 0 ) * ((b * ins * alpha) + img2[:, :, 0] * (1 - alpha))\n img2[:, :, 1] =img2[:, :, 1] * ( ins == 0 ) + ( ins > 0 ) * ((g * ins * alpha) + img2[:, :, 1] * (1 - alpha))\n img2[:, :, 2] =img2[:, :, 2] * ( ins == 0 ) + ( ins > 0 ) * ((r * ins * alpha) + img2[:, :, 2] * (1 - alpha))\n # 2. show others\n for idx, ins in enumerate(seg_gt):\n r, g, b = get_colors(idx)\n contour_list = maskToPolygons(ins)\n cv2.polylines(img2, contour_list, True, (b,g,r), thickness=2)\n if show_bbox:\n bbox = gt[idx]['bbox']\n cv2.rectangle(img2, (round(bbox[0]), round(bbox[1])), (round(bbox[2]), round(bbox[3])), (b,g,r),\n thickness=3)\n x = random.randint(int(bbox[1]), round((bbox[1] + bbox[3]) / 2))\n class_id = gt[idx]['category_id'][0]\n caption = \"{}\".format(class_id)\n cv2.putText(img2, caption, (round(bbox[0]), x), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (b,g,r),2,\n cv2.LINE_AA)\n\n return img1,img2\n\ndef visualize_pseudo_label(mask, image, alpha = 0.5):\n RLES=[]\n for segm in mask.polygons:\n rles = maskUtils.frPyObjects(\n [p.numpy() for p in segm.polygons], 800, 800\n )\n rle = maskUtils.merge(rles)\n RLES.append(rle)\n for idx, cyto in enumerate(RLES):\n cyto_mask = maskUtils.decode(cyto)\n r, g, b = get_colors(int(2 * idx))\n image[:, :, 0] = image[:, :, 0] * (cyto_mask == 0) + (cyto_mask > 0) * (\n (b * alpha) + image[:, :, 0] * (1 - alpha))\n image[:, :, 1] = image[:, :, 1] * (cyto_mask == 0) + (cyto_mask > 0) * (\n (g * alpha) + image[:, :, 1] * (1 - alpha))\n image[:, :, 2] = image[:, :, 2] * (cyto_mask == 0) + (cyto_mask > 0) * (\n (r * alpha) + image[:, :, 2] * (1 - alpha))\n return image\n\ndef display_instance_gen_rle(image, cyto_list, nuclei_list, alpha = 0.5):\n h, w, _ = image.shape\n\n for idx, cyto in enumerate(cyto_list):\n cyto_mask = maskUtils.decode(cyto)\n r, g, b = get_colors(int(2 * idx))\n image[:, :, 0] = image[:, :, 0] * (cyto_mask == 0) + (cyto_mask > 0) * (\n (b * alpha) + image[:, :, 0] * (1 - alpha))\n image[:, :, 1] = image[:, :, 1] * (cyto_mask == 0) + (cyto_mask > 0) * (\n (g * alpha) + image[:, :, 1] * (1 - alpha))\n image[:, :, 2] = image[:, :, 2] * (cyto_mask == 0) + (cyto_mask > 0) * (\n (r * alpha) + image[:, :, 2] * (1 - alpha))\n for idx, cyto in enumerate(nuclei_list):\n cyto_mask = maskUtils.decode(cyto)\n r, g, b = get_colors(int(2 * idx + 1))\n image[:, :, 0] = image[:, :, 0] * (cyto_mask == 0) + (cyto_mask > 0) * (\n (b * alpha) + image[:, :, 0] * (1 - alpha))\n image[:, :, 1] = image[:, :, 1] * (cyto_mask == 0) + (cyto_mask > 0) * (\n (g * alpha) + image[:, :, 1] * (1 - alpha))\n image[:, :, 2] = image[:, :, 2] * (cyto_mask == 0) + (cyto_mask > 0) * (\n (r * alpha) + image[:, :, 2] * (1 - alpha))\n\n return image\ndef display_instance_gen(image, cyto_list, nuclei_list, alpha = 0.5):\n h, w, _ = image.shape\n\n for idx, cyto in enumerate(cyto_list):\n cyto_mask = np.array(cyto, np.int)\n cyto_mask = [list(itertools.chain.from_iterable(cyto_mask.tolist()))]\n cyto_mask = maskUtils.frPyObjects(cyto_mask, h, w)\n cyto_mask = maskUtils.decode(cyto_mask[0])\n r, g, b = get_colors(int(2 * idx))\n image[:, :, 0] = image[:, :, 0] * (cyto_mask == 0) + (cyto_mask > 0) * ((b* alpha) + image[:, :, 0] * (1 - alpha))\n image[:, :, 1] = image[:, :, 1] * (cyto_mask == 0) + (cyto_mask > 0) * ((g* alpha) + image[:, :, 1] * (1 - alpha))\n image[:, :, 2] = image[:, :, 2] * (cyto_mask == 0) + (cyto_mask > 0) * ((r* alpha) + image[:, :, 2] * (1 - alpha))\n for idx, cyto in enumerate(nuclei_list):\n cyto_mask = np.array(cyto, np.int)\n cyto_mask = [list(itertools.chain.from_iterable(cyto_mask.tolist()))]\n cyto_mask = maskUtils.frPyObjects(cyto_mask, h, w)\n cyto_mask = maskUtils.decode(cyto_mask[0])\n r, g, b = get_colors(int(2 * idx + 1))\n image[:, :, 0] = image[:, :, 0] * (cyto_mask == 0) + (cyto_mask > 0) * ((b* alpha) + image[:, :, 0] * (1 - alpha))\n image[:, :, 1] = image[:, :, 1] * (cyto_mask == 0) + (cyto_mask > 0) * ((g* alpha) + image[:, :, 1] * (1 - alpha))\n image[:, :, 2] = image[:, :, 2] * (cyto_mask == 0) + (cyto_mask > 0) * ((r* alpha) + image[:, :, 2] * (1 - alpha))\n\n return image\n # for cyto in cyto_list:\n # cyto_mask = np.array(cyto, np.int)\n # cyto_mask = list(itertools.chain.from_iterable(cyto_mask.tolist()))\n # cyto_rle.append()\n\n\n\n\n\n\ndef display_instance_dt(dataset, image_name, dt, show_masks=True, show_bbox=True, alpha=0.5,\n show_caption=True):\n '''\n\n :param image: h,w,c\n :param dt, gt : dict\n :param title: (optional) Figure title\n :param figsize:(optional) the size of the image\n :param color: (optional) An array or colors to use with each object\n :param captions:(optional) A list of strings to use as captions for each object\n :return:\n '''\n\n # input: list of dicts\n\n def convert_seg_to_np(x):\n rle = x['segmentation']\n arr = maskUtils.decode(rle)\n return arr\n\n seg_dt = list(map(convert_seg_to_np, dt))\n\n name, w, h = image_name.split('~')\n # img = dataset._imgpath%name\n img = os.path.join(dataset.root, name )\n img1 = cv2.imread(img)\n # canvas = np.zeros_like(img, dtype = np.uint8)\n # 1. draw masks\n if show_masks:\n for idx, d in enumerate(seg_dt):\n r, g, b = get_colors(idx)\n # visualize masks\n # convert list to numpy\n img1[:, :, 0] = img1[:, :, 0] * (d == 0) + (d > 0) * ((b * d * alpha) + img1[:, :, 0] * (1 - alpha))\n img1[:, :, 1] = img1[:, :, 1] * (d == 0) + (d > 0) * ((g * d * alpha) + img1[:, :, 1] * (1 - alpha))\n img1[:, :, 2] = img1[:, :, 2] * (d == 0) + (d > 0) * ((r * d * alpha) + img1[:, :, 2] * (1 - alpha))\n # 2. show others\n for idx, d in enumerate(seg_dt):\n r, g, b = get_colors(idx)\n # visualize masks\n contour_list = maskToPolygons(d)\n cv2.polylines(img1, contour_list, True, (b, g, r), thickness=1)\n if show_bbox:\n bbox = dt[idx]['bbox']\n cv2.rectangle(img1, (round(bbox[0]), round(bbox[1])), (round(bbox[2]), round(bbox[3])), (b, g, r),\n thickness=1)\n # add information\n class_id = dt[idx]['category_id'][0]\n score = dt[idx]['score']\n if show_caption:\n x = random.randint(int(bbox[1]), round((bbox[1] + bbox[3]) / 2))\n caption = \"{} {:.3f}\".format(class_id, score)\n cv2.putText(img1, caption, (round(bbox[0]), x), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (b, g, r), 2, cv2.LINE_AA)\n # canvas2 = np.zeros_like(img, dtype = np.uint8)\n\n\n return img1\n\n\n\n"
] | [
[
"numpy.zeros",
"torch.from_numpy",
"torch.as_tensor"
],
[
"torch.distributed.get_rank",
"torch.cuda.max_memory_allocated",
"torch.distributed.reduce",
"torch.no_grad",
"torch.stack",
"torch.device"
],
[
"numpy.asarray",
"numpy.squeeze",
"numpy.zeros_like",
"numpy.transpose",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
GengZ/siameseFC-pytorch-vot | [
"e825637b5ac68c38d6c62bba265b61b85c4955d9"
] | [
"Train/run_Train_SiamFC.py"
] | [
"import __init_paths\n\nimport os\nimport numpy as np\nfrom tqdm import tqdm\n\nimport torch\nfrom torch.autograd import Variable\nfrom torch.optim.lr_scheduler import LambdaLR\nfrom torch.utils.data import DataLoader\nimport torchvision.transforms as transforms\n\nfrom lib.VIDDataset import VIDDataset\nfrom lib.DataAugmentation import RandomStretch, CenterCrop, RandomCrop, ToTensor\nfrom lib.Utils import create_label\nfrom lib.eval_utils import centerThrErr\n\nfrom experiments.siamese_fc.Config import Config\nfrom experiments.siamese_fc.network import SiamNet\n\n\n# fix random seed\nnp.random.seed(1357)\ntorch.manual_seed(1234)\n\n\ndef train(data_dir, train_imdb, val_imdb,\n model_save_path=\"./model/\",\n config=None):\n\n assert config is not None\n use_gpu = config.use_gpu\n\n # set gpu ID\n if use_gpu:\n os.environ['CUDA_VISIBLE_DEVICES'] = str(config.gpu_id)\n\n # do data augmentation in PyTorch;\n # you can also do complex data augmentation as in the original paper\n center_crop_size = config.instance_size - config.stride\n random_crop_size = config.instance_size - 2 * config.stride\n\n train_z_transforms = transforms.Compose([\n RandomStretch(),\n CenterCrop((config.examplar_size, config.examplar_size)),\n ToTensor()\n ])\n train_x_transforms = transforms.Compose([\n RandomStretch(),\n CenterCrop((center_crop_size, center_crop_size)),\n RandomCrop((random_crop_size, random_crop_size)),\n ToTensor()\n ])\n valid_z_transforms = transforms.Compose([\n CenterCrop((config.examplar_size, config.examplar_size)),\n ToTensor(),\n ])\n valid_x_transforms = transforms.Compose([\n ToTensor()\n ])\n\n # load data (see details in VIDDataset.py)\n train_dataset = VIDDataset(train_imdb, data_dir, config,\n train_z_transforms, train_x_transforms)\n val_dataset = VIDDataset(val_imdb, data_dir, config, valid_z_transforms,\n valid_x_transforms, \"Validation\")\n\n # create dataloader\n train_loader = DataLoader(train_dataset, batch_size=config.batch_size,\n shuffle=True,\n num_workers=config.train_num_workers,\n drop_last=True)\n val_loader = DataLoader(val_dataset, batch_size=config.batch_size,\n shuffle=True,\n num_workers=config.val_num_workers,\n drop_last=True)\n\n # create SiamFC network architecture (see details in SiamNet.py)\n net = SiamNet()\n # move network to GPU if using GPU\n if use_gpu:\n net.cuda()\n\n # define training strategy;\n # ========================================\n # customize parameters attributes\n # 1. adjust layer weight learnable\n # 2. bias in feat_extraction exempt from weight_decay\n params = []\n # feature extract\n for key, value in dict(net.feat_extraction.named_parameters()).items():\n if 'conv' in key:\n if 'bias' in key:\n params += [{'params': [value],\n 'weight_decay': 0}]\n else: # weight\n params += [{'params': [value],\n 'weight_decay': config.weight_decay}]\n if 'bn' in key:\n params += [{'params': [value],\n 'weight_decay': 0}]\n # adjust layer\n params += [\n {'params': [net.adjust.bias]},\n # {'params': [net.adjust.weight], 'lr': not config.fix_adjust_layer},\n ]\n if config.fix_adjust_layer:\n params += [\n {'params': [net.adjust.weight], 'lr': 0},\n ]\n else:\n params += [\n {'params': [net.adjust.weight]},\n ]\n # ========================================\n optimizer = torch.optim.SGD(params,\n config.lr,\n config.momentum,\n config.weight_decay)\n # adjusting learning in each epoch\n if not config.resume:\n train_lrs = np.logspace(-2, -5, config.num_epoch)\n scheduler = LambdaLR(optimizer, lambda epoch: train_lrs[epoch])\n else:\n train_lrs = np.logspace(-2, -5, config.num_epoch)\n train_lrs = train_lrs[config.start_epoch:]\n\n net.load_state_dict(torch.load(os.path.join(model_save_path,\n 'SiamFC_' +\n str(config.start_epoch) +\n '_model.pth')))\n optimizer.load_state_dict(torch.load(os.path.join(model_save_path,\n 'optimizer.pth')))\n scheduler = LambdaLR(optimizer, lambda epoch: train_lrs[epoch])\n print('resume training from epoch {} checkpoint'.format(config.start_epoch))\n\n # used to control generating label for training;\n # once generated, they are fixed since the labels for each\n # pair of images (examplar z and search region x) are the same\n train_response_flag = False\n valid_response_flag = False\n\n # -------------------- training & validation process --------------------\n for i in range(config.start_epoch, config.num_epoch):\n\n # adjusting learning rate\n scheduler.step()\n\n # -------------------------- training --------------------------\n # indicating training (very important for batch normalization)\n net.train()\n\n # used to collect loss\n train_loss = []\n\n # used as eval metric\n err_disp = 0\n sample_num = 0\n\n for j, data in enumerate(train_loader):\n\n # fetch data,\n # i.e., B x C x W x H (batchsize x channel x wdith x heigh)\n exemplar_imgs, instance_imgs = data\n\n # forward pass\n if use_gpu:\n exemplar_imgs = exemplar_imgs.cuda()\n instance_imgs = instance_imgs.cuda()\n output = net.forward(Variable(exemplar_imgs),\n Variable(instance_imgs))\n\n # create label for training (only do it one time)\n if not train_response_flag:\n # change control flag\n train_response_flag = True\n # get shape of output (i.e., response map)\n response_size = output.shape[2:4]\n # generate label and weight\n train_eltwise_label, train_instance_weight = \\\n create_label(response_size, config, use_gpu)\n\n # clear the gradient\n optimizer.zero_grad()\n\n # loss\n if config.loss == \"logistic\":\n loss = net.weight_loss(output,\n Variable(train_eltwise_label),\n Variable(train_instance_weight))\n elif config.loss == 'customize':\n loss = net.customize_loss(output,\n Variable(train_eltwise_label),\n Variable(train_instance_weight))\n\n # backward\n loss.backward()\n\n # update parameter\n optimizer.step()\n\n # collect training loss\n train_loss.append(loss.data)\n\n # collect additional data for metric\n err_disp = centerThrErr(output.data.cpu().numpy(),\n train_eltwise_label.cpu().numpy(),\n err_disp, sample_num)\n sample_num += config.batch_size\n\n # stdout\n if (j + 1) % config.log_freq == 0:\n print (\"Epoch %d, Iter %06d, loss: %f, error disp: %f\"\n % (i+1, (j+1), np.mean(train_loss), err_disp))\n\n # ------------------------- saving model ---------------------------\n if not os.path.exists(model_save_path):\n os.makedirs(model_save_path)\n torch.save(net.state_dict(),\n os.path.join(model_save_path,\n \"SiamFC_\" + str(i + 1) + \"_model.pth\"))\n torch.save(optimizer.state_dict(),\n os.path.join(model_save_path,\n 'optimizer.pth'))\n\n # --------------------------- validation ---------------------------\n # indicate validation\n net.eval()\n\n # used to collect validation loss\n val_loss = []\n\n for j, data in enumerate(tqdm(val_loader)):\n\n exemplar_imgs, instance_imgs = data\n\n # forward pass\n if use_gpu:\n exemplar_imgs = exemplar_imgs.cuda()\n instance_imgs = instance_imgs.cuda()\n output = net.forward(Variable(exemplar_imgs),\n Variable(instance_imgs))\n\n # create label for validation (only do it one time)\n if not valid_response_flag:\n valid_response_flag = True\n response_size = output.shape[2:4]\n valid_eltwise_label, valid_instance_weight = \\\n create_label(response_size, config, use_gpu)\n\n # loss\n if config.loss == \"logistic\":\n loss = net.weight_loss(output,\n Variable(valid_eltwise_label),\n Variable(valid_instance_weight))\n elif config.loss == 'customize':\n loss = net.customize_loss(output,\n Variable(valid_eltwise_label),\n Variable(valid_instance_weight))\n\n # collect validation loss\n val_loss.append(loss.data)\n\n print (\"Epoch %d training loss: %f, validation loss: %f\"\n % (i+1, np.mean(train_loss), np.mean(val_loss)))\n\n\nif __name__ == \"__main__\":\n\n # initialize training configuration\n config = Config()\n\n data_dir = config.data_dir\n train_imdb = config.train_imdb\n val_imdb = config.val_imdb\n model_save_path = os.path.join(config.save_base_path, config.save_sub_path)\n\n # training SiamFC network, using GPU by default\n train(data_dir, train_imdb, val_imdb,\n model_save_path=model_save_path,\n config=config)\n"
] | [
[
"torch.optim.lr_scheduler.LambdaLR",
"numpy.random.seed",
"numpy.logspace",
"torch.manual_seed",
"torch.utils.data.DataLoader",
"numpy.mean",
"torch.optim.SGD",
"torch.autograd.Variable"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
KT12/Training | [
"ac4de382a1387ccfe51404eb3302cc518762a781"
] | [
"ltf/generate_samples.py"
] | [
"import tensorflow as tf\nimport numpy as np\n\nfrom functions import *\n\nn_features = 2\nn_clusters = 3\nn_samples_per_cluster = 500\nseed = 700\nembiggen_factor = 70\n\nnp.random.seed()\n\ndata_centroids, samples = create_samples(n_clusters, n_samples_per_cluster, n_features,\n embiggen_factor, seed)\ninitial_centroids = choose_random_centroids(samples, n_clusters)\nnearest_indices = assign_to_nearest(samples, initial_centroids)\nupdated_centroids = update_centroids(samples, nearest_indices, n_clusters)\n\nmodel = tf.global_variables_initializer()\nwith tf.Session() as session:\n sample_values = session.run(samples)\n #plot_clusters(sample_values, initial_centroids, n_samples_per_cluster)\n for i in range(1024):\n updated_centroid_value = session.run(updated_centroids)\n if i%128 == 0:\n print(nearest_indices)\n plot_to_nearest(sample_values, updated_centroid_value, nearest_indices)\n\n# Code to run iteratively, but not display original distribution below\n# Also doesn't change the color of the dots to closest centroid\n# model = tf.global_variables_initializer()\n# with tf.Session() as session:\n# sample_values = session.run(samples)\n# for i in range(1024):\n# updated_centroid_value = session.run(updated_centroids)\n# if i%64 == 0:\n# plot_clusters(sample_values, updated_centroid_value, n_samples_per_cluster)"
] | [
[
"tensorflow.Session",
"tensorflow.global_variables_initializer",
"numpy.random.seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
RobLewisQA/BChain_Project | [
"7bdf682ea1e23359f2958620ad0afb417892ba1e"
] | [
"app/WordList_Reader/application/routes.py"
] | [
"import random\nimport application.BChain_WordList as bwords\nimport pandas as pd\nfrom flask import Flask, redirect, request, url_for,render_template, Response, jsonify\nfrom application import app\n\[email protected]('/mnemonic_generator', methods=['GET']) \ndef mnemonic_generator():\n seedphrase_words = []\n\n while len(seedphrase_words) < 12:\n seedphrase_words.append(bwords.wordlist[random.randint(0,len(bwords.wordlist)-1)])\n series = pd.Series(seedphrase_words, name=\"sp_words\").reset_index().drop(columns='index')\n return series.to_json()"
] | [
[
"pandas.Series"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
desihsu/lane-finder | [
"f40249c52909d5e235bee40b116965cf0641f871"
] | [
"lane_finder.py"
] | [
"import sys\nfrom moviepy.editor import VideoFileClip\nimport camera\nimport image_thresholding\nimport line_fitting\nimport matplotlib.image as mpimg\n\n\nclass Line():\n def __init__(self):\n self.detected = False # lane line detected in previous iteration\n self.fit = None # most recent polynomial fit\n self.fitx = None # most recent x pixel values for line\n\n\ndef process_image(img):\n color_grad_combined = image_thresholding.color_grad(img)\n warped, Minv = camera.perspective_transform(color_grad_combined, mtx, dist)\n\n if left_line.detected and right_line.detected:\n (left_line.fit, right_line.fit, \n left_line.fitx, right_line.fitx, \n ploty) = line_fitting.search_around_poly(warped, left_line.fit, \n right_line.fit)\n else:\n (left_line.fit, right_line.fit, \n left_line.fitx, right_line.fitx, \n ploty) = line_fitting.fit_polynomial(warped, detected=False)\n left_line.detected = True\n right_line.detected = True\n\n result = line_fitting.draw_lines(img, warped, Minv, left_line.fitx, \n right_line.fitx, ploty)\n return result\n\n\nif __name__ == \"__main__\":\n mtx, dist = camera.calibrate()\n left_line = Line()\n right_line = Line()\n\n if (sys.argv[1].split(\".\")[-1] == \"mp4\"):\n \tclip = VideoFileClip(sys.argv[1])\n \toutput = clip.fl_image(process_image)\n \toutput.write_videofile(\"output.mp4\", audio=False)\n else:\n \timg = mpimg.imread(sys.argv[1])\n \timg = process_image(img)\n \tmpimg.imsave(\"output.jpg\", img)"
] | [
[
"matplotlib.image.imread",
"matplotlib.image.imsave"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
willijm92/fsri-compartments-2018 | [
"8fd5ddd6f535d434df69e5853aa27db77d599ef3"
] | [
"03_Scripts/plot.py"
] | [
"# plot.py\n\n# --------------- #\n# Import Packages #\n# --------------- #\nimport os\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n# Set seaborn as default plot config\nsns.set()\nsns.set_style(\"whitegrid\")\nfrom itertools import cycle\n\n# ---------------------------------- #\n# Define Subdirectories & Info Files #\n# ---------------------------------- #\ndata_dir = '../01_Data/'\ninfo_dir = '../02_Info/'\nplot_dir = '../04_Charts/'\n# Create plot dir if necessary\nif not os.path.exists(plot_dir): os.makedirs(plot_dir)\n\n# Read in channel list & create list of sensor groups\nfull_channel_list = pd.read_csv(f'{info_dir}channel_list.csv', index_col='Channel_Name')\n\n# ------------------- #\n# Set Plot Parameters #\n# ------------------- #\nlabel_size = 18\ntick_size = 16\nline_width = 2\nevent_font = 12\nfont_rotation = 60\nlegend_font = 12\nfig_width = 10\nfig_height = 8\n\n# ---------------------- #\n# User-Defined Functions #\n# ---------------------- #\ndef timestamp_to_seconds(timestamp):\n timestamp = timestamp[11:]\n hh, mm, ss = timestamp.split(':')\n return(3600 * int(hh) + 60 * int(mm) + int(ss))\n\ndef convert_timestamps(timestamps, start_time):\n raw_seconds = map(timestamp_to_seconds, timestamps)\n return([s - start_time for s in list(raw_seconds)])\n\ndef create_1plot_fig():\n # Define figure for the plot\n fig, ax1 = plt.subplots(figsize=(fig_width, fig_height))\n\n # Set line colors & markers; reset axis lims\n current_palette_8 = sns.color_palette('deep', 8)\n sns.set_palette(current_palette_8)\n\n plot_markers = cycle(['s', 'o', '^', 'd', 'h', 'p','v', '8', 'D', '*', '<', '>', 'H'])\n x_max, y_min, y_max = 0, 0, 0\n\n return(fig, ax1, plot_markers, x_max, y_min, y_max)\n\ndef format_and_save_plot(y_lims, x_lims, secondary_axis_label, file_loc):\n # Set tick parameters\n ax1.tick_params(labelsize=tick_size, length=0, width=0)\n\n # Scale axes limits & labels\n ax1.grid(True)\n ax1.set_ylim(bottom=y_lims[0], top=y_lims[1])\n ax1.set_xlim(x_lims[0] - x_lims[1] / 500, x_lims[1])\n ax1.set_xlabel('Time (s)', fontsize=label_size)\n\n # Secondary y-axis parameters\n if secondary_axis_label != 'None':\n ax2 = ax1.twinx()\n ax2.tick_params(labelsize=tick_size, length=0, width=0)\n ax2.set_ylabel(secondary_axis_label, fontsize=label_size)\n if secondary_axis_label == 'Temperature ($^\\circ$F)':\n ax2.set_ylim([y_lims[0] * 1.8 + 32., y_lims[1] * 1.8 + 32.])\n else:\n ax2.set_ylim([secondary_axis_scale * y_lims[0], secondary_axis_scale * y_lims[1]])\n ax2.yaxis.grid(visible=None)\n\n # Add vertical lines and labels for timing information (if available)\n ax3 = ax1.twiny()\n ax3.set_xlim(x_lims[0] - x_lims[1] / 500, x_lims[1])\n ax3.set_xticks([_x for _x in Events.index.values if _x >= x_lims[0] and _x <= x_lims[1]])\n ax3.tick_params(axis='x', width=1, labelrotation=font_rotation, labelsize=event_font)\n ax3.set_xticklabels([Events['Event'][_x] for _x in Events.index.values if _x >= x_lims[0] and _x <= x_lims[1]], fontsize=event_font, ha='left')\n ax3.xaxis.grid(visible=None)\n\n # Add legend, clean up whitespace padding, save chart as pdf, & close fig\n handles1, labels1 = ax1.get_legend_handles_labels()\n ax1.legend(handles1, labels1, loc='best', fontsize=legend_font, handlelength=3, frameon=True, framealpha=0.75)\n\n fig.tight_layout()\n plt.savefig(file_loc)\n plt.close()\n\n# ----------------- #\n# Main Body of Code #\n# ----------------- #\n# Loop through test data files & create plots\nfor f in os.listdir(data_dir):\n # Skip if f is not a exp data file\n if any([not f.endswith('.csv'), f.startswith('.'), f.endswith('_Events.csv')]):\n continue\n\n # Get test name from file & load data & event files for given experiment\n test_name = f[:-4]\n data_df = pd.read_csv(f'{data_dir}{f}', index_col='Time')\n Events = pd.read_csv(f'{data_dir}{test_name}_Events.csv')\n print (f'--- Loaded data for {test_name} ---')\n\n # Create index column of time relative to ignition in events file\n Events = pd.read_csv(f'{data_dir}{f[:-4]}_Events.csv')\n Events.rename(columns={'Time':'Timestamp'}, inplace=True)\n start_timestamp = Events.loc[0, 'Timestamp'][11:]\n hh,mm,ss = start_timestamp.split(':')\n start_time = 3600 * int(hh) + 60 * int(mm) + int(ss)\n Events['Time'] = convert_timestamps(Events['Timestamp'], start_time)\n Events = Events.set_index('Time')\n\n # Define channel list as full list & drop unused channels for given experiment\n channel_list = full_channel_list[[i in data_df.columns for i in full_channel_list.index]]\n\n # Loop through channel groups to plot data from all channels in each group\n for group in channel_list.groupby('Group').groups:\n # Create figure for plot\n print (f\" Plotting {group.replace('_',' ')}\")\n fig, ax1, plot_markers, x_max, y_min, y_max = create_1plot_fig()\n\n # Loop through each channel in given group\n for channel in channel_list.groupby('Group').get_group(group).index.values:\n # Set secondary axis default to None, get data type from channel list\n secondary_axis_label = 'None'\n data_type = channel_list.loc[channel, 'Type']\n\n # Set plot parameters based on data type\n if data_type == 'Temperature':\n # Set y-axis labels & y_min\n ax1.set_ylabel('Temperature ($^\\circ$C)', fontsize=label_size)\n secondary_axis_label = 'Temperature ($^\\circ$F)'\n y_min = 0\n\n elif data_type == 'Velocity':\n # Apply moving average & set y-axis labels, secondary scale\n data_df[channel] = data_df[channel].rolling(window=10, center=True).mean()\n ax1.set_ylabel('Velocity (m/s)', fontsize=label_size)\n secondary_axis_label = 'Velocity (mph)'\n secondary_axis_scale = 2.23694\n\n elif data_type == 'Pressure':\n # Apply moving average & set y-axis labels, secondary scale\n data_df[channel] = data_df[channel].rolling(window=10, center=True).mean()\n ax1.set_ylabel('Pressure (Pa)', fontsize=label_size)\n\n elif data_type == 'Oxygen':\n # Set y-axis label\n ax1.set_ylabel('O$_2$ Concentration (%)', fontsize=label_size)\n\n elif data_type.endswith('Heat Flux'):\n # Apply moving average & set y-axis label\n data_df[channel] = data_df[channel].rolling(window=10, center=True).mean()\n ax1.set_ylabel('Heat Flux (kW/m$^2$)', fontsize=label_size)\n\n elif data_type == 'Heat Release Rate':\n # Set y-axis label\n ax1.set_ylabel('Heat Release Rate (kW)', fontsize=label_size)\n\n # Determine x max bound for current data & update max of chart if necessary\n x_end = data_df[channel].index[-1]\n if x_end > x_max:\n x_max = x_end\n\n # Plot channel data\n ax1.plot(data_df.index, data_df[channel], lw=line_width,\n marker=next(plot_markers), markevery=30, mew=3, mec='none', ms=7, \n label=channel_list.loc[channel, 'Label'])\n\n # Check if y min/max need to be updated\n if data_df[channel].min() - abs(data_df[channel].min() * .1) < y_min:\n y_min = data_df[channel].min() - abs(data_df[channel].min() * .1)\n\n if data_df[channel].max() * 1.1 > y_max:\n y_max = data_df[channel].max() * 1.1\n\n # Add vertical lines for event labels; label to y axis\n [ax1.axvline(_x, color='0.25', lw=1.5) for _x in Events.index.values if _x >= 0 and _x <= x_max]\n\n # Define/create save directory, call function to format & save plot\n save_dir = f'{plot_dir}{test_name}/'\n if not os.path.exists(save_dir): os.makedirs(save_dir)\n format_and_save_plot([y_min, y_max], [0, x_max], secondary_axis_label, f'{save_dir}{group}.pdf')\n\n print()"
] | [
[
"matplotlib.pyplot.close",
"pandas.read_csv",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
joeriess/rasa | [
"c1bdfd0934578f515a8bf3ab708c294b809300f8"
] | [
"rasa/nlu/selectors/response_selector.py"
] | [
"import copy\nimport logging\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom typing import Any, Dict, Optional, Text, Tuple, Union, List, Type\n\nfrom rasa.shared.nlu.training_data import util\nimport rasa.shared.utils.io\nfrom rasa.nlu.config import InvalidConfigError\nfrom rasa.shared.nlu.training_data.training_data import TrainingData\nfrom rasa.shared.nlu.training_data.message import Message\nfrom rasa.nlu.components import Component\nfrom rasa.nlu.featurizers.featurizer import Featurizer\nfrom rasa.nlu.model import Metadata\nfrom rasa.nlu.classifiers.diet_classifier import (\n DIETClassifier,\n DIET,\n LABEL_KEY,\n LABEL_SUB_KEY,\n EntityTagSpec,\n SEQUENCE_LENGTH,\n SENTENCE,\n SEQUENCE,\n)\nfrom rasa.utils.tensorflow.constants import (\n LABEL,\n HIDDEN_LAYERS_SIZES,\n SHARE_HIDDEN_LAYERS,\n TRANSFORMER_SIZE,\n NUM_TRANSFORMER_LAYERS,\n NUM_HEADS,\n BATCH_SIZES,\n BATCH_STRATEGY,\n EPOCHS,\n RANDOM_SEED,\n LEARNING_RATE,\n RANKING_LENGTH,\n LOSS_TYPE,\n SIMILARITY_TYPE,\n NUM_NEG,\n SPARSE_INPUT_DROPOUT,\n DENSE_INPUT_DROPOUT,\n MASKED_LM,\n ENTITY_RECOGNITION,\n INTENT_CLASSIFICATION,\n EVAL_NUM_EXAMPLES,\n EVAL_NUM_EPOCHS,\n UNIDIRECTIONAL_ENCODER,\n DROP_RATE,\n DROP_RATE_ATTENTION,\n WEIGHT_SPARSITY,\n NEGATIVE_MARGIN_SCALE,\n REGULARIZATION_CONSTANT,\n SCALE_LOSS,\n USE_MAX_NEG_SIM,\n MAX_NEG_SIM,\n MAX_POS_SIM,\n EMBEDDING_DIMENSION,\n BILOU_FLAG,\n KEY_RELATIVE_ATTENTION,\n VALUE_RELATIVE_ATTENTION,\n MAX_RELATIVE_POSITION,\n RETRIEVAL_INTENT,\n USE_TEXT_AS_LABEL,\n SOFTMAX,\n AUTO,\n BALANCED,\n TENSORBOARD_LOG_DIR,\n TENSORBOARD_LOG_LEVEL,\n CONCAT_DIMENSION,\n FEATURIZERS,\n DENSE_DIMENSION,\n)\nfrom rasa.nlu.constants import (\n RESPONSE_SELECTOR_PROPERTY_NAME,\n RESPONSE_SELECTOR_RETRIEVAL_INTENTS,\n RESPONSE_SELECTOR_RESPONSES_KEY,\n RESPONSE_SELECTOR_PREDICTION_KEY,\n RESPONSE_SELECTOR_RANKING_KEY,\n RESPONSE_SELECTOR_TEMPLATE_NAME_KEY,\n PREDICTED_CONFIDENCE_KEY,\n RESPONSE_SELECTOR_DEFAULT_INTENT,\n)\nfrom rasa.shared.nlu.constants import (\n TEXT,\n INTENT,\n RESPONSE,\n INTENT_RESPONSE_KEY,\n INTENT_NAME_KEY,\n)\n\nfrom rasa.utils.tensorflow.model_data import RasaModelData\nfrom rasa.utils.tensorflow.models import RasaModel\n\nlogger = logging.getLogger(__name__)\n\n\nclass ResponseSelector(DIETClassifier):\n \"\"\"Response selector using supervised embeddings.\n\n The response selector embeds user inputs\n and candidate response into the same space.\n Supervised embeddings are trained by maximizing similarity between them.\n It also provides rankings of the response that did not \"win\".\n\n The supervised response selector needs to be preceded by\n a featurizer in the pipeline.\n This featurizer creates the features used for the embeddings.\n It is recommended to use ``CountVectorsFeaturizer`` that\n can be optionally preceded by ``SpacyNLP`` and ``SpacyTokenizer``.\n\n Based on the starspace idea from: https://arxiv.org/abs/1709.03856.\n However, in this implementation the `mu` parameter is treated differently\n and additional hidden layers are added together with dropout.\n \"\"\"\n\n @classmethod\n def required_components(cls) -> List[Type[Component]]:\n return [Featurizer]\n\n defaults = {\n # ## Architecture of the used neural network\n # Hidden layer sizes for layers before the embedding layers for user message\n # and labels.\n # The number of hidden layers is equal to the length of the corresponding\n # list.\n HIDDEN_LAYERS_SIZES: {TEXT: [256, 128], LABEL: [256, 128]},\n # Whether to share the hidden layer weights between input words and responses\n SHARE_HIDDEN_LAYERS: False,\n # Number of units in transformer\n TRANSFORMER_SIZE: None,\n # Number of transformer layers\n NUM_TRANSFORMER_LAYERS: 0,\n # Number of attention heads in transformer\n NUM_HEADS: 4,\n # If 'True' use key relative embeddings in attention\n KEY_RELATIVE_ATTENTION: False,\n # If 'True' use key relative embeddings in attention\n VALUE_RELATIVE_ATTENTION: False,\n # Max position for relative embeddings\n MAX_RELATIVE_POSITION: None,\n # Use a unidirectional or bidirectional encoder.\n UNIDIRECTIONAL_ENCODER: False,\n # ## Training parameters\n # Initial and final batch sizes:\n # Batch size will be linearly increased for each epoch.\n BATCH_SIZES: [64, 256],\n # Strategy used when creating batches.\n # Can be either 'sequence' or 'balanced'.\n BATCH_STRATEGY: BALANCED,\n # Number of epochs to train\n EPOCHS: 300,\n # Set random seed to any 'int' to get reproducible results\n RANDOM_SEED: None,\n # Initial learning rate for the optimizer\n LEARNING_RATE: 0.001,\n # ## Parameters for embeddings\n # Dimension size of embedding vectors\n EMBEDDING_DIMENSION: 20,\n # Default dense dimension to use if no dense features are present.\n DENSE_DIMENSION: {TEXT: 512, LABEL: 512},\n # Default dimension to use for concatenating sequence and sentence features.\n CONCAT_DIMENSION: {TEXT: 512, LABEL: 512},\n # The number of incorrect labels. The algorithm will minimize\n # their similarity to the user input during training.\n NUM_NEG: 20,\n # Type of similarity measure to use, either 'auto' or 'cosine' or 'inner'.\n SIMILARITY_TYPE: AUTO,\n # The type of the loss function, either 'softmax' or 'margin'.\n LOSS_TYPE: SOFTMAX,\n # Number of top actions to normalize scores for loss type 'softmax'.\n # Set to 0 to turn off normalization.\n RANKING_LENGTH: 10,\n # Indicates how similar the algorithm should try to make embedding vectors\n # for correct labels.\n # Should be 0.0 < ... < 1.0 for 'cosine' similarity type.\n MAX_POS_SIM: 0.8,\n # Maximum negative similarity for incorrect labels.\n # Should be -1.0 < ... < 1.0 for 'cosine' similarity type.\n MAX_NEG_SIM: -0.4,\n # If 'True' the algorithm only minimizes maximum similarity over\n # incorrect intent labels, used only if 'loss_type' is set to 'margin'.\n USE_MAX_NEG_SIM: True,\n # Scale loss inverse proportionally to confidence of correct prediction\n SCALE_LOSS: True,\n # ## Regularization parameters\n # The scale of regularization\n REGULARIZATION_CONSTANT: 0.002,\n # Sparsity of the weights in dense layers\n WEIGHT_SPARSITY: 0.0,\n # The scale of how important is to minimize the maximum similarity\n # between embeddings of different labels.\n NEGATIVE_MARGIN_SCALE: 0.8,\n # Dropout rate for encoder\n DROP_RATE: 0.2,\n # Dropout rate for attention\n DROP_RATE_ATTENTION: 0,\n # If 'True' apply dropout to sparse input tensors\n SPARSE_INPUT_DROPOUT: False,\n # If 'True' apply dropout to dense input tensors\n DENSE_INPUT_DROPOUT: False,\n # ## Evaluation parameters\n # How often calculate validation accuracy.\n # Small values may hurt performance, e.g. model accuracy.\n EVAL_NUM_EPOCHS: 20,\n # How many examples to use for hold out validation set\n # Large values may hurt performance, e.g. model accuracy.\n EVAL_NUM_EXAMPLES: 0,\n # ## Selector config\n # If 'True' random tokens of the input message will be masked and the model\n # should predict those tokens.\n MASKED_LM: False,\n # Name of the intent for which this response selector is to be trained\n RETRIEVAL_INTENT: None,\n # Boolean flag to check if actual text of the response\n # should be used as ground truth label for training the model.\n USE_TEXT_AS_LABEL: False,\n # If you want to use tensorboard to visualize training and validation metrics,\n # set this option to a valid output directory.\n TENSORBOARD_LOG_DIR: None,\n # Define when training metrics for tensorboard should be logged.\n # Either after every epoch or for every training step.\n # Valid values: 'epoch' and 'minibatch'\n TENSORBOARD_LOG_LEVEL: \"epoch\",\n # Specify what features to use as sequence and sentence features\n # By default all features in the pipeline are used.\n FEATURIZERS: [],\n }\n\n def __init__(\n self,\n component_config: Optional[Dict[Text, Any]] = None,\n index_label_id_mapping: Optional[Dict[int, Text]] = None,\n entity_tag_specs: Optional[List[EntityTagSpec]] = None,\n model: Optional[RasaModel] = None,\n all_retrieval_intents: Optional[List[Text]] = None,\n responses: Optional[Dict[Text, List[Dict[Text, Any]]]] = None,\n ) -> None:\n\n component_config = component_config or {}\n\n # the following properties cannot be adapted for the ResponseSelector\n component_config[INTENT_CLASSIFICATION] = True\n component_config[ENTITY_RECOGNITION] = False\n component_config[BILOU_FLAG] = None\n\n # Initialize defaults\n self.responses = responses or {}\n self.all_retrieval_intents = all_retrieval_intents or []\n self.retrieval_intent = None\n self.use_text_as_label = False\n\n super().__init__(\n component_config, index_label_id_mapping, entity_tag_specs, model\n )\n\n @property\n def label_key(self) -> Text:\n return LABEL_KEY\n\n @property\n def label_sub_key(self) -> Text:\n return LABEL_SUB_KEY\n\n @staticmethod\n def model_class(use_text_as_label: bool) -> Type[RasaModel]:\n if use_text_as_label:\n return DIET2DIET\n else:\n return DIET2BOW\n\n def _load_selector_params(self, config: Dict[Text, Any]) -> None:\n self.retrieval_intent = config[RETRIEVAL_INTENT]\n self.use_text_as_label = config[USE_TEXT_AS_LABEL]\n\n def _check_config_parameters(self) -> None:\n super()._check_config_parameters()\n self._load_selector_params(self.component_config)\n\n def _set_message_property(\n self, message: Message, prediction_dict: Dict[Text, Any], selector_key: Text\n ) -> None:\n message_selector_properties = message.get(RESPONSE_SELECTOR_PROPERTY_NAME, {})\n message_selector_properties[\n RESPONSE_SELECTOR_RETRIEVAL_INTENTS\n ] = self.all_retrieval_intents\n message_selector_properties[selector_key] = prediction_dict\n message.set(\n RESPONSE_SELECTOR_PROPERTY_NAME,\n message_selector_properties,\n add_to_output=True,\n )\n\n def preprocess_train_data(self, training_data: TrainingData) -> RasaModelData:\n \"\"\"Prepares data for training.\n\n Performs sanity checks on training data, extracts encodings for labels.\n \"\"\"\n\n if self.retrieval_intent:\n training_data = training_data.filter_training_examples(\n lambda ex: self.retrieval_intent == ex.get(INTENT)\n )\n else:\n # retrieval intent was left to its default value\n logger.info(\n \"Retrieval intent parameter was left to its default value. This \"\n \"response selector will be trained on training examples combining \"\n \"all retrieval intents.\"\n )\n\n label_attribute = RESPONSE if self.use_text_as_label else INTENT_RESPONSE_KEY\n\n label_id_index_mapping = self._label_id_index_mapping(\n training_data, attribute=label_attribute\n )\n\n self.responses = training_data.responses\n self.all_retrieval_intents = list(training_data.retrieval_intents)\n\n if not label_id_index_mapping:\n # no labels are present to train\n return RasaModelData()\n\n self.index_label_id_mapping = self._invert_mapping(label_id_index_mapping)\n\n self._label_data = self._create_label_data(\n training_data, label_id_index_mapping, attribute=label_attribute\n )\n\n model_data = self._create_model_data(\n training_data.intent_examples,\n label_id_index_mapping,\n label_attribute=label_attribute,\n )\n\n self._check_input_dimension_consistency(model_data)\n\n return model_data\n\n def _resolve_intent_response_key(\n self, label: Dict[Text, Optional[Text]]\n ) -> Optional[Text]:\n \"\"\"Given a label, return the response key based on the label id.\n\n Args:\n label: predicted label by the selector\n\n Returns:\n The match for the label that was found in the known responses.\n It is always guaranteed to have a match, otherwise that case should have been caught\n earlier and a warning should have been raised.\n \"\"\"\n\n for key, responses in self.responses.items():\n\n # First check if the predicted label was the key itself\n search_key = util.template_key_to_intent_response_key(key)\n if hash(search_key) == label.get(\"id\"):\n return search_key\n\n # Otherwise loop over the responses to check if the text has a direct match\n for response in responses:\n if hash(response.get(TEXT, \"\")) == label.get(\"id\"):\n return search_key\n return None\n\n def process(self, message: Message, **kwargs: Any) -> None:\n \"\"\"Return the most likely response, the associated intent_response_key and its similarity to the input.\"\"\"\n\n out = self._predict(message)\n top_label, label_ranking = self._predict_label(out)\n\n # Get the exact intent_response_key and the associated\n # response templates for the top predicted label\n label_intent_response_key = (\n self._resolve_intent_response_key(top_label) or top_label[INTENT_NAME_KEY]\n )\n label_response_templates = self.responses.get(\n util.intent_response_key_to_template_key(label_intent_response_key)\n )\n\n if label_intent_response_key and not label_response_templates:\n # response templates seem to be unavailable,\n # likely an issue with the training data\n # we'll use a fallback instead\n rasa.shared.utils.io.raise_warning(\n f\"Unable to fetch response templates for {label_intent_response_key} \"\n f\"This means that there is likely an issue with the training data.\"\n f\"Please make sure you have added response templates for this intent.\"\n )\n label_response_templates = [{TEXT: label_intent_response_key}]\n\n for label in label_ranking:\n label[INTENT_RESPONSE_KEY] = (\n self._resolve_intent_response_key(label) or label[INTENT_NAME_KEY]\n )\n # Remove the \"name\" key since it is either the same as\n # \"intent_response_key\" or it is the response text which\n # is not needed in the ranking.\n label.pop(INTENT_NAME_KEY)\n\n selector_key = (\n self.retrieval_intent\n if self.retrieval_intent\n else RESPONSE_SELECTOR_DEFAULT_INTENT\n )\n\n logger.debug(\n f\"Adding following selector key to message property: {selector_key}\"\n )\n\n prediction_dict = {\n RESPONSE_SELECTOR_PREDICTION_KEY: {\n \"id\": top_label[\"id\"],\n RESPONSE_SELECTOR_RESPONSES_KEY: label_response_templates,\n PREDICTED_CONFIDENCE_KEY: top_label[PREDICTED_CONFIDENCE_KEY],\n INTENT_RESPONSE_KEY: label_intent_response_key,\n RESPONSE_SELECTOR_TEMPLATE_NAME_KEY: util.intent_response_key_to_template_key(\n label_intent_response_key\n ),\n },\n RESPONSE_SELECTOR_RANKING_KEY: label_ranking,\n }\n\n self._set_message_property(message, prediction_dict, selector_key)\n\n def persist(self, file_name: Text, model_dir: Text) -> Dict[Text, Any]:\n \"\"\"Persist this model into the passed directory.\n\n Return the metadata necessary to load the model again.\n \"\"\"\n if self.model is None:\n return {\"file\": None}\n\n super().persist(file_name, model_dir)\n\n return {\n \"file\": file_name,\n \"responses\": self.responses,\n \"all_retrieval_intents\": self.all_retrieval_intents,\n }\n\n @classmethod\n def _load_model_class(\n cls,\n tf_model_file: Text,\n model_data_example: RasaModelData,\n label_data: RasaModelData,\n entity_tag_specs: List[EntityTagSpec],\n meta: Dict[Text, Any],\n ) -> \"RasaModel\":\n\n return cls.model_class(meta[USE_TEXT_AS_LABEL]).load(\n tf_model_file,\n model_data_example,\n data_signature=model_data_example.get_signature(),\n label_data=label_data,\n entity_tag_specs=entity_tag_specs,\n config=copy.deepcopy(meta),\n )\n\n def _instantiate_model_class(self, model_data: RasaModelData) -> \"RasaModel\":\n\n return self.model_class(self.use_text_as_label)(\n data_signature=model_data.get_signature(),\n label_data=self._label_data,\n entity_tag_specs=self._entity_tag_specs,\n config=self.component_config,\n )\n\n @classmethod\n def load(\n cls,\n meta: Dict[Text, Any],\n model_dir: Text = None,\n model_metadata: Metadata = None,\n cached_component: Optional[\"ResponseSelector\"] = None,\n **kwargs: Any,\n ) -> \"ResponseSelector\":\n \"\"\"Loads the trained model from the provided directory.\"\"\"\n\n model = super().load(\n meta, model_dir, model_metadata, cached_component, **kwargs\n )\n if not meta.get(\"file\"):\n return model # pytype: disable=bad-return-type\n\n model.responses = meta.get(\"responses\", {})\n model.all_retrieval_intents = meta.get(\"all_retrieval_intents\", [])\n\n return model # pytype: disable=bad-return-type\n\n\nclass DIET2BOW(DIET):\n def _create_metrics(self) -> None:\n # self.metrics preserve order\n # output losses first\n self.mask_loss = tf.keras.metrics.Mean(name=\"m_loss\")\n self.response_loss = tf.keras.metrics.Mean(name=\"r_loss\")\n # output accuracies second\n self.mask_acc = tf.keras.metrics.Mean(name=\"m_acc\")\n self.response_acc = tf.keras.metrics.Mean(name=\"r_acc\")\n\n def _update_metrics_to_log(self) -> None:\n debug_log_level = logging.getLogger(\"rasa\").level == logging.DEBUG\n\n if self.config[MASKED_LM]:\n self.metrics_to_log.append(\"m_acc\")\n if debug_log_level:\n self.metrics_to_log.append(\"m_loss\")\n\n self.metrics_to_log.append(\"r_acc\")\n if debug_log_level:\n self.metrics_to_log.append(\"r_loss\")\n\n self._log_metric_info()\n\n def _log_metric_info(self) -> None:\n metric_name = {\"t\": \"total\", \"m\": \"mask\", \"r\": \"response\"}\n logger.debug(\"Following metrics will be logged during training: \")\n for metric in self.metrics_to_log:\n parts = metric.split(\"_\")\n name = f\"{metric_name[parts[0]]} {parts[1]}\"\n logger.debug(f\" {metric} ({name})\")\n\n def _update_label_metrics(self, loss: tf.Tensor, acc: tf.Tensor) -> None:\n\n self.response_loss.update_state(loss)\n self.response_acc.update_state(acc)\n\n\nclass DIET2DIET(DIET):\n def _check_data(self) -> None:\n if TEXT not in self.data_signature:\n raise InvalidConfigError(\n f\"No text features specified. \"\n f\"Cannot train '{self.__class__.__name__}' model.\"\n )\n if LABEL not in self.data_signature:\n raise InvalidConfigError(\n f\"No label features specified. \"\n f\"Cannot train '{self.__class__.__name__}' model.\"\n )\n if (\n self.config[SHARE_HIDDEN_LAYERS]\n and self.data_signature[TEXT][SENTENCE]\n != self.data_signature[LABEL][SENTENCE]\n ):\n raise ValueError(\n \"If hidden layer weights are shared, data signatures \"\n \"for text_features and label_features must coincide.\"\n )\n\n def _create_metrics(self) -> None:\n # self.metrics preserve order\n # output losses first\n self.mask_loss = tf.keras.metrics.Mean(name=\"m_loss\")\n self.response_loss = tf.keras.metrics.Mean(name=\"r_loss\")\n # output accuracies second\n self.mask_acc = tf.keras.metrics.Mean(name=\"m_acc\")\n self.response_acc = tf.keras.metrics.Mean(name=\"r_acc\")\n\n def _update_metrics_to_log(self) -> None:\n debug_log_level = logging.getLogger(\"rasa\").level == logging.DEBUG\n\n if self.config[MASKED_LM]:\n self.metrics_to_log.append(\"m_acc\")\n if debug_log_level:\n self.metrics_to_log.append(\"m_loss\")\n\n self.metrics_to_log.append(\"r_acc\")\n if debug_log_level:\n self.metrics_to_log.append(\"r_loss\")\n\n self._log_metric_info()\n\n def _log_metric_info(self) -> None:\n metric_name = {\"t\": \"total\", \"m\": \"mask\", \"r\": \"response\"}\n logger.debug(\"Following metrics will be logged during training: \")\n for metric in self.metrics_to_log:\n parts = metric.split(\"_\")\n name = f\"{metric_name[parts[0]]} {parts[1]}\"\n logger.debug(f\" {metric} ({name})\")\n\n def _prepare_layers(self) -> None:\n self.text_name = TEXT\n self.label_name = TEXT if self.config[SHARE_HIDDEN_LAYERS] else LABEL\n\n self._prepare_sequence_layers(self.text_name)\n self._prepare_sequence_layers(self.label_name)\n if self.config[MASKED_LM]:\n self._prepare_mask_lm_layers(self.text_name)\n self._prepare_label_classification_layers()\n\n def _create_all_labels(self) -> Tuple[tf.Tensor, tf.Tensor]:\n all_label_ids = self.tf_label_data[LABEL_KEY][LABEL_SUB_KEY][0]\n\n sequence_mask_label = super()._get_mask_for(\n self.tf_label_data, LABEL, SEQUENCE_LENGTH\n )\n batch_dim = tf.shape(self.tf_label_data[LABEL_KEY][LABEL_SUB_KEY][0])[0]\n sequence_lengths_label = self._get_sequence_lengths(\n self.tf_label_data, LABEL, SEQUENCE_LENGTH, batch_dim\n )\n mask_label = self._compute_mask(sequence_lengths_label)\n\n label_transformed, _, _, _ = self._create_sequence(\n self.tf_label_data[LABEL][SEQUENCE],\n self.tf_label_data[LABEL][SENTENCE],\n sequence_mask_label,\n mask_label,\n self.label_name,\n )\n sentence_label = self._last_token(label_transformed, sequence_lengths_label)\n\n all_labels_embed = self._tf_layers[f\"embed.{LABEL}\"](sentence_label)\n\n return all_label_ids, all_labels_embed\n\n def batch_loss(\n self, batch_in: Union[Tuple[tf.Tensor], Tuple[np.ndarray]]\n ) -> tf.Tensor:\n tf_batch_data = self.batch_to_model_data_format(batch_in, self.data_signature)\n\n batch_dim = self._get_batch_dim(tf_batch_data)\n sequence_mask_text = super()._get_mask_for(tf_batch_data, TEXT, SEQUENCE_LENGTH)\n sequence_lengths_text = self._get_sequence_lengths(\n tf_batch_data, TEXT, SEQUENCE_LENGTH, batch_dim\n )\n mask_text = self._compute_mask(sequence_lengths_text)\n\n (\n text_transformed,\n text_in,\n text_seq_ids,\n lm_mask_bool_text,\n ) = self._create_sequence(\n tf_batch_data[TEXT][SEQUENCE],\n tf_batch_data[TEXT][SENTENCE],\n sequence_mask_text,\n mask_text,\n self.text_name,\n sparse_dropout=self.config[SPARSE_INPUT_DROPOUT],\n dense_dropout=self.config[DENSE_INPUT_DROPOUT],\n masked_lm_loss=self.config[MASKED_LM],\n sequence_ids=True,\n )\n\n sequence_mask_label = super()._get_mask_for(\n tf_batch_data, LABEL, SEQUENCE_LENGTH\n )\n sequence_lengths_label = self._get_sequence_lengths(\n tf_batch_data, LABEL, SEQUENCE_LENGTH, batch_dim\n )\n mask_label = self._compute_mask(sequence_lengths_label)\n\n label_transformed, _, _, _ = self._create_sequence(\n tf_batch_data[LABEL][SEQUENCE],\n tf_batch_data[LABEL][SENTENCE],\n sequence_mask_label,\n mask_label,\n self.label_name,\n )\n\n losses = []\n\n if self.config[MASKED_LM]:\n loss, acc = self._mask_loss(\n text_transformed,\n text_in,\n text_seq_ids,\n lm_mask_bool_text,\n self.text_name,\n )\n\n self.mask_loss.update_state(loss)\n self.mask_acc.update_state(acc)\n losses.append(loss)\n\n # get sentence feature vector for label classification\n sentence_vector_text = self._last_token(text_transformed, sequence_lengths_text)\n sentence_vector_label = self._last_token(\n label_transformed, sequence_lengths_label\n )\n label_ids = tf_batch_data[LABEL_KEY][LABEL_SUB_KEY][0]\n\n loss, acc = self._calculate_label_loss(\n sentence_vector_text, sentence_vector_label, label_ids\n )\n self.response_loss.update_state(loss)\n self.response_acc.update_state(acc)\n losses.append(loss)\n\n return tf.math.add_n(losses)\n\n def batch_predict(\n self, batch_in: Union[Tuple[tf.Tensor], Tuple[np.ndarray]]\n ) -> Dict[Text, tf.Tensor]:\n tf_batch_data = self.batch_to_model_data_format(\n batch_in, self.predict_data_signature\n )\n\n sequence_mask_text = super()._get_mask_for(tf_batch_data, TEXT, SEQUENCE_LENGTH)\n sequence_lengths_text = self._get_sequence_lengths(\n tf_batch_data, TEXT, SEQUENCE_LENGTH, batch_dim=1\n )\n mask_text = self._compute_mask(sequence_lengths_text)\n\n text_transformed, _, _, _ = self._create_sequence(\n tf_batch_data[TEXT][SEQUENCE],\n tf_batch_data[TEXT][SENTENCE],\n sequence_mask_text,\n mask_text,\n self.text_name,\n )\n\n out = {}\n\n if self.all_labels_embed is None:\n _, self.all_labels_embed = self._create_all_labels()\n\n # get sentence feature vector for intent classification\n sentence_vector = self._last_token(text_transformed, sequence_lengths_text)\n sentence_vector_embed = self._tf_layers[f\"embed.{TEXT}\"](sentence_vector)\n\n sim_all = self._tf_layers[f\"loss.{LABEL}\"].sim(\n sentence_vector_embed[:, tf.newaxis, :],\n self.all_labels_embed[tf.newaxis, :, :],\n )\n scores = self._tf_layers[f\"loss.{LABEL}\"].confidence_from_sim(\n sim_all, self.config[SIMILARITY_TYPE]\n )\n out[\"i_scores\"] = scores\n\n return out\n"
] | [
[
"tensorflow.math.add_n",
"tensorflow.keras.metrics.Mean",
"tensorflow.shape"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
LUGUANSONG/i2g2i | [
"ec532f2e128301472478c3d8fe4c72929e2967a4",
"ec532f2e128301472478c3d8fe4c72929e2967a4"
] | [
"combine_sg2im_neural_motifs/model.py",
"combine_sg2im_neural_motifs/train_all_in_one_bbox_feature_wgan.py"
] | [
"from lib.object_detector import ObjectDetector, gather_res\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nfrom combine_sg2im_neural_motifs.sg2im_model import Sg2ImModel\nfrom combine_sg2im_neural_motifs.discriminators import PatchDiscriminator, AcCropDiscriminator\nimport os\nfrom collections import defaultdict\nfrom lib.pytorch_misc import optimistic_restore\nimport torch.nn.functional as F\nfrom config import BOX_SCALE\nfrom sg2im.utils import timeit\n\n\ndef build_model(args):\n if args.checkpoint_start_from is not None:\n checkpoint = torch.load(args.checkpoint_start_from)\n kwargs = checkpoint['model_kwargs']\n model = Sg2ImModel(**kwargs)\n raw_state_dict = checkpoint['model_state']\n state_dict = {}\n for k, v in raw_state_dict.items():\n if k.startswith('module.'):\n k = k[7:]\n state_dict[k] = v\n model.load_state_dict(state_dict)\n else:\n kwargs = {\n 'image_size': args.image_size,\n 'embedding_dim': args.embedding_dim,\n 'gconv_dim': args.gconv_dim,\n 'gconv_hidden_dim': args.gconv_hidden_dim,\n 'gconv_num_layers': args.gconv_num_layers,\n 'mlp_normalization': args.mlp_normalization,\n 'refinement_dims': args.refinement_network_dims,\n 'normalization': args.normalization,\n 'activation': args.activation,\n 'mask_size': args.mask_size,\n 'layout_noise_dim': args.layout_noise_dim,\n }\n model = Sg2ImModel(**kwargs)\n return model, kwargs\n\n\ndef build_obj_discriminator(args, vocab):\n discriminator = None\n d_kwargs = {}\n d_weight = args.discriminator_loss_weight\n d_obj_weight = args.d_obj_weight\n if d_weight == 0 or d_obj_weight == 0:\n return discriminator, d_kwargs\n\n d_kwargs = {\n 'vocab': vocab,\n 'arch': args.d_obj_arch,\n 'normalization': args.d_normalization,\n 'activation': args.d_activation,\n 'padding': args.d_padding,\n 'object_size': args.crop_size,\n }\n discriminator = AcCropDiscriminator(**d_kwargs)\n return discriminator, d_kwargs\n\n\ndef build_img_discriminator(args):\n discriminator = None\n d_kwargs = {}\n d_weight = args.discriminator_loss_weight\n d_img_weight = args.d_img_weight\n if d_weight == 0 or d_img_weight == 0:\n return discriminator, d_kwargs\n\n d_kwargs = {\n 'arch': args.d_img_arch,\n 'normalization': args.d_normalization,\n 'activation': args.d_activation,\n 'padding': args.d_padding,\n }\n discriminator = PatchDiscriminator(**d_kwargs)\n return discriminator, d_kwargs\n\n\nclass neural_motifs_sg2im_model(nn.Module):\n def __init__(self, args, ind_to_classes):\n super(neural_motifs_sg2im_model, self).__init__()\n self.args = args\n\n # define and initial detector\n self.detector = ObjectDetector(classes=ind_to_classes, num_gpus=args.num_gpus,\n mode='refinerels' if not args.use_proposals else 'proposals',\n use_resnet=args.use_resnet)\n if args.ckpt is not None:\n ckpt = torch.load(args.ckpt)\n optimistic_restore(self.detector, ckpt['state_dict'])\n self.detector.eval()\n\n # define and initial generator, image_discriminator, obj_discriminator,\n # and corresponding optimizer\n vocab = {\n 'object_idx_to_name': ind_to_classes,\n }\n self.model, model_kwargs = build_model(args)\n\n self.optimizer = torch.optim.Adam(self.model.parameters(), lr=args.learning_rate)\n\n self.obj_discriminator, d_obj_kwargs = build_obj_discriminator(args, vocab)\n self.img_discriminator, d_img_kwargs = build_img_discriminator(args)\n\n if self.obj_discriminator is not None:\n self.obj_discriminator.train()\n self.optimizer_d_obj = torch.optim.Adam(self.obj_discriminator.parameters(), lr=args.learning_rate)\n\n if self.img_discriminator is not None:\n self.img_discriminator.train()\n self.optimizer_d_img = torch.optim.Adam(self.img_discriminator.parameters(), lr=args.learning_rate)\n\n restore_path = None\n if args.restore_from_checkpoint:\n restore_path = '%s_with_model.pt' % args.checkpoint_name\n restore_path = os.path.join(args.output_dir, restore_path)\n if restore_path is not None and os.path.isfile(restore_path):\n print('Restoring from checkpoint:')\n print(restore_path)\n checkpoint = torch.load(restore_path)\n self.model.load_state_dict(checkpoint['model_state'])\n self.optimizer.load_state_dict(checkpoint['optim_state'])\n\n if self.obj_discriminator is not None:\n self.obj_discriminator.load_state_dict(checkpoint['d_obj_state'])\n self.optimizer_d_obj.load_state_dict(checkpoint['d_obj_optim_state'])\n\n if self.img_discriminator is not None:\n self.img_discriminator.load_state_dict(checkpoint['d_img_state'])\n self.optimizer_d_img.load_state_dict(checkpoint['d_img_optim_state'])\n\n t = checkpoint['counters']['t']\n if 0 <= args.eval_mode_after <= t:\n self.model.eval()\n else:\n self.model.train()\n epoch = checkpoint['counters']['epoch']\n else:\n t, epoch = 0, 0\n checkpoint = {\n 'vocab': vocab,\n 'model_kwargs': model_kwargs,\n 'd_obj_kwargs': d_obj_kwargs,\n 'd_img_kwargs': d_img_kwargs,\n 'losses_ts': [],\n 'losses': defaultdict(list),\n 'd_losses': defaultdict(list),\n 'checkpoint_ts': [],\n 'train_batch_data': [],\n 'train_samples': [],\n 'train_iou': [],\n 'val_batch_data': [],\n 'val_samples': [],\n 'val_losses': defaultdict(list),\n 'val_iou': [],\n 'norm_d': [],\n 'norm_g': [],\n 'counters': {\n 't': None,\n 'epoch': None,\n },\n 'model_state': None, 'model_best_state': None, 'optim_state': None,\n 'd_obj_state': None, 'd_obj_best_state': None, 'd_obj_optim_state': None,\n 'd_img_state': None, 'd_img_best_state': None, 'd_img_optim_state': None,\n 'best_t': [],\n }\n\n self.t, self.epoch, self.checkpoint = t, epoch, checkpoint\n\n def forward(self, x, im_sizes, image_offset,\n gt_boxes=None, gt_classes=None, gt_rels=None, proposals=None, train_anchor_inds=None,\n return_fmap=False):\n # forward detector\n with timeit('detector forward', self.args.timing):\n result = self.detector(x, im_sizes, image_offset, gt_boxes, gt_classes, gt_rels, proposals,\n train_anchor_inds, return_fmap=True)\n if result.is_none():\n return ValueError(\"heck\")\n\n # forward generator\n imgs = F.interpolate(x, size=self.args.image_size)\n objs = result.obj_preds\n boxes = result.rm_box_priors / BOX_SCALE\n obj_to_img = result.im_inds - image_offset\n obj_fmap = result.obj_fmap\n\n # check if all image have detection\n cnt = torch.zeros(len(imgs)).byte()\n cnt[obj_to_img] += 1\n if (cnt > 0).sum() != len(imgs):\n print(\"some imgs have no detection\")\n print(cnt)\n imgs = imgs[cnt]\n obj_to_img_new = obj_to_img.clone()\n for i in range(len(cnt)):\n if cnt[i] == 0:\n obj_to_img_new -= (obj_to_img > i).long()\n obj_to_img = obj_to_img_new\n\n with timeit('generator forward', self.args.timing):\n imgs_pred = self.model(obj_to_img, boxes, obj_fmap)\n\n # forward discriminators to train generator\n if self.obj_discriminator is not None:\n with timeit('d_obj forward for g', self.args.timing):\n g_scores_fake_crop, g_obj_scores_fake_crop = self.obj_discriminator(imgs_pred, objs, boxes, obj_to_img)\n\n if self.img_discriminator is not None:\n with timeit('d_img forward for g', self.args.timing):\n g_scores_fake_img = self.img_discriminator(imgs_pred)\n\n # forward discriminators to train discriminators\n if self.obj_discriminator is not None:\n imgs_fake = imgs_pred.detach()\n with timeit('d_obj forward for d', self.args.timing):\n d_scores_fake_crop, d_obj_scores_fake_crop = self.obj_discriminator(imgs_fake, objs, boxes, obj_to_img)\n d_scores_real_crop, d_obj_scores_real_crop = self.obj_discriminator(imgs, objs, boxes, obj_to_img)\n\n if self.img_discriminator is not None:\n imgs_fake = imgs_pred.detach()\n with timeit('d_img forward for d', self.args.timing):\n d_scores_fake_img = self.img_discriminator(imgs_fake)\n d_scores_real_img = self.img_discriminator(imgs)\n\n return Result(\n imgs=imgs,\n imgs_pred=imgs_pred,\n objs=objs,\n g_scores_fake_crop=g_scores_fake_crop,\n g_obj_scores_fake_crop=g_obj_scores_fake_crop,\n g_scores_fake_img=g_scores_fake_img,\n d_scores_fake_crop=d_scores_fake_crop,\n d_obj_scores_fake_crop=d_obj_scores_fake_crop,\n d_scores_real_crop=d_scores_real_crop,\n d_obj_scores_real_crop=d_obj_scores_real_crop,\n d_scores_fake_img=d_scores_fake_img,\n d_scores_real_img=d_scores_real_img\n )\n # return imgs, imgs_pred, objs, g_scores_fake_crop, g_obj_scores_fake_crop, g_scores_fake_img, d_scores_fake_crop, \\\n # d_obj_scores_fake_crop, d_scores_real_crop, d_obj_scores_real_crop, d_scores_fake_img, d_scores_real_img\n\n def __getitem__(self, batch):\n \"\"\" Hack to do multi-GPU training\"\"\"\n batch.scatter()\n if self.args.num_gpus == 1:\n return self(*batch[0])\n\n replicas = nn.parallel.replicate(self, devices=list(range(self.args.num_gpus)))\n outputs = nn.parallel.parallel_apply(replicas, [batch[i] for i in range(self.args.num_gpus)])\n\n if self.training:\n return gather_res(outputs, 0, dim=0)\n return outputs\n\n\nclass Result(object):\n def __init__(self, imgs=None,\n imgs_pred=None,\n objs=None,\n g_scores_fake_crop=None,\n g_obj_scores_fake_crop=None,\n g_scores_fake_img=None,\n d_scores_fake_crop=None,\n d_obj_scores_fake_crop=None,\n d_scores_real_crop=None,\n d_obj_scores_real_crop=None,\n d_scores_fake_img=None,\n d_scores_real_img=None):\n self.__dict__.update(locals())\n del self.__dict__['self']\n\n def is_none(self):\n return all([v is None for k, v in self.__dict__.items() if k != 'self'])\n",
"#!/usr/bin/python\n#\n# Copyright 2018 Google LLC\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\nimport os\nfrom os.path import exists, join\nimport math\nfrom collections import defaultdict\nfrom tqdm import tqdm\nimport numpy as np\nimport torch\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom tensorboardX import SummaryWriter\n\n# sg2im\nfrom sg2im.losses import get_gan_losses, VGGLoss\nfrom sg2im.utils import timeit, bool_flag, LossManager\n\n# neural motifs\n# from dataloaders.visual_genome import VGDataLoader, VG\n# from dataloaders.mscoco import CocoDetection, CocoDataLoader\nfrom torchvision import transforms\nfrom bbox_feature_dataset.bbox_feature_dataset import VG, VGDataLoader\n# from config import ModelConfig\nfrom config_args import config_args\nfrom copy import deepcopy\n\n# combine\nfrom model_bbox_feature import neural_motifs_sg2im_model\n\ntorch.backends.cudnn.benchmark = True\n\n\ndef add_loss(total_loss, curr_loss, loss_dict, loss_name, weight=1):\n curr_loss = curr_loss * weight\n loss_dict[loss_name] = curr_loss.item()\n if total_loss is not None:\n total_loss += curr_loss\n else:\n total_loss = curr_loss\n return total_loss\n\n\ndef check_args(args):\n H, W = args.image_size\n for _ in args.refinement_network_dims[1:]:\n H = H // 2\n if H == 0:\n raise ValueError(\"Too many layers in refinement network\")\n\n\ndef check_model(args, loader, model):\n model.eval()\n num_samples = 0\n all_losses = defaultdict(list)\n model.forward_G = True\n model.calc_G_D_loss = False\n model.forward_D = True\n with torch.no_grad():\n for batch in loader:\n _batch = deepcopy(batch)\n result = model[_batch]\n # imgs, imgs_pred, objs, g_scores_fake_crop, g_obj_scores_fake_crop, g_scores_fake_img, \\\n # d_scores_fake_crop, d_obj_scores_fake_crop, d_scores_real_crop, d_obj_scores_real_crop, \\\n # d_scores_fake_img, d_scores_real_img = result.imgs, result.imgs_pred, result.objs, \\\n # result.g_scores_fake_crop, result.g_obj_scores_fake_crop, result.g_scores_fake_img, \\\n # result.d_scores_fake_crop, result.d_obj_scores_fake_crop, result.d_scores_real_crop, \\\n # result.d_obj_scores_real_crop, result.d_scores_fake_img, result.d_scores_real_img\n imgs, imgs_pred = result.imgs, result.imgs_pred\n mask_noise_indexes = result.mask_noise_indexes\n\n total_loss, losses = calculate_model_losses(\n args, imgs, imgs_pred, mask_noise_indexes)\n for loss_name, loss_val in losses.items():\n all_losses[loss_name].append(loss_val)\n num_samples += imgs.size(0)\n if num_samples >= args.num_val_samples:\n break\n\n same_input_different_noise = []\n for i in range(args.num_diff_noise):\n _batch = deepcopy(batch)\n result = model[_batch]\n same_input_different_noise.append(result.imgs_pred.detach().cpu())\n different_same_input = [torch.cat([batch[i:i+1] for batch in same_input_different_noise], dim=3) for i in range(len(same_input_different_noise[0]))]\n different_same_input = torch.cat(different_same_input, dim=2)\n\n samples = {}\n samples['gt_img'] = imgs\n samples['pred_img'] = imgs_pred\n samples['diff_noise_img'] = different_same_input\n samples['bg_layout'] = result.bg_layout\n if model.obj_discriminator is not None:\n real_crops, fake_crops = result.real_crops, result.fake_crops\n samples['real_crops'] = real_crops\n samples['fake_crops'] = fake_crops\n\n for k, images in samples.items():\n if k == \"bg_layout\":\n continue\n images = images * torch.tensor([0.229, 0.224, 0.225], device=images.device).reshape(1, 3, 1, 1)\n images = images + torch.tensor([0.485, 0.456, 0.406], device=images.device).reshape(1, 3, 1, 1)\n images_min = images.min(3)[0].min(2)[0].min(1)[0].reshape(len(images), 1, 1, 1)\n images_max = images.max(3)[0].max(2)[0].max(1)[0].reshape(len(images), 1, 1, 1)\n images = images - images_min\n images = images / (images_max - images_min)\n images = images.clamp(min=0, max=1)\n samples[k] = images\n\n mean_losses = {k: np.mean(v) for k, v in all_losses.items()}\n\n out = [mean_losses, samples]\n\n return tuple(out)\n\n\ndef calculate_model_losses(args, img, img_pred, mask_noise_indexes=None):\n total_loss = torch.zeros(1).to(img)\n losses = {}\n\n l1_pixel_weight = args.l1_pixel_loss_weight\n if mask_noise_indexes is not None:\n l1_pixel_loss = F.l1_loss(img_pred[mask_noise_indexes], img[mask_noise_indexes])\n else:\n l1_pixel_loss = F.l1_loss(img_pred, img)\n # print(\"check l1_pixel_weight here, it is %.10f\" % l1_pixel_weight)\n total_loss = add_loss(total_loss, l1_pixel_loss, losses, 'L1_pixel_loss',\n l1_pixel_weight)\n return total_loss, losses\n\n\ndef main(args):\n print(args)\n check_args(args)\n if not exists(args.output_dir):\n os.makedirs(args.output_dir)\n summary_writer = SummaryWriter(args.output_dir)\n\n # if args.coco:\n # train, val = CocoDetection.splits()\n # val.ids = val.ids[:args.val_size]\n # train.ids = train.ids\n # train_loader, val_loader = CocoDataLoader.splits(train, val, batch_size=args.batch_size,\n # num_workers=args.num_workers,\n # num_gpus=args.num_gpus)\n # else:\n train, val, _ = VG.splits(transform=transforms.Compose([\n transforms.Resize(args.image_size),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n ]), args=args)\n train_loader, val_loader = VGDataLoader.splits(train, val, batch_size=args.batch_size,\n num_workers=args.num_workers,\n num_gpus=args.num_gpus)\n print(train.ind_to_classes)\n\n all_in_one_model = neural_motifs_sg2im_model(args, train.ind_to_classes)\n print(all_in_one_model)\n # Freeze the detector\n # for n, param in all_in_one_model.detector.named_parameters():\n # param.requires_grad = False\n all_in_one_model.cuda()\n gan_g_loss, gan_d_loss = get_gan_losses(args.gan_loss_type)\n criterionVGG = VGGLoss() if args.perceptual_loss_weight > 0 else None\n\n t, epoch, checkpoint = all_in_one_model.t, all_in_one_model.epoch, all_in_one_model.checkpoint\n\n def D_step(result):\n imgs, imgs_pred, objs, \\\n d_scores_fake_crop, d_obj_scores_fake_crop, d_scores_real_crop, \\\n d_obj_scores_real_crop, d_scores_fake_img, d_scores_real_img, \\\n d_obj_gp, d_img_gp \\\n = result.imgs, result.imgs_pred, result.objs, \\\n result.d_scores_fake_crop, result.d_obj_scores_fake_crop, result.d_scores_real_crop, \\\n result.d_obj_scores_real_crop, result.d_scores_fake_img, result.d_scores_real_img, \\\n result.d_obj_gp, result.d_img_gp\n d_rec_feature_fake_crop, d_rec_feature_real_crop = result.d_rec_feature_fake_crop, result.d_rec_feature_real_crop\n obj_fmaps=result.obj_fmaps\n d_scores_fake_bg, d_scores_real_bg, d_bg_gp = result.d_scores_fake_bg, result.d_scores_real_bg, result.d_bg_gp\n\n d_obj_losses, d_img_losses, d_bg_losses = None, None, None\n if all_in_one_model.obj_discriminator is not None:\n with timeit('d_obj loss', args.timing):\n d_obj_losses = LossManager()\n if args.d_obj_weight > 0:\n d_obj_gan_loss = gan_d_loss(d_scores_real_crop, d_scores_fake_crop)\n d_obj_losses.add_loss(d_obj_gan_loss, 'd_obj_gan_loss')\n if args.gan_loss_type == 'wgan-gp':\n d_obj_losses.add_loss(d_obj_gp.mean(), 'd_obj_gp', args.d_obj_gp_weight)\n if args.ac_loss_weight > 0:\n d_obj_losses.add_loss(F.cross_entropy(d_obj_scores_real_crop, objs), 'd_ac_loss_real')\n d_obj_losses.add_loss(F.cross_entropy(d_obj_scores_fake_crop, objs), 'd_ac_loss_fake')\n if args.d_obj_rec_feat_weight > 0:\n d_obj_losses.add_loss(F.l1_loss(d_rec_feature_fake_crop, obj_fmaps), 'd_obj_fea_rec_loss_fake')\n d_obj_losses.add_loss(F.l1_loss(d_rec_feature_real_crop, obj_fmaps), 'd_obj_fea_rec_loss_real')\n\n with timeit('d_obj backward', args.timing):\n all_in_one_model.optimizer_d_obj.zero_grad()\n d_obj_losses.total_loss.backward()\n all_in_one_model.optimizer_d_obj.step()\n\n if all_in_one_model.img_discriminator is not None:\n with timeit('d_img loss', args.timing):\n d_img_losses = LossManager()\n d_img_gan_loss = gan_d_loss(d_scores_real_img, d_scores_fake_img)\n d_img_losses.add_loss(d_img_gan_loss, 'd_img_gan_loss')\n if args.gan_loss_type == 'wgan-gp':\n d_img_losses.add_loss(d_img_gp.mean(), 'd_img_gp', args.d_img_gp_weight)\n\n with timeit('d_img backward', args.timing):\n all_in_one_model.optimizer_d_img.zero_grad()\n d_img_losses.total_loss.backward()\n all_in_one_model.optimizer_d_img.step()\n\n if all_in_one_model.bg_discriminator is not None:\n with timeit('d_bg loss', args.timing):\n d_bg_losses = LossManager()\n d_bg_gan_loss = gan_d_loss(d_scores_real_bg, d_scores_fake_bg)\n d_bg_losses.add_loss(d_bg_gan_loss, 'd_bg_gan_loss')\n if args.gan_loss_type == 'wgan-gp':\n d_bg_losses.add_loss(d_bg_gp.mean(), 'd_bg_gp', args.d_bg_gp_weight)\n\n with timeit('d_bg backward', args.timing):\n all_in_one_model.optimizer_d_bg.zero_grad()\n d_bg_losses.total_loss.backward()\n all_in_one_model.optimizer_d_bg.step()\n\n return d_obj_losses, d_img_losses, d_bg_losses\n\n def G_step(result):\n imgs, imgs_pred, objs, \\\n g_scores_fake_crop, g_obj_scores_fake_crop, g_scores_fake_img, \\\n = result.imgs, result.imgs_pred, result.objs, \\\n result.g_scores_fake_crop, result.g_obj_scores_fake_crop, result.g_scores_fake_img\n mask_noise_indexes = result.mask_noise_indexes\n g_rec_feature_fake_crop = result.g_rec_feature_fake_crop\n obj_fmaps = result.obj_fmaps\n g_scores_fake_bg = result.g_scores_fake_bg\n \n with timeit('loss', args.timing):\n total_loss, losses = calculate_model_losses(\n args, imgs, imgs_pred, mask_noise_indexes)\n\n if criterionVGG is not None:\n if mask_noise_indexes is not None and args.perceptual_not_on_noise:\n perceptual_loss = criterionVGG(imgs_pred[mask_noise_indexes], imgs[mask_noise_indexes])\n else:\n perceptual_loss = criterionVGG(imgs_pred, imgs)\n total_loss = add_loss(total_loss, perceptual_loss, losses, 'perceptual_loss',\n args.perceptual_loss_weight)\n\n if all_in_one_model.obj_discriminator is not None:\n total_loss = add_loss(total_loss, F.cross_entropy(g_obj_scores_fake_crop, objs), losses, 'ac_loss',\n args.ac_loss_weight)\n weight = args.discriminator_loss_weight * args.d_obj_weight\n total_loss = add_loss(total_loss, gan_g_loss(g_scores_fake_crop), losses,\n 'g_gan_obj_loss', weight)\n if args.d_obj_rec_feat_weight > 0:\n total_loss = add_loss(total_loss, F.l1_loss(g_rec_feature_fake_crop, obj_fmaps), losses,\n 'g_obj_fea_rec_loss', args.d_obj_rec_feat_weight)\n\n if all_in_one_model.img_discriminator is not None:\n weight = args.discriminator_loss_weight * args.d_img_weight\n total_loss = add_loss(total_loss, gan_g_loss(g_scores_fake_img), losses,\n 'g_gan_img_loss', weight)\n\n if all_in_one_model.bg_discriminator is not None:\n weight = args.discriminator_loss_weight * args.d_bg_weight\n total_loss = add_loss(total_loss, gan_g_loss(g_scores_fake_bg), losses,\n 'g_gan_bg_loss', weight)\n\n losses['total_loss'] = total_loss.item()\n\n if math.isfinite(losses['total_loss']):\n with timeit('backward', args.timing):\n all_in_one_model.optimizer.zero_grad()\n total_loss.backward()\n all_in_one_model.optimizer.step()\n\n return losses\n\n while True:\n if t >= args.num_iterations * (args.n_critic + args.n_gen):\n break\n epoch += 1\n print('Starting epoch %d' % epoch)\n\n for step, batch in enumerate(tqdm(train_loader, desc='Training Epoch %d' % epoch, total=len(train_loader))):\n # if t == args.eval_mode_after:\n # print('switching to eval mode')\n # all_in_one_model.model.eval()\n # all_in_one_model.optimizer = optim.Adam(all_in_one_model.parameters(), lr=args.learning_rate)\n all_in_one_model.train()\n modes = ['l1', 'noise_std', 'd_obj', 'd_img', 'ac_loss']\n attrs = ['l1_pixel_loss_weight', 'noise_std', 'd_obj_weight', 'd_img_weight', 'ac_loss_weight']\n for mode, attr in zip(modes, attrs):\n old_value = getattr(args, attr)\n if getattr(args, \"%s_mode\" % mode) == \"change\" and t in getattr(args, \"%s_change_iters\" % mode):\n step_index = getattr(args, \"%s_change_iters\" % mode).index(t)\n new_value = getattr(args, \"%s_change_vals\" % mode)[step_index]\n setattr(args, attr, new_value)\n print(\"Change %s from %.10f to %.10f at iteration %d\" % (attr, old_value, getattr(args, attr), t))\n elif getattr(args, \"%s_mode\" % mode) == \"change_linear\":\n start_step = getattr(args, \"%s_change_iters\" % mode)[0]\n end_step = getattr(args, \"%s_change_iters\" % mode)[1]\n if start_step <= t <= end_step:\n start_val = getattr(args, \"%s_change_vals\" % mode)[0]\n end_val = getattr(args, \"%s_change_vals\" % mode)[1]\n new_value = start_val + (end_val - start_val) * (t - start_step) / (end_step - start_step)\n setattr(args, attr, new_value)\n print(\"Change %s from %.10f to %.10f at iteration %d\" % (attr, old_value, getattr(args, attr), t))\n elif t > end_step:\n end_val = getattr(args, \"%s_change_vals\" % mode)[1]\n if old_value != end_val:\n new_value = end_val\n setattr(args, attr, new_value)\n print(\"probably resume training from previous checkpoint\")\n print(\"Change %s from %.10f to %.10f at iteration %d\" % (attr, old_value, getattr(args, attr), t))\n t += 1\n if args.gan_loss_type in [\"wgan\", \"wgan-gp\"] or args.n_critic != 0:\n # train discriminator (critic) for n_critic iterations\n if t % (args.n_critic + args.n_gen) in list(range(1, args.n_critic+1)):\n all_in_one_model.forward_G = True\n all_in_one_model.calc_G_D_loss = False\n all_in_one_model.forward_D = True\n all_in_one_model.set_requires_grad(\n [all_in_one_model.obj_discriminator, all_in_one_model.img_discriminator],\n True)\n with timeit('forward', args.timing):\n result = all_in_one_model[batch]\n d_obj_losses, d_img_losses, d_bg_losses = D_step(result)\n\n # train generator for 1 iteration after n_critic iterations\n if t % (args.n_critic + args.n_gen) in (list(range(args.n_critic+1, args.n_critic + args.n_gen)) + [0]):\n all_in_one_model.forward_G = True\n all_in_one_model.calc_G_D_loss = True\n all_in_one_model.forward_D = False\n all_in_one_model.set_requires_grad(\n [all_in_one_model.obj_discriminator, all_in_one_model.img_discriminator],\n False)\n result = all_in_one_model[batch]\n\n losses = G_step(result)\n if not math.isfinite(losses['total_loss']):\n print('WARNING: Got loss = NaN, not backpropping')\n continue\n else: # vanilla gan or lsgan\n all_in_one_model.forward_G = True\n all_in_one_model.calc_G_D_loss = True\n all_in_one_model.forward_D = True\n with timeit('forward', args.timing):\n result = all_in_one_model[batch]\n losses = G_step(result)\n if not math.isfinite(losses['total_loss']):\n print('WARNING: Got loss = NaN, not backpropping')\n continue\n d_obj_losses, d_img_losses, d_bg_losses = D_step(result)\n\n if t % (args.print_every * (args.n_critic + args.n_gen)) == 0:\n print('t = %d / %d' % (t, args.num_iterations))\n G_loss_list = []\n for name, val in losses.items():\n G_loss_list.append('[%s]: %.4f' % (name, val))\n checkpoint['losses'][name].append(val)\n summary_writer.add_scalar(\"G_%s\" % name, val, t)\n print(\"G: %s\" % \", \".join(G_loss_list))\n checkpoint['losses_ts'].append(t)\n\n if all_in_one_model.obj_discriminator is not None:\n D_obj_loss_list = []\n for name, val in d_obj_losses.items():\n D_obj_loss_list.append('[%s]: %.4f' % (name, val))\n checkpoint['d_losses'][name].append(val)\n summary_writer.add_scalar(\"D_obj_%s\" % name, val, t)\n print(\"D_obj: %s\" % \", \".join(D_obj_loss_list))\n\n if all_in_one_model.img_discriminator is not None:\n D_img_loss_list = []\n for name, val in d_img_losses.items():\n D_img_loss_list.append('[%s]: %.4f' % (name, val))\n checkpoint['d_losses'][name].append(val)\n summary_writer.add_scalar(\"D_img_%s\" % name, val, t)\n print(\"D_img: %s\" % \", \".join(D_img_loss_list))\n\n if all_in_one_model.bg_discriminator is not None:\n D_bg_loss_list = []\n for name, val in d_bg_losses.items():\n D_bg_loss_list.append('[%s]: %.4f' % (name, val))\n checkpoint['d_losses'][name].append(val)\n summary_writer.add_scalar(\"D_bg_%s\" % name, val, t)\n print(\"D_bg: %s\" % \", \".join(D_bg_loss_list))\n\n if t % (args.checkpoint_every * (args.n_critic + args.n_gen)) == 0:\n print('checking on train')\n train_results = check_model(args, train_loader, all_in_one_model)\n t_losses, t_samples = train_results\n\n checkpoint['train_samples'].append(t_samples)\n checkpoint['checkpoint_ts'].append(t)\n for name, images in t_samples.items():\n summary_writer.add_image(\"train_%s\" % name, images, t)\n\n print('checking on val')\n val_results = check_model(args, val_loader, all_in_one_model)\n val_losses, val_samples = val_results\n checkpoint['val_samples'].append(val_samples)\n for name, images in val_samples.items():\n summary_writer.add_image(\"val_%s\" % name, images, t)\n\n for k, v in val_losses.items():\n checkpoint['val_losses'][k].append(v)\n summary_writer.add_scalar(\"val_%s\" % k, v, t)\n checkpoint['model_state'] = all_in_one_model.model.state_dict()\n\n if all_in_one_model.obj_discriminator is not None:\n checkpoint['d_obj_state'] = all_in_one_model.obj_discriminator.state_dict()\n checkpoint['d_obj_optim_state'] = all_in_one_model.optimizer_d_obj.state_dict()\n\n if all_in_one_model.img_discriminator is not None:\n checkpoint['d_img_state'] = all_in_one_model.img_discriminator.state_dict()\n checkpoint['d_img_optim_state'] = all_in_one_model.optimizer_d_img.state_dict()\n\n if all_in_one_model.bg_discriminator is not None:\n checkpoint['d_bg_state'] = all_in_one_model.bg_discriminator.state_dict()\n checkpoint['d_bg_optim_state'] = all_in_one_model.optimizer_d_bg.state_dict()\n\n checkpoint['optim_state'] = all_in_one_model.optimizer.state_dict()\n checkpoint['counters']['t'] = t\n checkpoint['counters']['epoch'] = epoch\n checkpoint_path = os.path.join(args.output_dir,\n '%s_with_model.pt' % args.checkpoint_name)\n print('Saving checkpoint to ', checkpoint_path)\n torch.save(checkpoint, checkpoint_path)\n\n # Save another checkpoint without any model or optim state\n checkpoint_path = os.path.join(args.output_dir,\n '%s_no_model.pt' % args.checkpoint_name)\n key_blacklist = ['model_state', 'optim_state', 'model_best_state',\n 'd_obj_state', 'd_obj_optim_state', 'd_obj_best_state',\n 'd_img_state', 'd_img_optim_state', 'd_img_best_state',\n 'd_bg_state', 'd_bg_optim_state', 'd_bg_best_state']\n small_checkpoint = {}\n for k, v in checkpoint.items():\n if k not in key_blacklist:\n small_checkpoint[k] = v\n torch.save(small_checkpoint, checkpoint_path)\n\n\nif __name__ == '__main__':\n # args = ModelConfig()\n args = config_args\n main(args)\n\n"
] | [
[
"torch.nn.functional.interpolate",
"torch.load"
],
[
"torch.nn.functional.l1_loss",
"torch.zeros",
"torch.cat",
"torch.nn.functional.cross_entropy",
"torch.tensor",
"torch.no_grad",
"numpy.mean",
"torch.save"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
charzy/vocalremover | [
"9bf983ab5579c36c75447c74eec0400d78ab49f9",
"9bf983ab5579c36c75447c74eec0400d78ab49f9"
] | [
"inference.py",
"lib/nets.py"
] | [
"import argparse\nimport os\n\nimport cv2\nimport librosa\nimport numpy as np\nimport soundfile as sf\nimport torch\nfrom tqdm import tqdm\n\nfrom lib import dataset\nfrom lib import nets\nfrom lib import spec_utils\n\n\nclass VocalRemover(object):\n\n def __init__(self, model, device, window_size):\n self.model = model\n self.offset = model.offset\n self.device = device\n self.window_size = window_size\n\n def _execute(self, X_mag_pad, roi_size, n_window):\n self.model.eval()\n with torch.no_grad():\n preds = []\n for i in tqdm(range(n_window)):\n start = i * roi_size\n X_mag_window = X_mag_pad[None, :, :, start:start + self.window_size]\n X_mag_window = torch.from_numpy(X_mag_window).to(self.device)\n\n pred = self.model.predict(X_mag_window)\n\n pred = pred.detach().cpu().numpy()\n preds.append(pred[0])\n\n pred = np.concatenate(preds, axis=2)\n\n return pred\n\n def preprocess(self, X_spec):\n X_mag = np.abs(X_spec)\n X_phase = np.angle(X_spec)\n\n return X_mag, X_phase\n\n def inference(self, X_spec):\n X_mag, X_phase = self.preprocess(X_spec)\n\n coef = X_mag.max()\n X_mag_pre = X_mag / coef\n\n n_frame = X_mag_pre.shape[2]\n pad_l, pad_r, roi_size = dataset.make_padding(n_frame, self.window_size, self.offset)\n n_window = int(np.ceil(n_frame / roi_size))\n\n X_mag_pad = np.pad(X_mag_pre, ((0, 0), (0, 0), (pad_l, pad_r)), mode='constant')\n\n pred = self._execute(X_mag_pad, roi_size, n_window)\n pred = pred[:, :, :n_frame]\n\n return pred * coef, X_mag, np.exp(1.j * X_phase)\n\n def inference_tta(self, X_spec):\n X_mag, X_phase = self.preprocess(X_spec)\n\n coef = X_mag.max()\n X_mag_pre = X_mag / coef\n\n n_frame = X_mag_pre.shape[2]\n pad_l, pad_r, roi_size = dataset.make_padding(n_frame, self.window_size, self.offset)\n n_window = int(np.ceil(n_frame / roi_size))\n\n X_mag_pad = np.pad(X_mag_pre, ((0, 0), (0, 0), (pad_l, pad_r)), mode='constant')\n\n pred = self._execute(X_mag_pad, roi_size, n_window)\n pred = pred[:, :, :n_frame]\n\n pad_l += roi_size // 2\n pad_r += roi_size // 2\n n_window += 1\n\n X_mag_pad = np.pad(X_mag_pre, ((0, 0), (0, 0), (pad_l, pad_r)), mode='constant')\n\n pred_tta = self._execute(X_mag_pad, roi_size, n_window)\n pred_tta = pred_tta[:, :, roi_size // 2:]\n pred_tta = pred_tta[:, :, :n_frame]\n\n return (pred + pred_tta) * 0.5 * coef, X_mag, np.exp(1.j * X_phase)\n\n\ndef main():\n p = argparse.ArgumentParser()\n p.add_argument('--gpu', '-g', type=int, default=-1)\n p.add_argument('--pretrained_model', '-P', type=str, default='models/baseline.pth')\n p.add_argument('--input', '-i', required=True)\n p.add_argument('--sr', '-r', type=int, default=44100)\n p.add_argument('--n_fft', '-f', type=int, default=2048)\n p.add_argument('--hop_length', '-l', type=int, default=1024)\n p.add_argument('--window_size', '-w', type=int, default=512)\n p.add_argument('--output_image', '-I', action='store_true')\n p.add_argument('--postprocess', '-p', action='store_true')\n p.add_argument('--tta', '-t', action='store_true')\n args = p.parse_args()\n\n print('loading model...', end=' ')\n device = torch.device('cpu')\n model = nets.CascadedASPPNet(args.n_fft)\n model.load_state_dict(torch.load(args.pretrained_model, map_location=device))\n if torch.cuda.is_available() and args.gpu >= 0:\n device = torch.device('cuda:{}'.format(args.gpu))\n model.to(device)\n print('done')\n\n print('loading wave source...', end=' ')\n X, sr = librosa.load(\n args.input, args.sr, False, dtype=np.float32, res_type='kaiser_fast')\n basename = os.path.splitext(os.path.basename(args.input))[0]\n print('done')\n\n if X.ndim == 1:\n X = np.asarray([X, X])\n\n print('stft of wave source...', end=' ')\n X = spec_utils.wave_to_spectrogram(X, args.hop_length, args.n_fft)\n print('done')\n\n vr = VocalRemover(model, device, args.window_size)\n\n if args.tta:\n pred, X_mag, X_phase = vr.inference_tta(X)\n else:\n pred, X_mag, X_phase = vr.inference(X)\n\n if args.postprocess:\n print('post processing...', end=' ')\n pred_inv = np.clip(X_mag - pred, 0, np.inf)\n pred = spec_utils.mask_silence(pred, pred_inv)\n print('done')\n\n print('inverse stft of instruments...', end=' ')\n y_spec = pred * X_phase\n wave = spec_utils.spectrogram_to_wave(y_spec, hop_length=args.hop_length)\n print('done')\n sf.write('{}_Instruments.wav'.format(basename), wave.T, sr)\n\n print('inverse stft of vocals...', end=' ')\n v_spec = np.clip(X_mag - pred, 0, np.inf) * X_phase\n wave = spec_utils.spectrogram_to_wave(v_spec, hop_length=args.hop_length)\n print('done')\n sf.write('{}_Vocals.wav'.format(basename), wave.T, sr)\n\n if args.output_image:\n with open('{}_Instruments.jpg'.format(basename), mode='wb') as f:\n image = spec_utils.spectrogram_to_image(y_spec)\n _, bin_image = cv2.imencode('.jpg', image)\n bin_image.tofile(f)\n with open('{}_Vocals.jpg'.format(basename), mode='wb') as f:\n image = spec_utils.spectrogram_to_image(v_spec)\n _, bin_image = cv2.imencode('.jpg', image)\n bin_image.tofile(f)\n\n\nif __name__ == '__main__':\n main()\n",
"import torch\nfrom torch import nn\nimport torch.nn.functional as F\n\nfrom lib import layers\n\n\nclass BaseASPPNet(nn.Module):\n\n def __init__(self, nin, ch, dilations=(4, 8, 16)):\n super(BaseASPPNet, self).__init__()\n self.enc1 = layers.Encoder(nin, ch, 3, 2, 1)\n self.enc2 = layers.Encoder(ch, ch * 2, 3, 2, 1)\n self.enc3 = layers.Encoder(ch * 2, ch * 4, 3, 2, 1)\n self.enc4 = layers.Encoder(ch * 4, ch * 8, 3, 2, 1)\n\n self.aspp = layers.ASPPModule(ch * 8, ch * 16, dilations)\n\n self.dec4 = layers.Decoder(ch * (8 + 16), ch * 8, 3, 1, 1)\n self.dec3 = layers.Decoder(ch * (4 + 8), ch * 4, 3, 1, 1)\n self.dec2 = layers.Decoder(ch * (2 + 4), ch * 2, 3, 1, 1)\n self.dec1 = layers.Decoder(ch * (1 + 2), ch, 3, 1, 1)\n\n def __call__(self, x):\n h, e1 = self.enc1(x)\n h, e2 = self.enc2(h)\n h, e3 = self.enc3(h)\n h, e4 = self.enc4(h)\n\n h = self.aspp(h)\n\n h = self.dec4(h, e4)\n h = self.dec3(h, e3)\n h = self.dec2(h, e2)\n h = self.dec1(h, e1)\n\n return h\n\n\nclass CascadedASPPNet(nn.Module):\n\n def __init__(self, n_fft):\n super(CascadedASPPNet, self).__init__()\n self.stg1_low_band_net = BaseASPPNet(2, 16)\n self.stg1_high_band_net = BaseASPPNet(2, 16)\n\n self.stg2_bridge = layers.Conv2DBNActiv(18, 8, 1, 1, 0)\n self.stg2_full_band_net = BaseASPPNet(8, 16)\n\n self.stg3_bridge = layers.Conv2DBNActiv(34, 16, 1, 1, 0)\n self.stg3_full_band_net = BaseASPPNet(16, 32)\n\n self.out = nn.Conv2d(32, 2, 1, bias=False)\n self.aux1_out = nn.Conv2d(16, 2, 1, bias=False)\n self.aux2_out = nn.Conv2d(16, 2, 1, bias=False)\n\n self.max_bin = n_fft // 2\n self.output_bin = n_fft // 2 + 1\n\n self.offset = 128\n\n def forward(self, x):\n mix = x.detach()\n x = x.clone()\n\n x = x[:, :, :self.max_bin]\n\n bandw = x.size()[2] // 2\n aux1 = torch.cat([\n self.stg1_low_band_net(x[:, :, :bandw]),\n self.stg1_high_band_net(x[:, :, bandw:])\n ], dim=2)\n\n h = torch.cat([x, aux1], dim=1)\n aux2 = self.stg2_full_band_net(self.stg2_bridge(h))\n\n h = torch.cat([x, aux1, aux2], dim=1)\n h = self.stg3_full_band_net(self.stg3_bridge(h))\n\n mask = torch.sigmoid(self.out(h))\n mask = F.pad(\n input=mask,\n pad=(0, 0, 0, self.output_bin - mask.size()[2]),\n mode='replicate')\n\n if self.training:\n aux1 = torch.sigmoid(self.aux1_out(aux1))\n aux1 = F.pad(\n input=aux1,\n pad=(0, 0, 0, self.output_bin - aux1.size()[2]),\n mode='replicate')\n aux2 = torch.sigmoid(self.aux2_out(aux2))\n aux2 = F.pad(\n input=aux2,\n pad=(0, 0, 0, self.output_bin - aux2.size()[2]),\n mode='replicate')\n return mask * mix, aux1 * mix, aux2 * mix\n else:\n return mask * mix\n\n def predict(self, x_mag):\n h = self.forward(x_mag)\n\n if self.offset > 0:\n h = h[:, :, :, self.offset:-self.offset]\n assert h.size()[3] > 0\n\n return h\n"
] | [
[
"numpy.abs",
"numpy.pad",
"torch.load",
"numpy.asarray",
"numpy.clip",
"torch.from_numpy",
"numpy.concatenate",
"numpy.ceil",
"torch.no_grad",
"torch.cuda.is_available",
"torch.device",
"numpy.angle",
"numpy.exp"
],
[
"torch.nn.Conv2d",
"torch.cat"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
SaynaEbrahimi/hat | [
"c1333c5f1639a011db336a99eecb75cac8738212",
"c1333c5f1639a011db336a99eecb75cac8738212"
] | [
"src/run.py",
"src/networks/resnet_hat.py"
] | [
"import sys,os,argparse,time\nimport numpy as np\nimport torch\n\nimport utils\n\ntstart=time.time()\n\n# Arguments\nparser=argparse.ArgumentParser(description='xxx')\nparser.add_argument('--seed',type=int,default=0,help='(default=%(default)d)')\nparser.add_argument('--experiment',default='',type=str,required=True,choices=['mnist2','pmnist','cifar','mixture'],help='(default=%(default)s)')\nparser.add_argument('--approach',default='',type=str,required=True,choices=['random','sgd','sgd-frozen','lwf','lfl','ewc','imm-mean','progressive','pathnet',\n 'imm-mode','sgd-restart',\n 'joint','alexnet-hat','resnet-hat','hat-test'],help='(default=%(default)s)')\nparser.add_argument('--output',default='',type=str,required=False,help='(default=%(default)s)')\nparser.add_argument('--nepochs',default=200,type=int,required=False,help='(default=%(default)d)')\nparser.add_argument('--lr',default=0.05,type=float,required=False,help='(default=%(default)f)')\nparser.add_argument('--parameter',type=str,default='',help='(default=%(default)s)')\nargs=parser.parse_args()\nif args.output=='':\n args.output='../res/'+args.experiment+'_'+args.approach+'_'+str(args.seed)+'.txt'\nprint('='*100)\nprint('Arguments =')\nfor arg in vars(args):\n print('\\t'+arg+':',getattr(args,arg))\nprint('='*100)\n\n########################################################################################################################\n\n# Seed\nnp.random.seed(args.seed)\ntorch.manual_seed(args.seed)\nif torch.cuda.is_available(): torch.cuda.manual_seed(args.seed)\nelse: print('[CUDA unavailable]'); sys.exit()\n\n# Args -- Experiment\nif args.experiment=='mnist2':\n from dataloaders import mnist2 as dataloader\nelif args.experiment=='pmnist':\n from dataloaders import pmnist as dataloader\nelif args.experiment=='cifar':\n from dataloaders import cifar as dataloader\nelif args.experiment=='mixture':\n from dataloaders import mixture as dataloader\n\n# Args -- Approach\nif args.approach=='random':\n from approaches import random as approach\nelif args.approach=='sgd':\n from approaches import sgd as approach\nelif args.approach=='sgd-restart':\n from approaches import sgd_restart as approach\nelif args.approach=='sgd-frozen':\n from approaches import sgd_frozen as approach\nelif args.approach=='lwf':\n from approaches import lwf as approach\nelif args.approach=='lfl':\n from approaches import lfl as approach\nelif args.approach=='ewc':\n from approaches import ewc as approach\nelif args.approach=='imm-mean':\n from approaches import imm_mean as approach\nelif args.approach=='imm-mode':\n from approaches import imm_mode as approach\nelif args.approach=='progressive':\n from approaches import progressive as approach\nelif args.approach=='pathnet':\n from approaches import pathnet as approach\nelif args.approach=='hat-test':\n from approaches import hat_test as approach\nelif args.approach=='alexnet-hat' or args.approach=='resnet-hat':\n from approaches import hat as approach\nelif args.approach=='joint':\n from approaches import joint as approach\n\n# Args -- Network\nif args.experiment=='mnist2' or args.experiment=='pmnist':\n if args.approach=='hat' or args.approach=='hat-test':\n from networks import mlp_hat as network\n else:\n from networks import mlp as network\nelse:\n if args.approach=='lfl':\n from networks import alexnet_lfl as network\n elif args.approach=='alexnet-hat':\n from networks import alexnet_hat as network\n elif args.approach=='resnet-hat':\n from networks import resnet_hat as network\n elif args.approach=='progressive':\n from networks import alexnet_progressive as network\n elif args.approach=='pathnet':\n from networks import alexnet_pathnet as network\n elif args.approach=='hat-test':\n from networks import alexnet_hat_test as network\n else:\n from networks import alexnet as network\n\n########################################################################################################################\n\n# Load\nprint('Load data...')\ndata,taskcla,inputsize=dataloader.get(seed=args.seed)\nprint('Input size =',inputsize,'\\nTask info =',taskcla)\n\n# Inits\nprint('Inits...')\nnet=network.Net(inputsize,taskcla).cuda()\nutils.print_model_report(net)\n\nappr=approach.Appr(net,nepochs=args.nepochs,lr=args.lr,args=args)\nprint(appr.criterion)\nutils.print_optimizer_config(appr.optimizer)\nprint('-'*100)\n\n# Loop tasks\nacc=np.zeros((len(taskcla),len(taskcla)),dtype=np.float32)\nlss=np.zeros((len(taskcla),len(taskcla)),dtype=np.float32)\nfor t,ncla in taskcla:\n print('*'*100)\n print('Task {:2d} ({:s})'.format(t,data[t]['name']))\n print('*'*100)\n\n if args.approach == 'joint':\n # Get data. We do not put it to GPU\n if t==0:\n xtrain=data[t]['train']['x']\n ytrain=data[t]['train']['y']\n xvalid=data[t]['valid']['x']\n yvalid=data[t]['valid']['y']\n task_t=t*torch.ones(xtrain.size(0)).int()\n task_v=t*torch.ones(xvalid.size(0)).int()\n task=[task_t,task_v]\n else:\n xtrain=torch.cat((xtrain,data[t]['train']['x']))\n ytrain=torch.cat((ytrain,data[t]['train']['y']))\n xvalid=torch.cat((xvalid,data[t]['valid']['x']))\n yvalid=torch.cat((yvalid,data[t]['valid']['y']))\n task_t=torch.cat((task_t,t*torch.ones(data[t]['train']['y'].size(0)).int()))\n task_v=torch.cat((task_v,t*torch.ones(data[t]['valid']['y'].size(0)).int()))\n task=[task_t,task_v]\n else:\n # Get data\n xtrain=data[t]['train']['x'].cuda()\n ytrain=data[t]['train']['y'].cuda()\n xvalid=data[t]['valid']['x'].cuda()\n yvalid=data[t]['valid']['y'].cuda()\n task=t\n\n # Train\n appr.train(task,xtrain,ytrain,xvalid,yvalid)\n print('-'*100)\n\n # Test\n for u in range(t+1):\n xtest=data[u]['test']['x'].cuda()\n ytest=data[u]['test']['y'].cuda()\n test_loss,test_acc=appr.eval(u,xtest,ytest)\n print('>>> Test on task {:2d} - {:15s}: loss={:.3f}, acc={:5.1f}% <<<'.format(u,data[u]['name'],test_loss,100*test_acc))\n acc[t,u]=test_acc\n lss[t,u]=test_loss\n\n # Save\n print('Save at '+args.output)\n np.savetxt(args.output,acc,'%.4f')\n\n# Done\nprint('*'*100)\nprint('Accuracies =')\nfor i in range(acc.shape[0]):\n print('\\t',end='')\n for j in range(acc.shape[1]):\n print('{:5.1f}% '.format(100*acc[i,j]),end='')\n print()\nprint('*'*100)\nprint('Done!')\n\nprint('[Elapsed time = {:.1f} h]'.format((time.time()-tstart)/(60*60)))\n\nif hasattr(appr, 'logs'):\n if appr.logs is not None:\n #save task names\n from copy import deepcopy\n appr.logs['task_name'] = {}\n appr.logs['test_acc'] = {}\n appr.logs['test_loss'] = {}\n for t,ncla in taskcla:\n appr.logs['task_name'][t] = deepcopy(data[t]['name'])\n appr.logs['test_acc'][t] = deepcopy(acc[t,:])\n appr.logs['test_loss'][t] = deepcopy(lss[t,:])\n #pickle\n import gzip\n import pickle\n with gzip.open(os.path.join(appr.logpath), 'wb') as output:\n pickle.dump(appr.logs, output, pickle.HIGHEST_PROTOCOL)\n\n########################################################################################################################\n",
"import torch\nimport torch.nn as nn\n\n\ndef conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=dilation, groups=groups, bias=False, dilation=dilation)\n\n\ndef conv1x1(in_planes, out_planes, stride=1):\n \"\"\"1x1 convolution\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,\n base_width=64, dilation=1, norm_layer=None, num_tasks=1):\n super(BasicBlock, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n if groups != 1 or base_width != 64:\n raise ValueError('BasicBlock only supports groups=1 and base_width=64')\n if dilation > 1:\n raise NotImplementedError(\"Dilation > 1 not supported in BasicBlock\")\n # Both self.conv1 and self.downsample layers downsample the input when stride != 1\n self.conv1 = conv3x3(inplanes, planes, stride)\n # self.bn1 = norm_layer(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n # self.bn2 = norm_layer(planes)\n self.downsample = downsample\n self.stride = stride\n\n # HAT code\n self.ec1 = nn.Embedding(num_tasks, planes)\n self.ec2 = nn.Embedding(num_tasks, planes)\n\n def mask(self, t, s=1):\n gc1 = torch.sigmoid(s * self.ec1(t))\n gc2 = torch.sigmoid(s * self.ec2(t))\n return [gc1, gc2]\n\n def forward(self, x, masks):\n identity = x\n\n # HAT code\n gc1, gc2 = masks\n\n out = self.conv1(x)\n # out = self.bn1(out)\n out = self.relu(out)\n\n # HAT code\n out = out * gc1.view(1, -1, 1, 1).expand_as(out)\n\n out = self.conv2(out)\n # out = self.bn2(out)\n\n # HAT code\n out = out * gc2.view(1, -1, 1, 1).expand_as(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n\n def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,\n groups=1, width_per_group=64, replace_stride_with_dilation=None,\n norm_layer=None, taskcla=None):\n super(ResNet, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm2d\n self._norm_layer = norm_layer\n\n self.inplanes = 64\n self.dilation = 1\n if replace_stride_with_dilation is None:\n # each element in the tuple indicates if we should replace\n # the 2x2 stride with a dilated convolution instead\n replace_stride_with_dilation = [False, False, False]\n if len(replace_stride_with_dilation) != 3:\n raise ValueError(\"replace_stride_with_dilation should be None \"\n \"or a 3-element tuple, got {}\".format(replace_stride_with_dilation))\n\n # HAT code\n self.num_tasks = len(taskcla)\n\n self.groups = groups\n self.base_width = width_per_group\n self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,\n bias=False)\n # self.bn1 = norm_layer(self.inplanes)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2,\n dilate=replace_stride_with_dilation[0])\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2,\n dilate=replace_stride_with_dilation[1])\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2,\n dilate=replace_stride_with_dilation[2])\n self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\n # self.fc = nn.Linear(512 * block.expansion, num_classes)\n self.last = nn.ModuleList()\n for _, n in taskcla:\n self.last.append(torch.nn.Linear(512 * block.expansion, n))\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n # Zero-initialize the last BN in each residual branch,\n # so that the residual branch starts with zeros, and each residual block behaves like an identity.\n # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677\n if zero_init_residual:\n for m in self.modules():\n # if isinstance(m, Bottleneck):\n # nn.init.constant_(m.bn3.weight, 0)\n if isinstance(m, BasicBlock):\n nn.init.constant_(m.bn2.weight, 0)\n\n # HAT code\n self.ec1 = nn.Embedding(self.num_tasks, 64)\n self.parameter_dict = {n: p for n, p in self.named_parameters()}\n self.pre_mask = None\n\n def _make_layer(self, block, planes, blocks, stride=1, dilate=False):\n norm_layer = self._norm_layer\n downsample = None\n previous_dilation = self.dilation\n if dilate:\n self.dilation *= stride\n stride = 1\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n conv1x1(self.inplanes, planes * block.expansion, stride),\n # norm_layer(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample, self.groups,\n self.base_width, previous_dilation, norm_layer,\n self.num_tasks))\n self.inplanes = planes * block.expansion\n for _ in range(1, blocks):\n layers.append(block(self.inplanes, planes, groups=self.groups,\n base_width=self.base_width, dilation=self.dilation,\n norm_layer=norm_layer, num_tasks=self.num_tasks))\n\n return nn.Sequential(*layers)\n\n def mask(self, t, s=1):\n gc1 = torch.sigmoid(s * self.ec1(t))\n layer_masks = sum([\n self.layer1[0].mask(t, s),\n self.layer1[1].mask(t, s),\n self.layer2[0].mask(t, s),\n self.layer2[1].mask(t, s),\n self.layer3[0].mask(t, s),\n self.layer3[1].mask(t, s),\n self.layer4[0].mask(t, s),\n self.layer4[1].mask(t, s),\n ], [])\n return [gc1] + layer_masks\n\n def _forward_impl(self, t, x, s=1):\n # See note [TorchScript super()]\n\n # HAT code\n masks = self.mask(t, s)\n gc1 = masks[0]\n\n x = self.conv1(x)\n # x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n # HAT code\n x = x * gc1.view(1, -1, 1, 1).expand_as(x)\n\n x = self.layer1[0](x, masks[1:3])\n x = self.layer1[1](x, masks[3:5])\n x = self.layer2[0](x, masks[5:7])\n x = self.layer2[1](x, masks[7:9])\n x = self.layer3[0](x, masks[9:11])\n x = self.layer3[1](x, masks[11:13])\n x = self.layer4[0](x, masks[13:15])\n x = self.layer4[1](x, masks[15:17])\n\n x = self.avgpool(x)\n x = torch.flatten(x, 1)\n y = []\n for i in range(self.num_tasks):\n y.append(self.last[i](x))\n\n return y, masks\n\n def forward(self, t, x, s=1):\n return self._forward_impl(t, x, s)\n\n def get_view_for(self, n, masks):\n gc1 = masks[0]\n if n == 'conv1.weight':\n self.pre_mask = gc1\n return gc1.data.view(-1, 1, 1, 1).expand_as(self.parameter_dict[n])\n elif n == 'conv1.bias':\n return gc1.data.view(-1)\n\n if n.startswith('layer') and 'conv' in n:\n layer = int(n[5]) - 1\n seq = int(n[7])\n conv = int(n[13]) - 1\n # print(n, layer, seq, conv)\n gc = masks[layer * 4 + seq * 2 + conv + 1]\n if 'weight' in n:\n post = gc.data.view(-1, 1, 1, 1).expand_as(self.parameter_dict[n])\n pre = self.pre_mask.data.view(1, -1, 1, 1).expand_as(self.parameter_dict[n])\n self.pre_mask = gc\n return torch.min(post, pre)\n else:\n return gc.data.view(-1)\n\n return None\n\n\ndef Net(inputsize, taskcla):\n return ResNet(BasicBlock, [2, 2, 2, 2], taskcla=taskcla)\n"
] | [
[
"torch.cuda.manual_seed",
"numpy.random.seed",
"torch.cat",
"torch.manual_seed",
"torch.cuda.is_available",
"numpy.savetxt"
],
[
"torch.nn.Sequential",
"torch.nn.init.constant_",
"torch.nn.ModuleList",
"torch.nn.Conv2d",
"torch.min",
"torch.nn.Embedding",
"torch.nn.MaxPool2d",
"torch.nn.Linear",
"torch.nn.AdaptiveAvgPool2d",
"torch.flatten",
"torch.nn.ReLU",
"torch.nn.init.kaiming_normal_"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
ishani-chakraborty/models | [
"367486482c5fe6fc896868edf9bbde7519deb52d",
"367486482c5fe6fc896868edf9bbde7519deb52d"
] | [
"official/nlp/tasks/question_answering.py",
"official/nlp/tasks/question_answering_test.py"
] | [
"# Lint as: python3\n# 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\"\"\"Question answering task.\"\"\"\nimport collections\nimport json\nimport os\n\nfrom absl import logging\nimport dataclasses\nimport orbit\nimport tensorflow as tf\nimport tensorflow_hub as hub\n\nfrom official.core import base_task\nfrom official.core import task_factory\nfrom official.modeling.hyperparams import base_config\nfrom official.modeling.hyperparams import config_definitions as cfg\nfrom official.nlp.bert import squad_evaluate_v1_1\nfrom official.nlp.bert import squad_evaluate_v2_0\nfrom official.nlp.bert import tokenization\nfrom official.nlp.configs import encoders\nfrom official.nlp.data import data_loader_factory\nfrom official.nlp.data import squad_lib as squad_lib_wp\nfrom official.nlp.data import squad_lib_sp\nfrom official.nlp.modeling import models\nfrom official.nlp.tasks import utils\n\n\[email protected]\nclass ModelConfig(base_config.Config):\n \"\"\"A base span labeler configuration.\"\"\"\n encoder: encoders.TransformerEncoderConfig = (\n encoders.TransformerEncoderConfig())\n\n\[email protected]\nclass QuestionAnsweringConfig(cfg.TaskConfig):\n \"\"\"The model config.\"\"\"\n # At most one of `init_checkpoint` and `hub_module_url` can be specified.\n init_checkpoint: str = ''\n hub_module_url: str = ''\n n_best_size: int = 20\n max_answer_length: int = 30\n null_score_diff_threshold: float = 0.0\n model: ModelConfig = ModelConfig()\n train_data: cfg.DataConfig = cfg.DataConfig()\n validation_data: cfg.DataConfig = cfg.DataConfig()\n\n\n@task_factory.register_task_cls(QuestionAnsweringConfig)\nclass QuestionAnsweringTask(base_task.Task):\n \"\"\"Task object for question answering.\"\"\"\n\n def __init__(self, params=cfg.TaskConfig, logging_dir=None):\n super(QuestionAnsweringTask, self).__init__(params, logging_dir)\n if params.hub_module_url and params.init_checkpoint:\n raise ValueError('At most one of `hub_module_url` and '\n '`init_checkpoint` can be specified.')\n if params.hub_module_url:\n self._hub_module = hub.load(params.hub_module_url)\n else:\n self._hub_module = None\n\n if params.validation_data.tokenization == 'WordPiece':\n self.squad_lib = squad_lib_wp\n elif params.validation_data.tokenization == 'SentencePiece':\n self.squad_lib = squad_lib_sp\n else:\n raise ValueError('Unsupported tokenization method: {}'.format(\n params.validation_data.tokenization))\n\n if params.validation_data.input_path:\n self._tf_record_input_path, self._eval_examples, self._eval_features = (\n self._preprocess_eval_data(params.validation_data))\n\n def set_preprocessed_eval_input_path(self, eval_input_path):\n \"\"\"Sets the path to the preprocessed eval data.\"\"\"\n self._tf_record_input_path = eval_input_path\n\n def build_model(self):\n if self._hub_module:\n encoder_network = utils.get_encoder_from_hub(self._hub_module)\n else:\n encoder_network = encoders.instantiate_encoder_from_cfg(\n self.task_config.model.encoder)\n # Currently, we only supports bert-style question answering finetuning.\n return models.BertSpanLabeler(\n network=encoder_network,\n initializer=tf.keras.initializers.TruncatedNormal(\n stddev=self.task_config.model.encoder.initializer_range))\n\n def build_losses(self, labels, model_outputs, aux_losses=None) -> tf.Tensor:\n start_positions = labels['start_positions']\n end_positions = labels['end_positions']\n start_logits, end_logits = model_outputs\n\n start_loss = tf.keras.losses.sparse_categorical_crossentropy(\n start_positions,\n tf.cast(start_logits, dtype=tf.float32),\n from_logits=True)\n end_loss = tf.keras.losses.sparse_categorical_crossentropy(\n end_positions,\n tf.cast(end_logits, dtype=tf.float32),\n from_logits=True)\n\n loss = (tf.reduce_mean(start_loss) + tf.reduce_mean(end_loss)) / 2\n return loss\n\n def _preprocess_eval_data(self, params):\n eval_examples = self.squad_lib.read_squad_examples(\n input_file=params.input_path,\n is_training=False,\n version_2_with_negative=params.version_2_with_negative)\n\n temp_file_path = params.input_preprocessed_data_path or self.logging_dir\n if not temp_file_path:\n raise ValueError('You must specify a temporary directory, either in '\n 'params.input_preprocessed_data_path or logging_dir to '\n 'store intermediate evaluation TFRecord data.')\n eval_writer = self.squad_lib.FeatureWriter(\n filename=os.path.join(temp_file_path, 'eval.tf_record'),\n is_training=False)\n eval_features = []\n\n def _append_feature(feature, is_padding):\n if not is_padding:\n eval_features.append(feature)\n eval_writer.process_feature(feature)\n\n kwargs = dict(\n examples=eval_examples,\n tokenizer=tokenization.FullTokenizer(\n vocab_file=params.vocab_file,\n do_lower_case=params.do_lower_case),\n max_seq_length=params.seq_length,\n doc_stride=params.doc_stride,\n max_query_length=params.query_length,\n is_training=False,\n output_fn=_append_feature,\n batch_size=params.global_batch_size)\n if params.tokenization == 'SentencePiece':\n # squad_lib_sp requires one more argument 'do_lower_case'.\n kwargs['do_lower_case'] = params.do_lower_case\n\n eval_dataset_size = self.squad_lib.convert_examples_to_features(**kwargs)\n eval_writer.close()\n\n logging.info('***** Evaluation input stats *****')\n logging.info(' Num orig examples = %d', len(eval_examples))\n logging.info(' Num split examples = %d', len(eval_features))\n logging.info(' Batch size = %d', params.global_batch_size)\n logging.info(' Dataset size = %d', eval_dataset_size)\n\n return eval_writer.filename, eval_examples, eval_features\n\n def build_inputs(self, params, input_context=None):\n \"\"\"Returns tf.data.Dataset for sentence_prediction task.\"\"\"\n if params.input_path == 'dummy':\n # Dummy training data for unit test.\n def dummy_data(_):\n dummy_ids = tf.zeros((1, params.seq_length), dtype=tf.int32)\n x = dict(\n input_word_ids=dummy_ids,\n input_mask=dummy_ids,\n input_type_ids=dummy_ids)\n y = dict(\n start_positions=tf.constant(0, dtype=tf.int32),\n end_positions=tf.constant(1, dtype=tf.int32))\n return (x, y)\n\n dataset = tf.data.Dataset.range(1)\n dataset = dataset.repeat()\n dataset = dataset.map(\n dummy_data, num_parallel_calls=tf.data.experimental.AUTOTUNE)\n return dataset\n\n if params.is_training:\n dataloader_params = params\n else:\n input_path = self._tf_record_input_path\n dataloader_params = params.replace(input_path=input_path)\n\n return data_loader_factory.get_data_loader(\n dataloader_params).load(input_context)\n\n def build_metrics(self, training=None):\n del training\n # TODO(lehou): a list of metrics doesn't work the same as in compile/fit.\n metrics = [\n tf.keras.metrics.SparseCategoricalAccuracy(\n name='start_position_accuracy'),\n tf.keras.metrics.SparseCategoricalAccuracy(\n name='end_position_accuracy'),\n ]\n return metrics\n\n def process_metrics(self, metrics, labels, model_outputs):\n metrics = dict([(metric.name, metric) for metric in metrics])\n start_logits, end_logits = model_outputs\n metrics['start_position_accuracy'].update_state(\n labels['start_positions'], start_logits)\n metrics['end_position_accuracy'].update_state(\n labels['end_positions'], end_logits)\n\n def process_compiled_metrics(self, compiled_metrics, labels, model_outputs):\n start_logits, end_logits = model_outputs\n compiled_metrics.update_state(\n y_true=labels, # labels has keys 'start_positions' and 'end_positions'.\n y_pred={'start_positions': start_logits, 'end_positions': end_logits})\n\n def validation_step(self, inputs, model: tf.keras.Model, metrics=None):\n features, _ = inputs\n unique_ids = features.pop('unique_ids')\n model_outputs = self.inference_step(features, model)\n start_logits, end_logits = model_outputs\n logs = {\n self.loss: 0.0, # TODO(lehou): compute the real validation loss.\n 'unique_ids': unique_ids,\n 'start_logits': start_logits,\n 'end_logits': end_logits,\n }\n return logs\n\n raw_aggregated_result = collections.namedtuple(\n 'RawResult', ['unique_id', 'start_logits', 'end_logits'])\n\n def aggregate_logs(self, state=None, step_outputs=None):\n assert step_outputs is not None, 'Got no logs from self.validation_step.'\n if state is None:\n state = []\n\n for unique_ids, start_logits, end_logits in zip(\n step_outputs['unique_ids'],\n step_outputs['start_logits'],\n step_outputs['end_logits']):\n u_ids, s_logits, e_logits = (\n unique_ids.numpy(), start_logits.numpy(), end_logits.numpy())\n for values in zip(u_ids, s_logits, e_logits):\n state.append(self.raw_aggregated_result(\n unique_id=values[0],\n start_logits=values[1].tolist(),\n end_logits=values[2].tolist()))\n return state\n\n def reduce_aggregated_logs(self, aggregated_logs):\n all_predictions, _, scores_diff = (\n self.squad_lib.postprocess_output(\n self._eval_examples,\n self._eval_features,\n aggregated_logs,\n self.task_config.n_best_size,\n self.task_config.max_answer_length,\n self.task_config.validation_data.do_lower_case,\n version_2_with_negative=(\n self.task_config.validation_data.version_2_with_negative),\n null_score_diff_threshold=(\n self.task_config.null_score_diff_threshold),\n verbose=False))\n\n with tf.io.gfile.GFile(\n self.task_config.validation_data.input_path, 'r') as reader:\n dataset_json = json.load(reader)\n pred_dataset = dataset_json['data']\n if self.task_config.validation_data.version_2_with_negative:\n eval_metrics = squad_evaluate_v2_0.evaluate(\n pred_dataset, all_predictions, scores_diff)\n # Filter out useless metrics, such as start_position_accuracy that\n # we did not actually compute.\n eval_metrics = {\n 'exact_match': eval_metrics['final_exact'],\n 'exact_match_threshold': eval_metrics['final_exact_thresh'],\n 'final_f1': eval_metrics['final_f1'] / 100.0, # scale back to [0, 1].\n 'f1_threshold': eval_metrics['final_f1_thresh'],\n 'has_answer_exact_match': eval_metrics['HasAns_exact'],\n 'has_answer_f1': eval_metrics['HasAns_f1']}\n else:\n eval_metrics = squad_evaluate_v1_1.evaluate(pred_dataset, all_predictions)\n # Filter out useless metrics, such as start_position_accuracy that\n # we did not actually compute.\n eval_metrics = {'exact_match': eval_metrics['exact_match'],\n 'final_f1': eval_metrics['final_f1']}\n return eval_metrics\n\n\ndef predict(task: QuestionAnsweringTask, params: cfg.DataConfig,\n model: tf.keras.Model):\n \"\"\"Predicts on the input data.\n\n Args:\n task: A `QuestionAnsweringTask` object.\n params: A `cfg.DataConfig` object.\n model: A keras.Model.\n\n Returns:\n A tuple of `all_predictions`, `all_nbest` and `scores_diff`, which\n are dict and can be written to json files including prediction json file,\n nbest json file and null_odds json file.\n \"\"\"\n tf_record_input_path, eval_examples, eval_features = (\n task._preprocess_eval_data(params)) # pylint: disable=protected-access\n\n # `tf_record_input_path` will overwrite `params.input_path`,\n # when `task.buid_inputs()` is called.\n task.set_preprocessed_eval_input_path(tf_record_input_path)\n\n def predict_step(inputs):\n \"\"\"Replicated prediction calculation.\"\"\"\n return task.validation_step(inputs, model)\n\n dataset = orbit.utils.make_distributed_dataset(tf.distribute.get_strategy(),\n task.build_inputs, params)\n aggregated_outputs = utils.predict(predict_step, task.aggregate_logs, dataset)\n\n all_predictions, all_nbest, scores_diff = (\n task.squad_lib.postprocess_output(\n eval_examples,\n eval_features,\n aggregated_outputs,\n task.task_config.n_best_size,\n task.task_config.max_answer_length,\n task.task_config.validation_data.do_lower_case,\n version_2_with_negative=(params.version_2_with_negative),\n null_score_diff_threshold=task.task_config.null_score_diff_threshold,\n verbose=False))\n return all_predictions, all_nbest, scores_diff\n",
"# Lint as: python3\n# 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 official.nlp.tasks.question_answering.\"\"\"\nimport itertools\nimport json\nimport os\nfrom absl.testing import parameterized\nimport tensorflow as tf\n\nfrom official.nlp.bert import configs\nfrom official.nlp.bert import export_tfhub\nfrom official.nlp.configs import bert\nfrom official.nlp.configs import encoders\nfrom official.nlp.data import question_answering_dataloader\nfrom official.nlp.tasks import question_answering\n\n\nclass QuestionAnsweringTaskTest(tf.test.TestCase, parameterized.TestCase):\n\n def setUp(self):\n super(QuestionAnsweringTaskTest, self).setUp()\n self._encoder_config = encoders.TransformerEncoderConfig(\n vocab_size=30522, num_layers=1)\n self._train_data_config = question_answering_dataloader.QADataConfig(\n input_path=\"dummy\",\n seq_length=128,\n global_batch_size=1)\n\n val_data = {\"version\": \"1.1\",\n \"data\": [{\"paragraphs\": [\n {\"context\": \"Sky is blue.\",\n \"qas\": [{\"question\": \"What is blue?\", \"id\": \"1234\",\n \"answers\": [{\"text\": \"Sky\", \"answer_start\": 0},\n {\"text\": \"Sky\", \"answer_start\": 0},\n {\"text\": \"Sky\", \"answer_start\": 0}]\n }]}]}]}\n self._val_input_path = os.path.join(self.get_temp_dir(), \"val_data.json\")\n with tf.io.gfile.GFile(self._val_input_path, \"w\") as writer:\n writer.write(json.dumps(val_data, indent=4) + \"\\n\")\n\n self._test_vocab = os.path.join(self.get_temp_dir(), \"vocab.txt\")\n with tf.io.gfile.GFile(self._test_vocab, \"w\") as writer:\n writer.write(\"[PAD]\\n[UNK]\\n[CLS]\\n[SEP]\\n[MASK]\\nsky\\nis\\nblue\\n\")\n\n def _get_validation_data_config(self, version_2_with_negative=False):\n return question_answering_dataloader.QADataConfig(\n is_training=False,\n input_path=self._val_input_path,\n input_preprocessed_data_path=self.get_temp_dir(),\n seq_length=128,\n global_batch_size=1,\n version_2_with_negative=version_2_with_negative,\n vocab_file=self._test_vocab,\n tokenization=\"WordPiece\",\n do_lower_case=True)\n\n def _run_task(self, config):\n task = question_answering.QuestionAnsweringTask(config)\n model = task.build_model()\n metrics = task.build_metrics()\n task.initialize(model)\n\n train_dataset = task.build_inputs(config.train_data)\n train_iterator = iter(train_dataset)\n optimizer = tf.keras.optimizers.SGD(lr=0.1)\n task.train_step(next(train_iterator), model, optimizer, metrics=metrics)\n\n val_dataset = task.build_inputs(config.validation_data)\n val_iterator = iter(val_dataset)\n logs = task.validation_step(next(val_iterator), model, metrics=metrics)\n # Mock that `logs` is from one replica.\n logs = {x: (logs[x],) for x in logs}\n logs = task.aggregate_logs(step_outputs=logs)\n metrics = task.reduce_aggregated_logs(logs)\n self.assertIn(\"final_f1\", metrics)\n\n @parameterized.parameters(itertools.product(\n (False, True),\n (\"WordPiece\", \"SentencePiece\"),\n ))\n def test_task(self, version_2_with_negative, tokenization):\n # Saves a checkpoint.\n pretrain_cfg = bert.BertPretrainerConfig(\n encoder=self._encoder_config,\n cls_heads=[\n bert.ClsHeadConfig(\n inner_dim=10, num_classes=3, name=\"next_sentence\")\n ])\n pretrain_model = bert.instantiate_pretrainer_from_cfg(pretrain_cfg)\n ckpt = tf.train.Checkpoint(\n model=pretrain_model, **pretrain_model.checkpoint_items)\n saved_path = ckpt.save(self.get_temp_dir())\n\n config = question_answering.QuestionAnsweringConfig(\n init_checkpoint=saved_path,\n model=question_answering.ModelConfig(encoder=self._encoder_config),\n train_data=self._train_data_config,\n validation_data=self._get_validation_data_config(\n version_2_with_negative))\n self._run_task(config)\n\n def test_task_with_fit(self):\n config = question_answering.QuestionAnsweringConfig(\n model=question_answering.ModelConfig(encoder=self._encoder_config),\n train_data=self._train_data_config,\n validation_data=self._get_validation_data_config())\n task = question_answering.QuestionAnsweringTask(config)\n model = task.build_model()\n model = task.compile_model(\n model,\n optimizer=tf.keras.optimizers.SGD(lr=0.1),\n train_step=task.train_step,\n metrics=[tf.keras.metrics.SparseCategoricalAccuracy(name=\"accuracy\")])\n dataset = task.build_inputs(config.train_data)\n logs = model.fit(dataset, epochs=1, steps_per_epoch=2)\n self.assertIn(\"loss\", logs.history)\n self.assertIn(\"start_positions_accuracy\", logs.history)\n self.assertIn(\"end_positions_accuracy\", logs.history)\n\n def _export_bert_tfhub(self):\n bert_config = configs.BertConfig(\n vocab_size=30522,\n hidden_size=16,\n intermediate_size=32,\n max_position_embeddings=128,\n num_attention_heads=2,\n num_hidden_layers=1)\n _, encoder = export_tfhub.create_bert_model(bert_config)\n model_checkpoint_dir = os.path.join(self.get_temp_dir(), \"checkpoint\")\n checkpoint = tf.train.Checkpoint(model=encoder)\n checkpoint.save(os.path.join(model_checkpoint_dir, \"test\"))\n model_checkpoint_path = tf.train.latest_checkpoint(model_checkpoint_dir)\n\n vocab_file = os.path.join(self.get_temp_dir(), \"uncased_vocab.txt\")\n with tf.io.gfile.GFile(vocab_file, \"w\") as f:\n f.write(\"dummy content\")\n\n hub_destination = os.path.join(self.get_temp_dir(), \"hub\")\n export_tfhub.export_bert_tfhub(bert_config, model_checkpoint_path,\n hub_destination, vocab_file)\n return hub_destination\n\n def test_task_with_hub(self):\n hub_module_url = self._export_bert_tfhub()\n config = question_answering.QuestionAnsweringConfig(\n hub_module_url=hub_module_url,\n model=question_answering.ModelConfig(encoder=self._encoder_config),\n train_data=self._train_data_config,\n validation_data=self._get_validation_data_config())\n self._run_task(config)\n\n @parameterized.named_parameters((\"squad1\", False), (\"squad2\", True))\n def test_predict(self, version_2_with_negative):\n validation_data = self._get_validation_data_config(\n version_2_with_negative=version_2_with_negative)\n\n config = question_answering.QuestionAnsweringConfig(\n model=question_answering.ModelConfig(encoder=self._encoder_config),\n train_data=self._train_data_config,\n validation_data=validation_data)\n task = question_answering.QuestionAnsweringTask(config)\n model = task.build_model()\n\n all_predictions, all_nbest, scores_diff = question_answering.predict(\n task, validation_data, model)\n self.assertLen(all_predictions, 1)\n self.assertLen(all_nbest, 1)\n if version_2_with_negative:\n self.assertLen(scores_diff, 1)\n else:\n self.assertEmpty(scores_diff)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n"
] | [
[
"tensorflow.constant",
"tensorflow.keras.metrics.SparseCategoricalAccuracy",
"tensorflow.reduce_mean",
"tensorflow.zeros",
"tensorflow.io.gfile.GFile",
"tensorflow.cast",
"tensorflow.data.Dataset.range",
"tensorflow.keras.initializers.TruncatedNormal",
"tensorflow.distribute.get_strategy"
],
[
"tensorflow.train.latest_checkpoint",
"tensorflow.train.Checkpoint",
"tensorflow.io.gfile.GFile",
"tensorflow.test.main",
"tensorflow.keras.metrics.SparseCategoricalAccuracy",
"tensorflow.keras.optimizers.SGD"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.6",
"2.4",
"2.3",
"2.5",
"2.2"
]
}
] |
t2wain/machine-learning | [
"4b5e1a24fab7c4ab42f646f7785191ff3d3283ba",
"4b5e1a24fab7c4ab42f646f7785191ff3d3283ba"
] | [
"tnmlearn/other/convenience.py",
"tnmlearn/datasets/standard_datasets.py"
] | [
"# -*- coding: utf-8 -*-\n\n# author: Adrian Rosebrock\n# website: http://www.pyimagesearch.com\n\n# import the necessary packages\nimport numpy as np\nimport cv2\nimport sys\n\n# import any special Python 2.7 packages\nif sys.version_info.major == 2:\n from urllib import urlopen\n\n# import any special Python 3 packages\nelif sys.version_info.major == 3:\n from urllib.request import urlopen\n\ndef translate(image, x, y):\n # define the translation matrix and perform the translation\n M = np.float32([[1, 0, x], [0, 1, y]])\n shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))\n\n # return the translated image\n return shifted\n\ndef rotate(image, angle, center=None, scale=1.0):\n # grab the dimensions of the image\n (h, w) = image.shape[:2]\n\n # if the center is None, initialize it as the center of\n # the image\n if center is None:\n center = (w // 2, h // 2)\n\n # perform the rotation\n M = cv2.getRotationMatrix2D(center, angle, scale)\n rotated = cv2.warpAffine(image, M, (w, h))\n\n # return the rotated image\n return rotated\n\ndef rotate_bound(image, angle):\n # grab the dimensions of the image and then determine the\n # center\n (h, w) = image.shape[:2]\n (cX, cY) = (w / 2, h / 2)\n\n # grab the rotation matrix (applying the negative of the\n # angle to rotate clockwise), then grab the sine and cosine\n # (i.e., the rotation components of the matrix)\n M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)\n cos = np.abs(M[0, 0])\n sin = np.abs(M[0, 1])\n\n # compute the new bounding dimensions of the image\n nW = int((h * sin) + (w * cos))\n nH = int((h * cos) + (w * sin))\n\n # adjust the rotation matrix to take into account translation\n M[0, 2] += (nW / 2) - cX\n M[1, 2] += (nH / 2) - cY\n\n # perform the actual rotation and return the image\n return cv2.warpAffine(image, M, (nW, nH))\n\ndef resize(image, width=None, height=None, inter=cv2.INTER_AREA):\n # initialize the dimensions of the image to be resized and\n # grab the image size\n dim = None\n (h, w) = image.shape[:2]\n\n # if both the width and height are None, then return the\n # original image\n if width is None and height is None:\n return image\n\n # check to see if the width is None\n if width is None:\n # calculate the ratio of the height and construct the\n # dimensions\n r = height / float(h)\n dim = (int(w * r), height)\n\n # otherwise, the height is None\n else:\n # calculate the ratio of the width and construct the\n # dimensions\n r = width / float(w)\n dim = (width, int(h * r))\n\n # resize the image\n resized = cv2.resize(image, dim, interpolation=inter)\n\n # return the resized image\n return resized\n\ndef skeletonize(image, size, structuring=cv2.MORPH_RECT):\n # determine the area (i.e. total number of pixels in the image),\n # initialize the output skeletonized image, and construct the\n # morphological structuring element\n area = image.shape[0] * image.shape[1]\n skeleton = np.zeros(image.shape, dtype=\"uint8\")\n elem = cv2.getStructuringElement(structuring, size)\n\n # keep looping until the erosions remove all pixels from the\n # image\n while True:\n # erode and dilate the image using the structuring element\n eroded = cv2.erode(image, elem)\n temp = cv2.dilate(eroded, elem)\n\n # subtract the temporary image from the original, eroded\n # image, then take the bitwise 'or' between the skeleton\n # and the temporary image\n temp = cv2.subtract(image, temp)\n skeleton = cv2.bitwise_or(skeleton, temp)\n image = eroded.copy()\n\n # if there are no more 'white' pixels in the image, then\n # break from the loop\n if area == area - cv2.countNonZero(image):\n break\n\n # return the skeletonized image\n return skeleton\n\ndef opencv2matplotlib(image):\n # OpenCV represents images in BGR order; however, Matplotlib\n # expects the image in RGB order, so simply convert from BGR\n # to RGB and return\n return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\ndef url_to_image(url, readFlag=cv2.IMREAD_COLOR):\n # download the image, convert it to a NumPy array, and then read\n # it into OpenCV format\n resp = urlopen(url)\n image = np.asarray(bytearray(resp.read()), dtype=\"uint8\")\n image = cv2.imdecode(image, readFlag)\n\n # return the image\n return image\n\ndef auto_canny(image, sigma=0.33):\n # compute the median of the single channel pixel intensities\n v = np.median(image)\n\n # apply automatic Canny edge detection using the computed median\n lower = int(max(0, (1.0 - sigma) * v))\n upper = int(min(255, (1.0 + sigma) * v))\n edged = cv2.Canny(image, lower, upper)\n\n # return the edged image\n return edged\n\ndef grab_contours(cnts):\n # if the length the contours tuple returned by cv2.findContours\n # is '2' then we are using either OpenCV v2.4, v4-beta, or\n # v4-official\n if len(cnts) == 2:\n cnts = cnts[0]\n\n # if the length of the contours tuple is '3' then we are using\n # either OpenCV v3, v4-pre, or v4-alpha\n elif len(cnts) == 3:\n cnts = cnts[1]\n\n # otherwise OpenCV has changed their cv2.findContours return\n # signature yet again and I have no idea WTH is going on\n else:\n raise Exception((\"Contours tuple must have length 2 or 3, \"\n \"otherwise OpenCV changed their cv2.findContours return \"\n \"signature yet again. Refer to OpenCV's documentation \"\n \"in that case\"))\n\n # return the actual contours array\n return cnts\n\ndef is_cv2(or_better=False):\n # grab the OpenCV major version number\n major = get_opencv_major_version()\n\n # check to see if we are using *at least* OpenCV 2\n if or_better:\n return major >= 2\n\n # otherwise we want to check for *strictly* OpenCV 2\n return major == 2\n\ndef is_cv3(or_better=False):\n # grab the OpenCV major version number\n major = get_opencv_major_version()\n\n # check to see if we are using *at least* OpenCV 3\n if or_better:\n return major >= 3\n\n # otherwise we want to check for *strictly* OpenCV 3\n return major == 3\n\ndef is_cv4(or_better=False):\n # grab the OpenCV major version number\n major = get_opencv_major_version()\n\n # check to see if we are using *at least* OpenCV 4\n if or_better:\n return major >= 4\n\n # otherwise we want to check for *strictly* OpenCV 4\n return major == 4\n\ndef get_opencv_major_version(lib=None):\n # if the supplied library is None, import OpenCV\n if lib is None:\n import cv2 as lib\n\n # return the major version number\n return int(lib.__version__.split(\".\")[0])\n\ndef check_opencv_version(major, lib=None):\n # this function may be removed in a future release as we now\n # use the get_opencv_major_function to obtain the current OpenCV\n # version and then perform the actual version check *within* the\n # respective function\n import warnings\n message = \"\"\"\n The check_opencv_version function is deprecated and may be\n removed in a future release. Use at your own risk.\n \"\"\"\n warnings.warn(message, DeprecationWarning, stacklevel=2)\n \n # if the supplied library is None, import OpenCV\n if lib is None:\n import cv2 as lib\n \n # return whether or not the current OpenCV version matches the\n # major version number\n return lib.__version__.startswith(major)\n\ndef build_montages(image_list, image_shape, montage_shape):\n \"\"\"\n ---------------------------------------------------------------------------------------------\n author: Kyle Hounslow\n ---------------------------------------------------------------------------------------------\n Converts a list of single images into a list of 'montage' images of specified rows and columns.\n A new montage image is started once rows and columns of montage image is filled.\n Empty space of incomplete montage images are filled with black pixels\n ---------------------------------------------------------------------------------------------\n :param image_list: python list of input images\n :param image_shape: tuple, size each image will be resized to for display (width, height)\n :param montage_shape: tuple, shape of image montage (width, height)\n :return: list of montage images in numpy array format\n ---------------------------------------------------------------------------------------------\n\n example usage:\n\n # load single image\n img = cv2.imread('lena.jpg')\n # duplicate image 25 times\n num_imgs = 25\n img_list = []\n for i in xrange(num_imgs):\n img_list.append(img)\n # convert image list into a montage of 256x256 images tiled in a 5x5 montage\n montages = make_montages_of_images(img_list, (256, 256), (5, 5))\n # iterate through montages and display\n for montage in montages:\n cv2.imshow('montage image', montage)\n cv2.waitKey(0)\n\n ----------------------------------------------------------------------------------------------\n \"\"\"\n if len(image_shape) != 2:\n raise Exception('image shape must be list or tuple of length 2 (rows, cols)')\n if len(montage_shape) != 2:\n raise Exception('montage shape must be list or tuple of length 2 (rows, cols)')\n image_montages = []\n # start with black canvas to draw images onto\n montage_image = np.zeros(shape=(image_shape[1] * (montage_shape[1]), image_shape[0] * montage_shape[0], 3),\n dtype=np.uint8)\n cursor_pos = [0, 0]\n start_new_img = False\n for img in image_list:\n if type(img).__module__ != np.__name__:\n raise Exception('input of type {} is not a valid numpy array'.format(type(img)))\n start_new_img = False\n img = cv2.resize(img, image_shape)\n # draw image to black canvas\n montage_image[cursor_pos[1]:cursor_pos[1] + image_shape[1], cursor_pos[0]:cursor_pos[0] + image_shape[0]] = img\n cursor_pos[0] += image_shape[0] # increment cursor x position\n if cursor_pos[0] >= montage_shape[0] * image_shape[0]:\n cursor_pos[1] += image_shape[1] # increment cursor y position\n cursor_pos[0] = 0\n if cursor_pos[1] >= montage_shape[1] * image_shape[1]:\n cursor_pos = [0, 0]\n image_montages.append(montage_image)\n # reset black canvas\n montage_image = np.zeros(shape=(image_shape[1] * (montage_shape[1]), image_shape[0] * montage_shape[0], 3),\n dtype=np.uint8)\n start_new_img = True\n if start_new_img is False:\n image_montages.append(montage_image) # add unfinished montage\n return image_montages\n\n\ndef adjust_brightness_contrast(image, brightness=0., contrast=0.):\n \"\"\"\n Adjust the brightness and/or contrast of an image\n\n :param image: OpenCV BGR image\n :param contrast: Float, contrast adjustment with 0 meaning no change\n :param brightness: Float, brightness adjustment with 0 meaning no change\n \"\"\"\n beta = 0\n # See the OpenCV docs for more info on the `beta` parameter to addWeighted\n # https://docs.opencv.org/3.4.2/d2/de8/group__core__array.html#gafafb2513349db3bcff51f54ee5592a19\n return cv2.addWeighted(image,\n 1 + float(contrast) / 100.,\n image,\n beta,\n float(brightness))",
"# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import datasets\nfrom keras.datasets import cifar10\nfrom keras import backend as K\nfrom tnmlearn.other import paths\nfrom tnmlearn.datasets import SimpleDatasetLoader\n\n\n# %%\n\ndef load_cifar10(for_dnn=False):\n # load the training and testing data, then scale it into the\n # range [0, 1]\n print(\"[INFO] loading CIFAR-10 data...\")\n ((trainX, trainY), (testX, testY)) = cifar10.load_data()\n \n trainX = trainX.astype(\"float\") / 255.0\n testX = testX.astype(\"float\") / 255.0\n \n if for_dnn:\n trainX = trainX.reshape((trainX.shape[0], 3072))\n testX = testX.reshape((testX.shape[0], 3072))\n \n # convert the labels from integers to vectors\n lb = LabelBinarizer()\n trainY = lb.fit_transform(trainY)\n testY = lb.transform(testY)\n \n # initialize the label names for the CIFAR-10 dataset\n classNames = [\"airplane\", \"automobile\", \"bird\", \"cat\", \"deer\",\n \"dog\", \"frog\", \"horse\", \"ship\", \"truck\"]\n \n return ((trainX, trainY), (testX, testY), classNames)\n \n \ndef load_mnist(for_cnn=False):\n # grab the MNIST dataset (if this is your first time running this\n # script, the download may take a minute -- the 55MB MNIST dataset\n # will be downloaded)\n print(\"[INFO] loading MNIST (full) dataset...\")\n dataset = datasets.fetch_mldata(\"MNIST Original\")\n \n # scale the raw pixel intensities to the range [0, 1.0], then\n # construct the training and testing splits\n data = dataset.data.astype(\"float\") / 255.0\n if for_cnn:\n data = reshape_for_cnn(data, 28, 28, 1)\n (trainX, testX, trainY, testY) = train_test_split(data,\n dataset.target, test_size=0.25)\n \n # convert the labels from integers to vectors\n lb = LabelBinarizer()\n trainY = lb.fit_transform(trainY)\n testY = lb.transform(testY)\n classNames = [str(x) for x in lb.classes_] \n \n return ((trainX, trainY), (testX, testY), classNames)\n \n \ndef reshape_for_cnn(data_orig, height, width, channel):\n # if we are using \"channels first\" ordering, then reshape the\n # design matrix such that the matrix is:\n # num_samples x depth x rows x columns\n if K.image_data_format() == \"channels_first\":\n data = data_orig.reshape(data_orig.shape[0], channel, height, width)\n \n # otherwise, we are using \"channels last\" ordering, so the design\n # matrix shape should be: num_samples x rows x columns x depth\n else:\n data = data_orig.reshape(data_orig.shape[0], height, width, channel)\n\n return data\n\n\ndef load_data(datasetpath, preprocessors):\n # grab the list of images that we’ll be describing\n print(\"[INFO] loading images...\")\n imagePaths = list(paths.list_images(datasetpath))\n \n # load the dataset from disk then scale the raw pixel intensities\n # to the range [0, 1]\n sdl = SimpleDatasetLoader(preprocessors=preprocessors)\n (data, labels) = sdl.load(imagePaths, verbose=500)\n data = data.astype(\"float\") / 255.0\n \n # partition the data into training and testing splits using 75% of\n # the data for training and the remaining 25% for testing\n (trainX, testX, trainY, testY) = train_test_split(\n data, labels, test_size=0.25, random_state=42)\n \n # convert the labels from integers to vectors\n lb = LabelBinarizer()\n lb.fit(labels)\n trainY = lb.transform(trainY)\n testY = lb.transform(testY)\n classNames = lb.classes_\n if len(classNames) < 3:\n trainY = np.hstack((trainY, 1 - trainY))\n testY = np.hstack((testY, 1 - testY))\n\n return ((trainX, trainY), (testX, testY), classNames)\n"
] | [
[
"numpy.median",
"numpy.zeros",
"numpy.abs",
"numpy.float32"
],
[
"numpy.hstack",
"sklearn.datasets.fetch_mldata",
"sklearn.model_selection.train_test_split",
"sklearn.preprocessing.LabelBinarizer"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
PABlond/Portfolio-CMS-for-freelancers | [
"ace9e8ed526b1605ea4a8fbbfcee9461c1e6fa4d"
] | [
"install/install.py"
] | [
"import pandas\nimport utils\nimport config\n\nvar = config.Variable()\n\n\ndf = pandas.read_excel(var.config)\npwd = var.pwd\n\ndef run():\n # Get data for gatsby-config.js\n with open(var.gatsby_config_template, \"r\") as f:\n gatsby_config = f.read()\n\n\n # Get data for src/data/content.js\n with open(var.content_template, \"r\") as f:\n content = f.read()\n\n\n # Apply changes to files\n for index, row in df.iterrows():\n value = row['Value']\n gatsby_config = gatsby_config.replace(row['Key'], value)\n\n if row['Key'] == '<BIOGRAPHY>':\n value = list(filter(None, row['Value'].split('\\n')))\n content = content.replace(row['Key'], str(value))\n\n\n # Write gatsby-config.js \n with open(var.gatsby_config, \"w+\") as f:\n f.write(gatsby_config)\n\n # Write content.ts \n with open(var.content, \"w+\") as f:\n f.write(content)\n\n\n # Geneate Open Source data\n utils.export_xls_as_list(img_folder=\"{}/images/open_source/\".format(pwd),\n filename=var.open_source_xls,\n filename_output=\"{}/src/data/{}.json\".format(\n pwd, var.open_source_xls.split('.xls')[0].split('/')[-1]))\n\n # Generate Experience data\n utils.export_xls_as_list(img_folder=\"{}/images/experiences/\".format(pwd),\n filename=var.experiences_xls,\n filename_output=\"{}/src/data/{}.json\".format(\n pwd, var.experiences_xls.split('.xls')[0].split('/')[-1]))\n\n # Generate Certifications data\n utils.export_xls_as_list(img_folder=\"{}/images/certifications/\".format(pwd),\n filename=var.certifications_xls,\n filename_output=\"{}/src/data/{}.json\".format(\n pwd, var.certifications_xls.split('.xls')[0].split('/')[-1]))"
] | [
[
"pandas.read_excel"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
}
] |
yonghoonlee/dymos | [
"602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4",
"602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4"
] | [
"dymos/transcriptions/transcription_base.py",
"dymos/examples/oscillator/doc/test_doc_oscillator.py"
] | [
"from collections.abc import Sequence\n\nimport numpy as np\n\nimport openmdao.api as om\n\nfrom .common import BoundaryConstraintComp, ControlGroup, PolynomialControlGroup, PathConstraintComp\nfrom ..utils.constants import INF_BOUND\nfrom ..utils.misc import get_rate_units, _unspecified\nfrom ..utils.introspection import get_target_metadata, get_source_metadata\n\n\nclass TranscriptionBase(object):\n \"\"\"\n Base class for all dymos transcriptions.\n\n Parameters\n ----------\n **kwargs : dict\n Dictionary of optional arguments.\n \"\"\"\n def __init__(self, **kwargs):\n\n self.grid_data = None\n\n self.options = om.OptionsDictionary()\n\n self.options.declare('num_segments', types=int, desc='Number of segments')\n self.options.declare('segment_ends', default=None, types=(Sequence, np.ndarray),\n allow_none=True, desc='Locations of segment ends or None for equally '\n 'spaced segments')\n self.options.declare('order', default=3, types=(int, Sequence, np.ndarray),\n desc='Order of the state transcription. The order of the control '\n 'transcription is `order - 1`.')\n self.options.declare('compressed', default=True, types=bool,\n desc='Use compressed transcription, meaning state and control values'\n 'at segment boundaries are not duplicated on input. This '\n 'implicitly enforces value continuity between segments but in '\n 'some cases may make the problem more difficult to solve.')\n\n self._declare_options()\n self.initialize()\n self.options.update(kwargs)\n self.init_grid()\n\n # Where to query var info.\n self._rhs_source = None\n\n def _declare_options(self):\n pass\n\n def initialize(self):\n \"\"\"\n Declare transcription options.\n \"\"\"\n pass\n\n def init_grid(self):\n \"\"\"\n Setup the GridData object for the Transcription.\n \"\"\"\n raise NotImplementedError('Transcription {0} does not implement method'\n 'init_grid.'.format(self.__class__.__name__))\n\n def setup_time(self, phase):\n \"\"\"\n Setup up the time component and time extents for the phase.\n\n Parameters\n ----------\n phase : dymos.Phase\n The phase object to which this transcription instance applies.\n \"\"\"\n time_options = phase.time_options\n\n # Warn about invalid options\n phase.check_time_options()\n\n if not time_options['input_initial'] or not time_options['input_duration']:\n phase.add_subsystem('time_extents', om.IndepVarComp(),\n promotes_outputs=['*'])\n\n def configure_time(self, phase):\n \"\"\"\n Configure the inputs/outputs on the time component.\n\n Parameters\n ----------\n phase : dymos.Phase\n The phase object to which this transcription instance applies.\n \"\"\"\n time_options = phase.time_options\n\n # Determine the time unit.\n if time_options['units'] in (None, _unspecified):\n if time_options['targets']:\n ode = phase._get_subsystem(self._rhs_source)\n\n _, time_options['units'] = get_target_metadata(ode, name='time',\n user_targets=time_options['targets'],\n user_units=time_options['units'],\n user_shape='')\n\n time_units = time_options['units']\n indeps = []\n default_vals = {'t_initial': phase.time_options['initial_val'],\n 't_duration': phase.time_options['duration_val']}\n\n if not time_options['input_initial']:\n indeps.append('t_initial')\n\n if not time_options['input_duration']:\n indeps.append('t_duration')\n\n for var in indeps:\n phase.time_extents.add_output(var, val=default_vals[var], units=time_units)\n\n if not (time_options['input_initial'] or time_options['fix_initial']):\n lb, ub = time_options['initial_bounds']\n lb = -INF_BOUND if lb is None else lb\n ub = INF_BOUND if ub is None else ub\n\n phase.add_design_var('t_initial',\n lower=lb,\n upper=ub,\n scaler=time_options['initial_scaler'],\n adder=time_options['initial_adder'],\n ref0=time_options['initial_ref0'],\n ref=time_options['initial_ref'])\n\n if not (time_options['input_duration'] or time_options['fix_duration']):\n lb, ub = time_options['duration_bounds']\n lb = -INF_BOUND if lb is None else lb\n ub = INF_BOUND if ub is None else ub\n\n phase.add_design_var('t_duration',\n lower=lb,\n upper=ub,\n scaler=time_options['duration_scaler'],\n adder=time_options['duration_adder'],\n ref0=time_options['duration_ref0'],\n ref=time_options['duration_ref'])\n\n def setup_controls(self, phase):\n \"\"\"\n Setup the control group.\n\n Parameters\n ----------\n phase : dymos.Phase\n The phase object to which this transcription instance applies.\n \"\"\"\n phase._check_control_options()\n\n if phase.control_options:\n control_group = ControlGroup(control_options=phase.control_options,\n time_units=phase.time_options['units'],\n grid_data=self.grid_data)\n\n phase.add_subsystem('control_group',\n subsys=control_group)\n\n def _configure_state_introspection(self, state_name, options, phase):\n \"\"\"\n Modifies state options in-place, automatically determining 'targets', 'units', and 'shape'\n if necessary.\n\n The precedence rules for the state shape and units are as follows:\n 1. If the user has specified units and shape in the state options, use those.\n 2a. If the user has not specified shape, and targets exist, then pull the shape from the targets.\n 2b. If the user has not specified shape and no targets exist, then pull the shape from the rate source.\n 2c. If shape cannot be inferred, assume (1,)\n 3a. If the user has not specified units, first try to pull units from a target\n 3b. If there are no targets, pull units from the rate source and multiply by time units.\n\n Parameters\n ----------\n state_name : str\n The name of the state variable of interest.\n options : OptionsDictionary\n The options dictionary for the state variable of interest.\n phase : dymos.Phase\n The phase associated with the transcription.\n \"\"\"\n time_units = phase.time_options['units']\n user_targets = options['targets']\n user_units = options['units']\n user_shape = options['shape']\n\n need_units = user_units is _unspecified\n need_shape = user_shape in {None, _unspecified}\n\n ode = phase._get_subsystem(self._rhs_source)\n\n # Automatically determine targets of state if left _unspecified\n if user_targets is _unspecified:\n from dymos.utils.introspection import get_targets\n options['targets'] = get_targets(ode, state_name, user_targets)\n\n # 1. No introspection necessary\n if not(need_shape or need_units):\n return\n\n # 2. Attempt target introspection\n if options['targets']:\n try:\n from dymos.utils.introspection import get_state_target_metadata\n tgt_shape, tgt_units = get_state_target_metadata(ode, state_name, options['targets'],\n options['units'], options['shape'])\n options['shape'] = tgt_shape\n options['units'] = tgt_units\n return\n except ValueError:\n pass\n\n # 3. Attempt rate-source introspection\n rate_src = options['rate_source']\n rate_src_type = phase.classify_var(rate_src)\n\n if rate_src_type in ['time', 'time_phase']:\n rate_src_units = phase.time_options['units']\n rate_src_shape = (1,)\n elif rate_src_type == 'state':\n rate_src_units = phase.state_options[rate_src]['units']\n rate_src_shape = phase.state_options[rate_src]['shape']\n elif rate_src_type in ['input_control', 'indep_control']:\n rate_src_units = phase.control_options[rate_src]['units']\n rate_src_shape = phase.control_options[rate_src]['shape']\n elif rate_src_type in ['input_polynomial_control', 'indep_polynomial_control']:\n rate_src_units = phase.polynomial_control_options[rate_src]['units']\n rate_src_shape = phase.polynomial_control_options[rate_src]['shape']\n elif rate_src_type == 'parameter':\n rate_src_units = phase.parameter_options[rate_src]['units']\n rate_src_shape = phase.parameter_options[rate_src]['shape']\n elif rate_src_type == 'control_rate':\n control_name = rate_src[:-5]\n control = phase.control_options[control_name]\n rate_src_units = get_rate_units(control['units'], time_units, deriv=1)\n rate_src_shape = control['shape']\n elif rate_src_type == 'control_rate2':\n control_name = rate_src[:-6]\n control = phase.control_options[control_name]\n rate_src_units = get_rate_units(control['units'], time_units, deriv=2)\n rate_src_shape = control['shape']\n elif rate_src_type == 'polynomial_control_rate':\n control_name = rate_src[:-5]\n control = phase.polynomial_control_options[control_name]\n rate_src_units = get_rate_units(control['units'], time_units, deriv=1)\n rate_src_shape = control['shape']\n elif rate_src_type == 'polynomial_control_rate2':\n control_name = rate_src[:-6]\n control = phase.polynomial_control_options[control_name]\n rate_src_units = get_rate_units(control['units'], time_units, deriv=2)\n rate_src_shape = control['shape']\n elif rate_src_type == 'ode':\n rate_src_shape, rate_src_units = get_source_metadata(ode,\n src=rate_src,\n user_units=options['units'],\n user_shape=options['shape'])\n else:\n rate_src_shape = (1,)\n rate_src_units = None\n\n if need_shape:\n options['shape'] = rate_src_shape\n\n if need_units:\n options['units'] = time_units if rate_src_units is None else f'{rate_src_units}*{time_units}'\n\n return\n\n def configure_controls(self, phase):\n \"\"\"\n Configure the inputs/outputs for the controls.\n\n Parameters\n ----------\n phase : dymos.Phase\n The phase object to which this transcription instance applies.\n \"\"\"\n pass\n\n def setup_polynomial_controls(self, phase):\n \"\"\"\n Adds the polynomial control group to the model if any polynomial controls are present.\n\n Parameters\n ----------\n phase : dymos.Phase\n The phase object to which this transcription instance applies.\n \"\"\"\n if phase.polynomial_control_options:\n sys = PolynomialControlGroup(grid_data=self.grid_data,\n polynomial_control_options=phase.polynomial_control_options,\n time_units=phase.time_options['units'])\n phase.add_subsystem('polynomial_control_group', subsys=sys,\n promotes_inputs=['*'], promotes_outputs=['*'])\n\n def configure_polynomial_controls(self, phase):\n \"\"\"\n Configure the inputs/outputs for the polynomial controls.\n\n Parameters\n ----------\n phase : dymos.Phase\n The phase object to which this transcription instance applies.\n \"\"\"\n if phase.polynomial_control_options:\n phase.polynomial_control_group.configure_io()\n\n def setup_parameters(self, phase):\n \"\"\"\n Sets input defaults for parameters and optionally adds design variables.\n\n Parameters\n ----------\n phase : dymos.Phase\n The phase object to which this transcription instance applies.\n \"\"\"\n phase._check_parameter_options()\n\n if phase.parameter_options:\n for name, options in phase.parameter_options.items():\n src_name = 'parameters:{0}'.format(name)\n\n if options['opt']:\n lb = -INF_BOUND if options['lower'] is None else options['lower']\n ub = INF_BOUND if options['upper'] is None else options['upper']\n\n phase.add_design_var(name=src_name,\n lower=lb,\n upper=ub,\n scaler=options['scaler'],\n adder=options['adder'],\n ref0=options['ref0'],\n ref=options['ref'])\n\n def configure_parameters(self, phase):\n \"\"\"\n Configure parameter promotion.\n\n Parameters\n ----------\n phase : dymos.Phase\n The phase object to which this transcription instance applies.\n \"\"\"\n if phase.parameter_options:\n ode = self._get_ode(phase)\n\n for name, options in phase.parameter_options.items():\n prom_name = f'parameters:{name}'\n\n # Get units and shape from targets when needed.\n shape, units, static = get_target_metadata(ode, name=name,\n user_targets=options['targets'],\n user_shape=options['shape'],\n user_units=options['units'],\n user_static_target=options['static_target'])\n options['units'] = units\n options['shape'] = shape\n options['static_target'] = static\n\n for tgts, src_idxs in self.get_parameter_connections(name, phase):\n for pathname in tgts:\n parts = pathname.split('.')\n sub_sys = parts[0]\n tgt_var = '.'.join(parts[1:])\n if not options['static_target']:\n phase.promotes(sub_sys, inputs=[(tgt_var, prom_name)],\n src_indices=src_idxs, flat_src_indices=True)\n else:\n phase.promotes(sub_sys, inputs=[(tgt_var, prom_name)])\n\n val = options['val']\n _shape = options['shape']\n shaped_val = np.broadcast_to(val, _shape)\n phase.set_input_defaults(name=prom_name,\n val=shaped_val,\n units=options['units'])\n\n def setup_states(self, phase):\n \"\"\"\n Setup the states for this transcription.\n\n Parameters\n ----------\n phase : dymos.Phase\n The phase object to which this transcription instance applies.\n \"\"\"\n raise NotImplementedError('Transcription {0} does not implement method '\n 'setup_states.'.format(self.__class__.__name__))\n\n def setup_ode(self, phase):\n \"\"\"\n Setup the ode for this transcription.\n\n Parameters\n ----------\n phase : dymos.Phase\n The phase object to which this transcription instance applies.\n \"\"\"\n raise NotImplementedError('Transcription {0} does not implement method '\n 'setup_ode.'.format(self.__class__.__name__))\n\n def setup_timeseries_outputs(self, phase):\n \"\"\"\n Setup the timeseries for this transcription.\n\n Parameters\n ----------\n phase : dymos.Phase\n The phase object to which this transcription instance applies.\n \"\"\"\n raise NotImplementedError('Transcription {0} does not implement method '\n 'setup_timeseries_outputs.'.format(self.__class__.__name__))\n\n def setup_boundary_constraints(self, loc, phase):\n \"\"\"\n Setup the boundary constraints.\n\n Adds BoundaryConstraintComp for initial and/or final boundary constraints if necessary\n and issues appropriate connections.\n\n Parameters\n ----------\n loc : str\n The kind of boundary constraints being setup. Must be one of 'initial' or 'final'.\n phase : dymos.Phase\n The phase object to which this transcription instance applies.\n \"\"\"\n if loc not in ('initial', 'final'):\n raise ValueError('loc must be one of \\'initial\\' or \\'final\\'.')\n\n bc_dict = phase._initial_boundary_constraints \\\n if loc == 'initial' else phase._final_boundary_constraints\n\n if bc_dict:\n phase.add_subsystem(f'{loc}_boundary_constraints',\n subsys=BoundaryConstraintComp(loc=loc))\n\n def configure_boundary_constraints(self, loc, phase):\n \"\"\"\n Configures the boundary constraints.\n\n Adds BoundaryConstraintComp for initial and/or final boundary constraints if necessary\n and issues appropriate connections.\n\n Parameters\n ----------\n loc : str\n The kind of boundary constraints being setup. Must be one of 'initial' or 'final'.\n phase : dymos.Phase\n The phase object to which this transcription instance applies.\n \"\"\"\n bc_dict = phase._initial_boundary_constraints \\\n if loc == 'initial' else phase._final_boundary_constraints\n\n sys_name = f'{loc}_boundary_constraints'\n bc_comp = phase._get_subsystem(sys_name)\n\n for var, options in bc_dict.items():\n con_name = options['constraint_name']\n\n _, shape, units, linear = self._get_boundary_constraint_src(var, loc, phase)\n\n if options['indices'] is not None:\n # Sliced shape.\n con_shape = (len(options['indices']), )\n # Indices provided, make sure lower/upper/equals have shape of the indices.\n if options['lower'] and not np.isscalar(options['lower']) and \\\n np.asarray(options['lower']).shape != con_shape:\n raise ValueError('The lower bounds of boundary constraint on {0} are not '\n 'compatible with its shape, and no indices were '\n 'provided.'.format(var))\n\n if options['upper'] and not np.isscalar(options['upper']) and \\\n np.asarray(options['upper']).shape != con_shape:\n raise ValueError('The upper bounds of boundary constraint on {0} are not '\n 'compatible with its shape, and no indices were '\n 'provided.'.format(var))\n\n if options['equals'] and not np.isscalar(options['equals']) and \\\n np.asarray(options['equals']).shape != con_shape:\n raise ValueError('The equality boundary constraint value on {0} is not '\n 'compatible the provided indices. Provide them as a '\n 'flat array with the same size as indices.'.format(var))\n\n else:\n # Indices not provided, make sure lower/upper/equals have shape of source.\n if 'lower' in options and options['lower'] is not None and \\\n not np.isscalar(options['lower']) and np.asarray(options['lower']).shape != shape:\n raise ValueError('The lower bounds of boundary constraint on {0} are not '\n 'compatible with its shape, and no indices were '\n 'provided. Expected a shape of {1} but given shape '\n 'is {2}'.format(var, shape, np.asarray(options['lower']).shape))\n\n if 'upper' in options and options['upper'] is not None and \\\n not np.isscalar(options['upper']) and np.asarray(options['upper']).shape != shape:\n raise ValueError('The upper bounds of boundary constraint on {0} are not '\n 'compatible with its shape, and no indices were '\n 'provided. Expected a shape of {1} but given shape '\n 'is {2}'.format(var, shape, np.asarray(options['upper']).shape))\n\n if 'equals' in options and options['equals'] is not None and \\\n not np.isscalar(options['equals']) and np.asarray(options['equals']).shape != shape:\n raise ValueError('The equality boundary constraint value on {0} is not '\n 'compatible with its shape, and no indices were '\n 'provided. Expected a shape of {1} but given shape '\n 'is {2}'.format(var, shape, np.asarray(options['equals']).shape))\n\n # Constraint options are a copy of options with constraint_name key removed.\n con_options = options.copy()\n con_options.pop('constraint_name')\n\n # By now, all possible constraint target shapes should have been introspected.\n con_options['shape'] = options['shape'] = shape\n\n # If user overrides the introspected unit, then change the unit on the add_constraint call.\n con_units = options['units']\n con_options['units'] = units if con_units is None else con_units\n con_options['linear'] = linear\n\n bc_comp._add_constraint(con_name, **con_options)\n\n if bc_comp:\n bc_comp.configure_io()\n\n for var, options in bc_dict.items():\n con_name = options['constraint_name']\n\n src, shape, units, linear = self._get_boundary_constraint_src(var, loc, phase)\n\n size = np.prod(shape)\n\n # Build the correct src_indices regardless of shape\n if loc == 'initial':\n src_idxs = np.arange(size, dtype=int).reshape(shape)\n else:\n src_idxs = np.arange(-size, 0, dtype=int).reshape(shape)\n\n src_idxs = (src_idxs,)\n\n if 'parameters:' in src:\n sys_name = '{0}_boundary_constraints'.format(loc)\n tgt_name = '{0}_value_in:{1}'.format(loc, con_name)\n phase.promotes(sys_name, inputs=[(tgt_name, src)],\n src_indices=src_idxs, flat_src_indices=True)\n\n else:\n phase.connect(src, f'{loc}_boundary_constraints.{loc}_value_in:{con_name}',\n src_indices=src_idxs, flat_src_indices=True)\n\n def setup_path_constraints(self, phase):\n \"\"\"\n Add a path constraint component if necessary.\n\n Parameters\n ----------\n phase : dymos.Phase\n The phase object to which this transcription instance applies.\n \"\"\"\n gd = self.grid_data\n\n if phase._path_constraints:\n path_comp = PathConstraintComp(num_nodes=gd.num_nodes)\n phase.add_subsystem('path_constraints', subsys=path_comp)\n\n def configure_path_constraints(self, phase):\n \"\"\"\n Handle the common operations for configuration of the path constraints.\n\n Parameters\n ----------\n phase : dymos.Phase\n The phase object to which this transcription instance applies.\n \"\"\"\n time_units = phase.time_options['units']\n\n for var, options in phase._path_constraints.items():\n constraint_kwargs = options.copy()\n con_units = constraint_kwargs['units'] = options.get('units', None)\n con_name = constraint_kwargs.pop('constraint_name')\n\n # Determine the path to the variable which we will be constraining\n # This is more complicated for path constraints since, for instance,\n # a single state variable has two sources which must be connected to\n # the path component.\n var_type = phase.classify_var(var)\n\n if var_type == 'time':\n constraint_kwargs['shape'] = (1,)\n constraint_kwargs['units'] = time_units if con_units is None else con_units\n constraint_kwargs['linear'] = True\n\n elif var_type == 'time_phase':\n constraint_kwargs['shape'] = (1,)\n constraint_kwargs['units'] = time_units if con_units is None else con_units\n constraint_kwargs['linear'] = True\n\n elif var_type == 'state':\n state_shape = phase.state_options[var]['shape']\n state_units = phase.state_options[var]['units']\n constraint_kwargs['shape'] = state_shape\n constraint_kwargs['units'] = state_units if con_units is None else con_units\n constraint_kwargs['linear'] = False\n\n elif var_type == 'indep_control':\n control_shape = phase.control_options[var]['shape']\n control_units = phase.control_options[var]['units']\n\n constraint_kwargs['shape'] = control_shape\n constraint_kwargs['units'] = control_units if con_units is None else con_units\n constraint_kwargs['linear'] = True\n\n elif var_type == 'input_control':\n control_shape = phase.control_options[var]['shape']\n control_units = phase.control_options[var]['units']\n\n constraint_kwargs['shape'] = control_shape\n constraint_kwargs['units'] = control_units if con_units is None else con_units\n constraint_kwargs['linear'] = True\n\n elif var_type == 'indep_polynomial_control':\n control_shape = phase.polynomial_control_options[var]['shape']\n control_units = phase.polynomial_control_options[var]['units']\n constraint_kwargs['shape'] = control_shape\n constraint_kwargs['units'] = control_units if con_units is None else con_units\n constraint_kwargs['linear'] = False\n\n elif var_type == 'input_polynomial_control':\n control_shape = phase.polynomial_control_options[var]['shape']\n control_units = phase.polynomial_control_options[var]['units']\n constraint_kwargs['shape'] = control_shape\n constraint_kwargs['units'] = control_units if con_units is None else con_units\n constraint_kwargs['linear'] = False\n\n elif var_type == 'control_rate':\n control_name = var[:-5]\n control_shape = phase.control_options[control_name]['shape']\n control_units = phase.control_options[control_name]['units']\n constraint_kwargs['shape'] = control_shape\n constraint_kwargs['units'] = get_rate_units(control_units, time_units, deriv=1) \\\n if con_units is None else con_units\n\n elif var_type == 'control_rate2':\n control_name = var[:-6]\n control_shape = phase.control_options[control_name]['shape']\n control_units = phase.control_options[control_name]['units']\n constraint_kwargs['shape'] = control_shape\n constraint_kwargs['units'] = get_rate_units(control_units, time_units, deriv=2) \\\n if con_units is None else con_units\n\n elif var_type == 'polynomial_control_rate':\n control_name = var[:-5]\n control_shape = phase.polynomial_control_options[control_name]['shape']\n control_units = phase.polynomial_control_options[control_name]['units']\n constraint_kwargs['shape'] = control_shape\n constraint_kwargs['units'] = get_rate_units(control_units, time_units, deriv=1) \\\n if con_units is None else con_units\n\n elif var_type == 'polynomial_control_rate2':\n control_name = var[:-6]\n control_shape = phase.polynomial_control_options[control_name]['shape']\n control_units = phase.polynomial_control_options[control_name]['units']\n constraint_kwargs['shape'] = control_shape\n constraint_kwargs['units'] = get_rate_units(control_units, time_units, deriv=2) \\\n if con_units is None else con_units\n\n else:\n # Failed to find variable, assume it is in the ODE. This requires introspection.\n ode = phase._get_subsystem(self._rhs_source)\n\n shape, units = get_source_metadata(ode, src=var,\n user_units=options['units'],\n user_shape=options['shape'])\n\n constraint_kwargs['linear'] = False\n constraint_kwargs['shape'] = shape\n constraint_kwargs['units'] = units\n\n # Propagate the introspected shape back into the options dict.\n # Some transcriptions use this later.\n options['shape'] = constraint_kwargs['shape']\n\n constraint_kwargs.pop('constraint_name', None)\n phase._get_subsystem('path_constraints')._add_path_constraint_configure(con_name, **constraint_kwargs)\n\n def configure_objective(self, phase):\n \"\"\"\n Find the path of the objective(s) and add them.\n\n Parameters\n ----------\n phase : dymos.Phase\n The phase object to which this transcription instance applies.\n \"\"\"\n for name, options in phase._objectives.items():\n index = options['index']\n loc = options['loc']\n\n obj_path, shape, units, _ = self._get_boundary_constraint_src(name, loc, phase)\n\n shape = options['shape'] if shape is None else shape\n\n size = int(np.prod(shape))\n\n if size > 1 and index is None:\n raise ValueError('Objective variable is non-scaler {0} but no index specified '\n 'for objective'.format(shape))\n\n idx = 0 if index is None else index\n if idx < 0:\n idx = size + idx\n\n if idx >= size or idx < -size:\n raise ValueError('Objective index={0}, but the shape of the objective '\n 'variable is {1}'.format(index, shape))\n\n if loc == 'final':\n obj_index = -size + idx\n elif loc == 'initial':\n obj_index = idx\n else:\n raise ValueError('Invalid value for objective loc: {0}. Must be '\n 'one of \\'initial\\' or \\'final\\'.'.format(loc))\n\n from ..phase import Phase\n super(Phase, phase).add_objective(obj_path, ref=options['ref'], ref0=options['ref0'],\n index=obj_index, flat_indices=True, adder=options['adder'],\n scaler=options['scaler'],\n parallel_deriv_color=options['parallel_deriv_color'])\n\n def _get_boundary_constraint_src(self, name, loc, phase):\n raise NotImplementedError('Transcription {0} does not implement method'\n '_get_boundary_constraint_source.'.format(self.__class__.__name__))\n\n def _get_rate_source_path(self, name, loc, phase):\n raise NotImplementedError('Transcription {0} does not implement method'\n '_get_rate_source_path.'.format(self.__class__.__name__))\n\n def _get_ode(self, phase):\n \"\"\"\n Returns an instance of the ODE used in the phase that can be interrogated for IO metadata.\n\n Parameters\n ----------\n phase : dm.Phase\n The Phase instance to which this transcription applies\n\n Returns\n -------\n ode : om.System\n The OpenMDAO system which serves as the ODE for the given Phase.\n\n \"\"\"\n return phase._get_subsystem(self._rhs_source)\n\n def get_parameter_connections(self, name, phase):\n \"\"\"\n Returns info about a parameter's target connections in the phase.\n\n Parameters\n ----------\n name : str\n The name of the parameter for which connection information is desired.\n phase : dymos.Phase\n The phase object to which this transcription applies.\n\n Returns\n -------\n list of (paths, indices)\n A list containing a tuple of target paths and corresponding src_indices to which the\n given design variable is to be connected.\n \"\"\"\n raise NotImplementedError('Transcription {0} does not implement method '\n 'get_parameter_connections.'.format(self.__class__.__name__))\n\n def is_static_ode_output(self, var, phase, num_nodes):\n \"\"\"\n Test whether the given output is a static output of the ODE.\n\n A variable is considered static if it's first dimension is different than the\n number of nodes in the ODE.\n\n Parameters\n ----------\n var : str\n The ode-relative path of the variable of interest.\n phase : dymos.Phase\n The phase to which this transcription applies.\n num_nodes : int\n The number of nodes in the ODE.\n\n Returns\n -------\n bool\n True if the given variable is a static output, otherwise False if it is dynamic.\n\n Raises\n ------\n KeyError\n KeyError is raised if the given variable isn't present in the ode outputs.\n \"\"\"\n ode = phase._get_subsystem(self._rhs_source)\n ode_outputs = {opts['prom_name']: opts for (k, opts) in\n ode.get_io_metadata(iotypes=('output',), get_remote=True).items()}\n ode_shape = ode_outputs[var]['shape']\n return ode_shape[0] != num_nodes\n\n def _requires_continuity_constraints(self, phase):\n \"\"\"\n Tests whether state and/or control and/or control rate continuity are required.\n\n Parameters\n ----------\n phase : dymos.Phase\n The phase to which this transcription applies.\n\n Returns\n -------\n state_continuity : bool\n True if any state continuity is required to be enforced.\n control_continuity : bool\n True if any control value continuity is required to be enforced.\n control_rate_continuity : bool\n True if any control rate continuity is required to be enforced.\n \"\"\"\n raise NotImplementedError(f'The transcription {self.__class__} does not provide an '\n f'implementation of _requires_continuity_constraints')\n",
"import unittest\nfrom openmdao.utils.testing_utils import use_tempdirs\n\n\n@use_tempdirs\nclass TestDocOscillator(unittest.TestCase):\n\n def test_ivp(self):\n import openmdao.api as om\n import dymos as dm\n import matplotlib.pyplot as plt\n plt.switch_backend('Agg') # disable plotting to the screen\n\n from dymos.examples.oscillator.doc.oscillator_ode import OscillatorODE\n\n # Instantiate an OpenMDAO Problem instance.\n prob = om.Problem()\n\n # Instantiate a Dymos Trajectory and add it to the Problem model.\n traj = dm.Trajectory()\n prob.model.add_subsystem('traj', traj)\n\n # Instantiate a Phase and add it to the Trajectory.\n # Here the transcription is necessary but not particularly relevant.\n phase = dm.Phase(ode_class=OscillatorODE, transcription=dm.Radau(num_segments=4))\n traj.add_phase('phase0', phase)\n\n # Tell Dymos the states to be propagated using the given ODE.\n phase.add_state('v', rate_source='v_dot', targets=['v'], units='m/s')\n phase.add_state('x', rate_source='v', targets=['x'], units='m')\n\n # The spring constant, damping coefficient, and mass are inputs to the system\n # that are constant throughout the phase.\n phase.add_parameter('k', units='N/m', targets=['k'])\n phase.add_parameter('c', units='N*s/m', targets=['c'])\n phase.add_parameter('m', units='kg', targets=['m'])\n\n # Setup the OpenMDAO problem\n prob.setup()\n\n # Assign values to the times and states\n prob.set_val('traj.phase0.t_initial', 0.0)\n prob.set_val('traj.phase0.t_duration', 15.0)\n\n prob.set_val('traj.phase0.states:x', 10.0)\n prob.set_val('traj.phase0.states:v', 0.0)\n\n prob.set_val('traj.phase0.parameters:k', 1.0)\n prob.set_val('traj.phase0.parameters:c', 0.5)\n prob.set_val('traj.phase0.parameters:m', 1.0)\n\n # Perform a single execution of the model (executing the model is required before simulation).\n prob.run_model()\n\n # Perform an explicit simulation of our ODE from the initial conditions.\n sim_out = traj.simulate(times_per_seg=50)\n\n # Plot the state values obtained from the phase timeseries objects in the simulation output.\n t_sol = prob.get_val('traj.phase0.timeseries.time')\n t_sim = sim_out.get_val('traj.phase0.timeseries.time')\n\n states = ['x', 'v']\n fig, axes = plt.subplots(len(states), 1)\n for i, state in enumerate(states):\n sol = axes[i].plot(t_sol, prob.get_val(f'traj.phase0.timeseries.states:{state}'), 'o')\n sim = axes[i].plot(t_sim, sim_out.get_val(f'traj.phase0.timeseries.states:{state}'), '-')\n axes[i].set_ylabel(state)\n axes[-1].set_xlabel('time (s)')\n fig.legend((sol[0], sim[0]), ('solution', 'simulation'), 'lower right', ncol=2)\n plt.tight_layout()\n plt.show()\n\n def test_ivp_solver(self):\n import openmdao.api as om\n import dymos as dm\n import matplotlib.pyplot as plt\n plt.switch_backend('Agg') # disable plotting to the screen\n\n from dymos.examples.oscillator.doc.oscillator_ode import OscillatorODE\n\n # Instantiate an OpenMDAO Problem instance.\n prob = om.Problem()\n\n # Instantiate a Dymos Trajectory and add it to the Problem model.\n traj = dm.Trajectory()\n prob.model.add_subsystem('traj', traj)\n\n # Instantiate a Phase and add it to the Trajectory.\n phase = dm.Phase(ode_class=OscillatorODE, transcription=dm.Radau(num_segments=4, solve_segments='forward'))\n traj.add_phase('phase0', phase)\n\n # Tell Dymos the states to be propagated using the given ODE.\n phase.add_state('x', fix_initial=True, rate_source='v', targets=['x'], units='m')\n phase.add_state('v', fix_initial=True, rate_source='v_dot', targets=['v'], units='m/s')\n\n # The spring constant, damping coefficient, and mass are inputs to the system that are\n # constant throughout the phase.\n phase.add_parameter('k', units='N/m', targets=['k'])\n phase.add_parameter('c', units='N*s/m', targets=['c'])\n phase.add_parameter('m', units='kg', targets=['m'])\n\n # Setup the OpenMDAO problem\n prob.setup()\n\n # Assign values to the times and states\n prob.set_val('traj.phase0.t_initial', 0.0)\n prob.set_val('traj.phase0.t_duration', 15.0)\n\n prob.set_val('traj.phase0.states:x', 10.0)\n prob.set_val('traj.phase0.states:v', 0.0)\n\n prob.set_val('traj.phase0.parameters:k', 1.0)\n prob.set_val('traj.phase0.parameters:c', 0.5)\n prob.set_val('traj.phase0.parameters:m', 1.0)\n\n # Now converge the dynamics using a nonlinear solver to find the trajectory without optimization.\n prob.run_model()\n\n # Perform an explicit simulation of our ODE from the initial conditions.\n sim_out = traj.simulate(times_per_seg=50)\n\n # Plot the state values obtained from the phase timeseries objects in the simulation output.\n t_sol = prob.get_val('traj.phase0.timeseries.time')\n t_sim = sim_out.get_val('traj.phase0.timeseries.time')\n\n states = ['x', 'v']\n fig, axes = plt.subplots(len(states), 1)\n for i, state in enumerate(states):\n sol = axes[i].plot(t_sol, prob.get_val(f'traj.phase0.timeseries.states:{state}'), 'o')\n sim = axes[i].plot(t_sim, sim_out.get_val(f'traj.phase0.timeseries.states:{state}'), '-')\n axes[i].set_ylabel(state)\n axes[-1].set_xlabel('time (s)')\n fig.legend((sol[0], sim[0]), ('solution', 'simulation'), 'lower right', ncol=2)\n plt.tight_layout()\n plt.show()\n\n def test_ivp_driver(self):\n import openmdao.api as om\n import dymos as dm\n import matplotlib.pyplot as plt\n plt.switch_backend('Agg') # disable plotting to the screen\n\n from dymos.examples.oscillator.doc.oscillator_ode import OscillatorODE\n\n # Instantiate an OpenMDAO Problem instance.\n prob = om.Problem()\n\n # We need an optimization driver. To solve this simple problem ScipyOptimizerDriver will work.\n prob.driver = om.ScipyOptimizeDriver()\n\n # Instantiate a Dymos Trajectory and add it to the Problem model.\n traj = dm.Trajectory()\n prob.model.add_subsystem('traj', traj)\n\n # Instantiate a Phase and add it to the Trajectory.\n phase = dm.Phase(ode_class=OscillatorODE, transcription=dm.Radau(num_segments=4))\n traj.add_phase('phase0', phase)\n\n # Tell Dymos that the duration of the phase is bounded.\n phase.set_time_options(fix_initial=True, fix_duration=True)\n\n # Tell Dymos the states to be propagated using the given ODE.\n phase.add_state('x', fix_initial=True, rate_source='v', targets=['x'], units='m')\n phase.add_state('v', fix_initial=True, rate_source='v_dot', targets=['v'], units='m/s')\n\n # The spring constant, damping coefficient, and mass are inputs to the system that are\n # constant throughout the phase.\n phase.add_parameter('k', units='N/m', targets=['k'])\n phase.add_parameter('c', units='N*s/m', targets=['c'])\n phase.add_parameter('m', units='kg', targets=['m'])\n\n # Since we're using an optimization driver, an objective is required. We'll minimize\n # the final time in this case.\n phase.add_objective('time', loc='final')\n\n # Setup the OpenMDAO problem\n prob.setup()\n\n # Assign values to the times and states\n prob.set_val('traj.phase0.t_initial', 0.0)\n prob.set_val('traj.phase0.t_duration', 15.0)\n\n prob.set_val('traj.phase0.states:x', 10.0)\n prob.set_val('traj.phase0.states:v', 0.0)\n\n prob.set_val('traj.phase0.parameters:k', 1.0)\n prob.set_val('traj.phase0.parameters:c', 0.5)\n prob.set_val('traj.phase0.parameters:m', 1.0)\n\n # Now we're using the optimization driver to iteratively run the model and vary the\n # phase duration until the final y value is 0.\n prob.run_driver()\n\n # Perform an explicit simulation of our ODE from the initial conditions.\n sim_out = traj.simulate(times_per_seg=50)\n\n # Plot the state values obtained from the phase timeseries objects in the simulation output.\n t_sol = prob.get_val('traj.phase0.timeseries.time')\n t_sim = sim_out.get_val('traj.phase0.timeseries.time')\n\n states = ['x', 'v']\n fig, axes = plt.subplots(len(states), 1)\n for i, state in enumerate(states):\n sol = axes[i].plot(t_sol, prob.get_val(f'traj.phase0.timeseries.states:{state}'), 'o')\n sim = axes[i].plot(t_sim, sim_out.get_val(f'traj.phase0.timeseries.states:{state}'), '-')\n axes[i].set_ylabel(state)\n axes[-1].set_xlabel('time (s)')\n fig.legend((sol[0], sim[0]), ('solution', 'simulation'), 'lower right', ncol=2)\n plt.tight_layout()\n plt.show()\n\n def test_ivp_driver_10_segs(self):\n import openmdao.api as om\n import dymos as dm\n import matplotlib.pyplot as plt\n plt.switch_backend('Agg') # disable plotting to the screen\n\n from dymos.examples.oscillator.doc.oscillator_ode import OscillatorODE\n\n # Instantiate an OpenMDAO Problem instance.\n prob = om.Problem()\n\n # We need an optimization driver. To solve this simple problem ScipyOptimizerDriver will work.\n prob.driver = om.ScipyOptimizeDriver()\n\n # Instantiate a Dymos Trajectory and add it to the Problem model.\n traj = dm.Trajectory()\n prob.model.add_subsystem('traj', traj)\n\n # Instantiate a Phase and add it to the Trajectory.\n phase = dm.Phase(ode_class=OscillatorODE, transcription=dm.Radau(num_segments=10))\n traj.add_phase('phase0', phase)\n\n # Tell Dymos that the duration of the phase is bounded.\n phase.set_time_options(fix_initial=True, fix_duration=True)\n\n # Tell Dymos the states to be propagated using the given ODE.\n phase.add_state('x', fix_initial=True, rate_source='v', targets=['x'], units='m')\n phase.add_state('v', fix_initial=True, rate_source='v_dot', targets=['v'], units='m/s')\n\n # The spring constant, damping coefficient, and mass are inputs to the system that\n # are constant throughout the phase.\n phase.add_parameter('k', units='N/m', targets=['k'])\n phase.add_parameter('c', units='N*s/m', targets=['c'])\n phase.add_parameter('m', units='kg', targets=['m'])\n\n # Since we're using an optimization driver, an objective is required. We'll minimize\n # the final time in this case.\n phase.add_objective('time', loc='final')\n\n # Setup the OpenMDAO problem\n prob.setup()\n\n # Assign values to the times and states\n prob.set_val('traj.phase0.t_initial', 0.0)\n prob.set_val('traj.phase0.t_duration', 15.0)\n\n prob.set_val('traj.phase0.states:x', 10.0)\n prob.set_val('traj.phase0.states:v', 0.0)\n\n prob.set_val('traj.phase0.parameters:k', 1.0)\n prob.set_val('traj.phase0.parameters:c', 0.5)\n prob.set_val('traj.phase0.parameters:m', 1.0)\n\n # Now we're using the optimization driver to iteratively run the model and vary the\n # phase duration until the final y value is 0.\n prob.run_driver()\n\n # Perform an explicit simulation of our ODE from the initial conditions.\n sim_out = traj.simulate(times_per_seg=50)\n\n # Plot the state values obtained from the phase timeseries objects in the simulation output.\n t_sol = prob.get_val('traj.phase0.timeseries.time')\n t_sim = sim_out.get_val('traj.phase0.timeseries.time')\n\n states = ['x', 'v']\n fig, axes = plt.subplots(len(states), 1)\n for i, state in enumerate(states):\n sol = axes[i].plot(t_sol, prob.get_val(f'traj.phase0.timeseries.states:{state}'), 'o')\n sim = axes[i].plot(t_sim, sim_out.get_val(f'traj.phase0.timeseries.states:{state}'), '-')\n axes[i].set_ylabel(state)\n axes[-1].set_xlabel('time (s)')\n fig.legend((sol[0], sim[0]), ('solution', 'simulation'), 'lower right', ncol=2)\n plt.tight_layout()\n plt.show()\n\n def test_ivp_driver_4_segs_7_order(self):\n import openmdao.api as om\n import dymos as dm\n import matplotlib.pyplot as plt\n plt.switch_backend('Agg') # disable plotting to the screen\n\n from dymos.examples.oscillator.doc.oscillator_ode import OscillatorODE\n\n # Instantiate an OpenMDAO Problem instance.\n prob = om.Problem()\n\n # We need an optimization driver. To solve this simple problem ScipyOptimizerDriver will work.\n prob.driver = om.ScipyOptimizeDriver()\n\n # Instantiate a Dymos Trajectory and add it to the Problem model.\n traj = dm.Trajectory()\n prob.model.add_subsystem('traj', traj)\n\n # Instantiate a Phase and add it to the Trajectory.\n phase = dm.Phase(ode_class=OscillatorODE, transcription=dm.Radau(num_segments=4, order=7))\n traj.add_phase('phase0', phase)\n\n # Tell Dymos that the duration of the phase is bounded.\n phase.set_time_options(fix_initial=True, fix_duration=True)\n\n # Tell Dymos the states to be propagated using the given ODE.\n phase.add_state('x', fix_initial=True, rate_source='v', targets=['x'], units='m')\n phase.add_state('v', fix_initial=True, rate_source='v_dot', targets=['v'], units='m/s')\n\n # The spring constant, damping coefficient, and mass are inputs to the system that are\n # constant throughout the phase.\n phase.add_parameter('k', units='N/m', targets=['k'])\n phase.add_parameter('c', units='N*s/m', targets=['c'])\n phase.add_parameter('m', units='kg', targets=['m'])\n\n # Since we're using an optimization driver, an objective is required. We'll minimize\n # the final time in this case.\n phase.add_objective('time', loc='final')\n\n # Setup the OpenMDAO problem\n prob.setup()\n\n # Assign values to the times and states\n prob.set_val('traj.phase0.t_initial', 0.0)\n prob.set_val('traj.phase0.t_duration', 15.0)\n\n prob.set_val('traj.phase0.states:x', 10.0)\n prob.set_val('traj.phase0.states:v', 0.0)\n\n prob.set_val('traj.phase0.parameters:k', 1.0)\n prob.set_val('traj.phase0.parameters:c', 0.5)\n prob.set_val('traj.phase0.parameters:m', 1.0)\n\n # Now we're using the optimization driver to iteratively run the model and vary the\n # phase duration until the final y value is 0.\n prob.run_driver()\n\n # Perform an explicit simulation of our ODE from the initial conditions.\n sim_out = traj.simulate(times_per_seg=50)\n\n # Plot the state values obtained from the phase timeseries objects in the simulation output.\n t_sol = prob.get_val('traj.phase0.timeseries.time')\n t_sim = sim_out.get_val('traj.phase0.timeseries.time')\n\n states = ['x', 'v']\n fig, axes = plt.subplots(len(states), 1)\n for i, state in enumerate(states):\n sol = axes[i].plot(t_sol, prob.get_val(f'traj.phase0.timeseries.states:{state}'), 'o')\n sim = axes[i].plot(t_sim, sim_out.get_val(f'traj.phase0.timeseries.states:{state}'), '-')\n axes[i].set_ylabel(state)\n axes[-1].set_xlabel('time (s)')\n fig.legend((sol[0], sim[0]), ('solution', 'simulation'), 'lower right', ncol=2)\n plt.tight_layout()\n plt.show()\n\n def test_ivp_driver_run_problem(self):\n import openmdao.api as om\n import dymos as dm\n import matplotlib.pyplot as plt\n plt.switch_backend('Agg') # disable plotting to the screen\n\n from dymos.examples.oscillator.doc.oscillator_ode import OscillatorODE\n\n # Instantiate an OpenMDAO Problem instance.\n prob = om.Problem()\n\n # We need an optimization driver. To solve this simple problem ScipyOptimizerDriver will work.\n prob.driver = om.ScipyOptimizeDriver()\n\n # Instantiate a Dymos Trajectory and add it to the Problem model.\n traj = dm.Trajectory()\n prob.model.add_subsystem('traj', traj)\n\n # Instantiate a Phase and add it to the Trajectory.\n phase = dm.Phase(ode_class=OscillatorODE, transcription=dm.Radau(num_segments=4))\n traj.add_phase('phase0', phase)\n\n # Tell Dymos that the duration of the phase is bounded.\n phase.set_time_options(fix_initial=True, fix_duration=True)\n\n # Tell Dymos the states to be propagated using the given ODE.\n phase.add_state('x', fix_initial=True, rate_source='v', targets=['x'], units='m')\n phase.add_state('v', fix_initial=True, rate_source='v_dot', targets=['v'], units='m/s')\n\n # The spring constant, damping coefficient, and mass are inputs to the system that are\n # constant throughout the phase.\n phase.add_parameter('k', units='N/m', targets=['k'])\n phase.add_parameter('c', units='N*s/m', targets=['c'])\n phase.add_parameter('m', units='kg', targets=['m'])\n\n # Since we're using an optimization driver, an objective is required. We'll minimize\n # the final time in this case.\n phase.add_objective('time', loc='final')\n\n # Setup the OpenMDAO problem\n prob.setup()\n\n # Assign values to the times and states\n prob.set_val('traj.phase0.t_initial', 0.0)\n prob.set_val('traj.phase0.t_duration', 15.0)\n\n prob.set_val('traj.phase0.states:x', 10.0)\n prob.set_val('traj.phase0.states:v', 0.0)\n\n prob.set_val('traj.phase0.parameters:k', 1.0)\n prob.set_val('traj.phase0.parameters:c', 0.5)\n prob.set_val('traj.phase0.parameters:m', 1.0)\n\n # Now we're using the optimization driver to iteratively run the model and vary the\n # phase duration until the final y value is 0.\n dm.run_problem(prob)\n\n # Perform an explicit simulation of our ODE from the initial conditions.\n sim_out = traj.simulate(times_per_seg=50)\n\n # Plot the state values obtained from the phase timeseries objects in the simulation output.\n t_sol = prob.get_val('traj.phase0.timeseries.time')\n t_sim = sim_out.get_val('traj.phase0.timeseries.time')\n\n states = ['x', 'v']\n fig, axes = plt.subplots(len(states), 1)\n for i, state in enumerate(states):\n sol = axes[i].plot(t_sol, prob.get_val(f'traj.phase0.timeseries.states:{state}'), 'o')\n sim = axes[i].plot(t_sim, sim_out.get_val(f'traj.phase0.timeseries.states:{state}'), '-')\n axes[i].set_ylabel(state)\n axes[-1].set_xlabel('time (s)')\n fig.legend((sol[0], sim[0]), ('solution', 'simulation'), 'lower right', ncol=2)\n plt.tight_layout()\n plt.show()\n\n\nif __name__ == '__main__':\n unittest.main()\n"
] | [
[
"numpy.asarray",
"numpy.arange",
"numpy.broadcast_to",
"numpy.isscalar",
"numpy.prod"
],
[
"matplotlib.pyplot.switch_backend",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.show"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
CJL89/pandas | [
"6210077d32a9e9675526ea896e6d1f9189629d4a",
"6210077d32a9e9675526ea896e6d1f9189629d4a",
"6210077d32a9e9675526ea896e6d1f9189629d4a",
"6210077d32a9e9675526ea896e6d1f9189629d4a",
"6210077d32a9e9675526ea896e6d1f9189629d4a",
"6210077d32a9e9675526ea896e6d1f9189629d4a",
"6210077d32a9e9675526ea896e6d1f9189629d4a",
"6210077d32a9e9675526ea896e6d1f9189629d4a",
"6210077d32a9e9675526ea896e6d1f9189629d4a",
"6210077d32a9e9675526ea896e6d1f9189629d4a"
] | [
"pandas/tests/plotting/test_groupby.py",
"pandas/tests/indexes/multi/test_drop.py",
"pandas/tests/io/json/test_deprecated_kwargs.py",
"pandas/io/spss.py",
"asv_bench/benchmarks/reindex.py",
"pandas/tests/series/methods/test_diff.py",
"pandas/tests/extension/base/casting.py",
"pandas/tests/reshape/concat/test_append.py",
"pandas/tests/tslibs/test_parse_iso8601.py",
"pandas/tests/resample/test_timedelta.py"
] | [
"\"\"\" Test cases for GroupBy.plot \"\"\"\n\n\nimport numpy as np\nimport pytest\n\nfrom pandas.compat import is_platform_windows\nimport pandas.util._test_decorators as td\n\nfrom pandas import DataFrame, Index, Series\nimport pandas._testing as tm\nfrom pandas.tests.plotting.common import TestPlotBase\n\npytestmark = pytest.mark.slow\n\n\[email protected]_if_no_mpl\nclass TestDataFrameGroupByPlots(TestPlotBase):\n @pytest.mark.xfail(\n is_platform_windows(),\n reason=\"Looks like LinePlot._is_ts_plot is wrong\",\n strict=False,\n )\n def test_series_groupby_plotting_nominally_works(self):\n n = 10\n weight = Series(np.random.normal(166, 20, size=n))\n height = Series(np.random.normal(60, 10, size=n))\n with tm.RNGContext(42):\n gender = np.random.choice([\"male\", \"female\"], size=n)\n\n weight.groupby(gender).plot()\n tm.close()\n height.groupby(gender).hist()\n tm.close()\n # Regression test for GH8733\n height.groupby(gender).plot(alpha=0.5)\n tm.close()\n\n def test_plotting_with_float_index_works(self):\n # GH 7025\n df = DataFrame(\n {\"def\": [1, 1, 1, 2, 2, 2, 3, 3, 3], \"val\": np.random.randn(9)},\n index=[1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 2.0, 3.0],\n )\n\n df.groupby(\"def\")[\"val\"].plot()\n tm.close()\n df.groupby(\"def\")[\"val\"].apply(lambda x: x.plot())\n tm.close()\n\n def test_hist_single_row(self):\n # GH10214\n bins = np.arange(80, 100 + 2, 1)\n df = DataFrame({\"Name\": [\"AAA\", \"BBB\"], \"ByCol\": [1, 2], \"Mark\": [85, 89]})\n df[\"Mark\"].hist(by=df[\"ByCol\"], bins=bins)\n df = DataFrame({\"Name\": [\"AAA\"], \"ByCol\": [1], \"Mark\": [85]})\n df[\"Mark\"].hist(by=df[\"ByCol\"], bins=bins)\n\n def test_plot_submethod_works(self):\n df = DataFrame({\"x\": [1, 2, 3, 4, 5], \"y\": [1, 2, 3, 2, 1], \"z\": list(\"ababa\")})\n df.groupby(\"z\").plot.scatter(\"x\", \"y\")\n tm.close()\n df.groupby(\"z\")[\"x\"].plot.line()\n tm.close()\n\n def test_plot_kwargs(self):\n\n df = DataFrame({\"x\": [1, 2, 3, 4, 5], \"y\": [1, 2, 3, 2, 1], \"z\": list(\"ababa\")})\n\n res = df.groupby(\"z\").plot(kind=\"scatter\", x=\"x\", y=\"y\")\n # check that a scatter plot is effectively plotted: the axes should\n # contain a PathCollection from the scatter plot (GH11805)\n assert len(res[\"a\"].collections) == 1\n\n res = df.groupby(\"z\").plot.scatter(x=\"x\", y=\"y\")\n assert len(res[\"a\"].collections) == 1\n\n @pytest.mark.parametrize(\"column, expected_axes_num\", [(None, 2), (\"b\", 1)])\n def test_groupby_hist_frame_with_legend(self, column, expected_axes_num):\n # GH 6279 - DataFrameGroupBy histogram can have a legend\n expected_layout = (1, expected_axes_num)\n expected_labels = column or [[\"a\"], [\"b\"]]\n\n index = Index(15 * [\"1\"] + 15 * [\"2\"], name=\"c\")\n df = DataFrame(np.random.randn(30, 2), index=index, columns=[\"a\", \"b\"])\n g = df.groupby(\"c\")\n\n for axes in g.hist(legend=True, column=column):\n self._check_axes_shape(\n axes, axes_num=expected_axes_num, layout=expected_layout\n )\n for ax, expected_label in zip(axes[0], expected_labels):\n self._check_legend_labels(ax, expected_label)\n\n @pytest.mark.parametrize(\"column\", [None, \"b\"])\n def test_groupby_hist_frame_with_legend_raises(self, column):\n # GH 6279 - DataFrameGroupBy histogram with legend and label raises\n index = Index(15 * [\"1\"] + 15 * [\"2\"], name=\"c\")\n df = DataFrame(np.random.randn(30, 2), index=index, columns=[\"a\", \"b\"])\n g = df.groupby(\"c\")\n\n with pytest.raises(ValueError, match=\"Cannot use both legend and label\"):\n g.hist(legend=True, column=column, label=\"d\")\n\n def test_groupby_hist_series_with_legend(self):\n # GH 6279 - SeriesGroupBy histogram can have a legend\n index = Index(15 * [\"1\"] + 15 * [\"2\"], name=\"c\")\n df = DataFrame(np.random.randn(30, 2), index=index, columns=[\"a\", \"b\"])\n g = df.groupby(\"c\")\n\n for ax in g[\"a\"].hist(legend=True):\n self._check_axes_shape(ax, axes_num=1, layout=(1, 1))\n self._check_legend_labels(ax, [\"1\", \"2\"])\n\n def test_groupby_hist_series_with_legend_raises(self):\n # GH 6279 - SeriesGroupBy histogram with legend and label raises\n index = Index(15 * [\"1\"] + 15 * [\"2\"], name=\"c\")\n df = DataFrame(np.random.randn(30, 2), index=index, columns=[\"a\", \"b\"])\n g = df.groupby(\"c\")\n\n with pytest.raises(ValueError, match=\"Cannot use both legend and label\"):\n g.hist(legend=True, label=\"d\")\n",
"import warnings\n\nimport numpy as np\nimport pytest\n\nfrom pandas.errors import PerformanceWarning\n\nimport pandas as pd\nfrom pandas import Index, MultiIndex\nimport pandas._testing as tm\n\n\ndef test_drop(idx):\n dropped = idx.drop([(\"foo\", \"two\"), (\"qux\", \"one\")])\n\n index = MultiIndex.from_tuples([(\"foo\", \"two\"), (\"qux\", \"one\")])\n dropped2 = idx.drop(index)\n\n expected = idx[[0, 2, 3, 5]]\n tm.assert_index_equal(dropped, expected)\n tm.assert_index_equal(dropped2, expected)\n\n dropped = idx.drop([\"bar\"])\n expected = idx[[0, 1, 3, 4, 5]]\n tm.assert_index_equal(dropped, expected)\n\n dropped = idx.drop(\"foo\")\n expected = idx[[2, 3, 4, 5]]\n tm.assert_index_equal(dropped, expected)\n\n index = MultiIndex.from_tuples([(\"bar\", \"two\")])\n with pytest.raises(KeyError, match=r\"^10$\"):\n idx.drop([(\"bar\", \"two\")])\n with pytest.raises(KeyError, match=r\"^10$\"):\n idx.drop(index)\n with pytest.raises(KeyError, match=r\"^'two'$\"):\n idx.drop([\"foo\", \"two\"])\n\n # partially correct argument\n mixed_index = MultiIndex.from_tuples([(\"qux\", \"one\"), (\"bar\", \"two\")])\n with pytest.raises(KeyError, match=r\"^10$\"):\n idx.drop(mixed_index)\n\n # error='ignore'\n dropped = idx.drop(index, errors=\"ignore\")\n expected = idx[[0, 1, 2, 3, 4, 5]]\n tm.assert_index_equal(dropped, expected)\n\n dropped = idx.drop(mixed_index, errors=\"ignore\")\n expected = idx[[0, 1, 2, 3, 5]]\n tm.assert_index_equal(dropped, expected)\n\n dropped = idx.drop([\"foo\", \"two\"], errors=\"ignore\")\n expected = idx[[2, 3, 4, 5]]\n tm.assert_index_equal(dropped, expected)\n\n # mixed partial / full drop\n dropped = idx.drop([\"foo\", (\"qux\", \"one\")])\n expected = idx[[2, 3, 5]]\n tm.assert_index_equal(dropped, expected)\n\n # mixed partial / full drop / error='ignore'\n mixed_index = [\"foo\", (\"qux\", \"one\"), \"two\"]\n with pytest.raises(KeyError, match=r\"^'two'$\"):\n idx.drop(mixed_index)\n dropped = idx.drop(mixed_index, errors=\"ignore\")\n expected = idx[[2, 3, 5]]\n tm.assert_index_equal(dropped, expected)\n\n\ndef test_droplevel_with_names(idx):\n index = idx[idx.get_loc(\"foo\")]\n dropped = index.droplevel(0)\n assert dropped.name == \"second\"\n\n index = MultiIndex(\n levels=[Index(range(4)), Index(range(4)), Index(range(4))],\n codes=[\n np.array([0, 0, 1, 2, 2, 2, 3, 3]),\n np.array([0, 1, 0, 0, 0, 1, 0, 1]),\n np.array([1, 0, 1, 1, 0, 0, 1, 0]),\n ],\n names=[\"one\", \"two\", \"three\"],\n )\n dropped = index.droplevel(0)\n assert dropped.names == (\"two\", \"three\")\n\n dropped = index.droplevel(\"two\")\n expected = index.droplevel(1)\n assert dropped.equals(expected)\n\n\ndef test_droplevel_list():\n index = MultiIndex(\n levels=[Index(range(4)), Index(range(4)), Index(range(4))],\n codes=[\n np.array([0, 0, 1, 2, 2, 2, 3, 3]),\n np.array([0, 1, 0, 0, 0, 1, 0, 1]),\n np.array([1, 0, 1, 1, 0, 0, 1, 0]),\n ],\n names=[\"one\", \"two\", \"three\"],\n )\n\n dropped = index[:2].droplevel([\"three\", \"one\"])\n expected = index[:2].droplevel(2).droplevel(0)\n assert dropped.equals(expected)\n\n dropped = index[:2].droplevel([])\n expected = index[:2]\n assert dropped.equals(expected)\n\n msg = (\n \"Cannot remove 3 levels from an index with 3 levels: \"\n \"at least one level must be left\"\n )\n with pytest.raises(ValueError, match=msg):\n index[:2].droplevel([\"one\", \"two\", \"three\"])\n\n with pytest.raises(KeyError, match=\"'Level four not found'\"):\n index[:2].droplevel([\"one\", \"four\"])\n\n\ndef test_drop_not_lexsorted():\n # GH 12078\n\n # define the lexsorted version of the multi-index\n tuples = [(\"a\", \"\"), (\"b1\", \"c1\"), (\"b2\", \"c2\")]\n lexsorted_mi = MultiIndex.from_tuples(tuples, names=[\"b\", \"c\"])\n assert lexsorted_mi.is_lexsorted()\n\n # and the not-lexsorted version\n df = pd.DataFrame(\n columns=[\"a\", \"b\", \"c\", \"d\"], data=[[1, \"b1\", \"c1\", 3], [1, \"b2\", \"c2\", 4]]\n )\n df = df.pivot_table(index=\"a\", columns=[\"b\", \"c\"], values=\"d\")\n df = df.reset_index()\n not_lexsorted_mi = df.columns\n assert not not_lexsorted_mi.is_lexsorted()\n\n # compare the results\n tm.assert_index_equal(lexsorted_mi, not_lexsorted_mi)\n with tm.assert_produces_warning(PerformanceWarning):\n tm.assert_index_equal(lexsorted_mi.drop(\"a\"), not_lexsorted_mi.drop(\"a\"))\n\n\ndef test_drop_with_nan_in_index(nulls_fixture):\n # GH#18853\n mi = MultiIndex.from_tuples([(\"blah\", nulls_fixture)], names=[\"name\", \"date\"])\n msg = r\"labels \\[Timestamp\\('2001-01-01 00:00:00'\\)\\] not found in level\"\n with pytest.raises(KeyError, match=msg):\n mi.drop(pd.Timestamp(\"2001\"), level=\"date\")\n\n\ndef test_drop_with_non_monotonic_duplicates():\n # GH#33494\n mi = MultiIndex.from_tuples([(1, 2), (2, 3), (1, 2)])\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", PerformanceWarning)\n result = mi.drop((1, 2))\n expected = MultiIndex.from_tuples([(2, 3)])\n tm.assert_index_equal(result, expected)\n\n\ndef test_single_level_drop_partially_missing_elements():\n # GH 37820\n\n mi = MultiIndex.from_tuples([(1, 2), (2, 2), (3, 2)])\n msg = r\"labels \\[4\\] not found in level\"\n with pytest.raises(KeyError, match=msg):\n mi.drop(4, level=0)\n with pytest.raises(KeyError, match=msg):\n mi.drop([1, 4], level=0)\n msg = r\"labels \\[nan\\] not found in level\"\n with pytest.raises(KeyError, match=msg):\n mi.drop([np.nan], level=0)\n with pytest.raises(KeyError, match=msg):\n mi.drop([np.nan, 1, 2, 3], level=0)\n\n mi = MultiIndex.from_tuples([(np.nan, 1), (1, 2)])\n msg = r\"labels \\['a'\\] not found in level\"\n with pytest.raises(KeyError, match=msg):\n mi.drop([np.nan, 1, \"a\"], level=0)\n",
"\"\"\"\nTests for the deprecated keyword arguments for `read_json`.\n\"\"\"\n\nimport pandas as pd\nimport pandas._testing as tm\n\nfrom pandas.io.json import read_json\n\n\ndef test_deprecated_kwargs():\n df = pd.DataFrame({\"A\": [2, 4, 6], \"B\": [3, 6, 9]}, index=[0, 1, 2])\n buf = df.to_json(orient=\"split\")\n with tm.assert_produces_warning(FutureWarning):\n tm.assert_frame_equal(df, read_json(buf, \"split\"))\n buf = df.to_json(orient=\"columns\")\n with tm.assert_produces_warning(FutureWarning):\n tm.assert_frame_equal(df, read_json(buf, \"columns\"))\n buf = df.to_json(orient=\"index\")\n with tm.assert_produces_warning(FutureWarning):\n tm.assert_frame_equal(df, read_json(buf, \"index\"))\n\n\ndef test_good_kwargs():\n df = pd.DataFrame({\"A\": [2, 4, 6], \"B\": [3, 6, 9]}, index=[0, 1, 2])\n with tm.assert_produces_warning(None):\n tm.assert_frame_equal(df, read_json(df.to_json(orient=\"split\"), orient=\"split\"))\n tm.assert_frame_equal(\n df, read_json(df.to_json(orient=\"columns\"), orient=\"columns\")\n )\n tm.assert_frame_equal(df, read_json(df.to_json(orient=\"index\"), orient=\"index\"))\n",
"from pathlib import Path\nfrom typing import Optional, Sequence, Union\n\nfrom pandas.compat._optional import import_optional_dependency\n\nfrom pandas.core.dtypes.inference import is_list_like\n\nfrom pandas.core.api import DataFrame\n\nfrom pandas.io.common import stringify_path\n\n\ndef read_spss(\n path: Union[str, Path],\n usecols: Optional[Sequence[str]] = None,\n convert_categoricals: bool = True,\n) -> DataFrame:\n \"\"\"\n Load an SPSS file from the file path, returning a DataFrame.\n\n .. versionadded:: 0.25.0\n\n Parameters\n ----------\n path : str or Path\n File path.\n usecols : list-like, optional\n Return a subset of the columns. If None, return all columns.\n convert_categoricals : bool, default is True\n Convert categorical columns into pd.Categorical.\n\n Returns\n -------\n DataFrame\n \"\"\"\n pyreadstat = import_optional_dependency(\"pyreadstat\")\n\n if usecols is not None:\n if not is_list_like(usecols):\n raise TypeError(\"usecols must be list-like.\")\n else:\n usecols = list(usecols) # pyreadstat requires a list\n\n df, _ = pyreadstat.read_sav(\n stringify_path(path), usecols=usecols, apply_value_formats=convert_categoricals\n )\n return df\n",
"import numpy as np\n\nfrom pandas import DataFrame, Index, MultiIndex, Series, date_range, period_range\n\nfrom .pandas_vb_common import lib, tm\n\n\nclass Reindex:\n def setup(self):\n rng = date_range(start=\"1/1/1970\", periods=10000, freq=\"1min\")\n self.df = DataFrame(np.random.rand(10000, 10), index=rng, columns=range(10))\n self.df[\"foo\"] = \"bar\"\n self.rng_subset = Index(rng[::2])\n self.df2 = DataFrame(\n index=range(10000), data=np.random.rand(10000, 30), columns=range(30)\n )\n N = 5000\n K = 200\n level1 = tm.makeStringIndex(N).values.repeat(K)\n level2 = np.tile(tm.makeStringIndex(K).values, N)\n index = MultiIndex.from_arrays([level1, level2])\n self.s = Series(np.random.randn(N * K), index=index)\n self.s_subset = self.s[::2]\n\n def time_reindex_dates(self):\n self.df.reindex(self.rng_subset)\n\n def time_reindex_columns(self):\n self.df2.reindex(columns=self.df.columns[1:5])\n\n def time_reindex_multiindex(self):\n self.s.reindex(self.s_subset.index)\n\n\nclass ReindexMethod:\n\n params = [[\"pad\", \"backfill\"], [date_range, period_range]]\n param_names = [\"method\", \"constructor\"]\n\n def setup(self, method, constructor):\n N = 100000\n self.idx = constructor(\"1/1/2000\", periods=N, freq=\"1min\")\n self.ts = Series(np.random.randn(N), index=self.idx)[::2]\n\n def time_reindex_method(self, method, constructor):\n self.ts.reindex(self.idx, method=method)\n\n\nclass Fillna:\n\n params = [\"pad\", \"backfill\"]\n param_names = [\"method\"]\n\n def setup(self, method):\n N = 100000\n self.idx = date_range(\"1/1/2000\", periods=N, freq=\"1min\")\n ts = Series(np.random.randn(N), index=self.idx)[::2]\n self.ts_reindexed = ts.reindex(self.idx)\n self.ts_float32 = self.ts_reindexed.astype(\"float32\")\n\n def time_reindexed(self, method):\n self.ts_reindexed.fillna(method=method)\n\n def time_float_32(self, method):\n self.ts_float32.fillna(method=method)\n\n\nclass LevelAlign:\n def setup(self):\n self.index = MultiIndex(\n levels=[np.arange(10), np.arange(100), np.arange(100)],\n codes=[\n np.arange(10).repeat(10000),\n np.tile(np.arange(100).repeat(100), 10),\n np.tile(np.tile(np.arange(100), 100), 10),\n ],\n )\n self.df = DataFrame(np.random.randn(len(self.index), 4), index=self.index)\n self.df_level = DataFrame(np.random.randn(100, 4), index=self.index.levels[1])\n\n def time_align_level(self):\n self.df.align(self.df_level, level=1, copy=False)\n\n def time_reindex_level(self):\n self.df_level.reindex(self.index, level=1)\n\n\nclass DropDuplicates:\n\n params = [True, False]\n param_names = [\"inplace\"]\n\n def setup(self, inplace):\n N = 10000\n K = 10\n key1 = tm.makeStringIndex(N).values.repeat(K)\n key2 = tm.makeStringIndex(N).values.repeat(K)\n self.df = DataFrame(\n {\"key1\": key1, \"key2\": key2, \"value\": np.random.randn(N * K)}\n )\n self.df_nan = self.df.copy()\n self.df_nan.iloc[:10000, :] = np.nan\n\n self.s = Series(np.random.randint(0, 1000, size=10000))\n self.s_str = Series(np.tile(tm.makeStringIndex(1000).values, 10))\n\n N = 1000000\n K = 10000\n key1 = np.random.randint(0, K, size=N)\n self.df_int = DataFrame({\"key1\": key1})\n self.df_bool = DataFrame(np.random.randint(0, 2, size=(K, 10), dtype=bool))\n\n def time_frame_drop_dups(self, inplace):\n self.df.drop_duplicates([\"key1\", \"key2\"], inplace=inplace)\n\n def time_frame_drop_dups_na(self, inplace):\n self.df_nan.drop_duplicates([\"key1\", \"key2\"], inplace=inplace)\n\n def time_series_drop_dups_int(self, inplace):\n self.s.drop_duplicates(inplace=inplace)\n\n def time_series_drop_dups_string(self, inplace):\n self.s_str.drop_duplicates(inplace=inplace)\n\n def time_frame_drop_dups_int(self, inplace):\n self.df_int.drop_duplicates(inplace=inplace)\n\n def time_frame_drop_dups_bool(self, inplace):\n self.df_bool.drop_duplicates(inplace=inplace)\n\n\nclass Align:\n # blog \"pandas escaped the zoo\"\n def setup(self):\n n = 50000\n indices = tm.makeStringIndex(n)\n subsample_size = 40000\n self.x = Series(np.random.randn(n), indices)\n self.y = Series(\n np.random.randn(subsample_size),\n index=np.random.choice(indices, subsample_size, replace=False),\n )\n\n def time_align_series_irregular_string(self):\n self.x + self.y\n\n\nclass LibFastZip:\n def setup(self):\n N = 10000\n K = 10\n key1 = tm.makeStringIndex(N).values.repeat(K)\n key2 = tm.makeStringIndex(N).values.repeat(K)\n col_array = np.vstack([key1, key2, np.random.randn(N * K)])\n col_array2 = col_array.copy()\n col_array2[:, :10000] = np.nan\n self.col_array_list = list(col_array)\n\n def time_lib_fast_zip(self):\n lib.fast_zip(self.col_array_list)\n\n\nfrom .pandas_vb_common import setup # noqa: F401 isort:skip\n",
"import numpy as np\nimport pytest\n\nfrom pandas import Series, TimedeltaIndex, date_range\nimport pandas._testing as tm\n\n\nclass TestSeriesDiff:\n def test_diff_np(self):\n pytest.skip(\"skipping due to Series no longer being an ndarray\")\n\n # no longer works as the return type of np.diff is now nd.array\n s = Series(np.arange(5))\n\n r = np.diff(s)\n tm.assert_series_equal(Series([np.nan, 0, 0, 0, np.nan]), r)\n\n def test_diff_int(self):\n # int dtype\n a = 10000000000000000\n b = a + 1\n s = Series([a, b])\n\n result = s.diff()\n assert result[1] == 1\n\n def test_diff_tz(self):\n # Combined datetime diff, normal diff and boolean diff test\n ts = tm.makeTimeSeries(name=\"ts\")\n ts.diff()\n\n # neg n\n result = ts.diff(-1)\n expected = ts - ts.shift(-1)\n tm.assert_series_equal(result, expected)\n\n # 0\n result = ts.diff(0)\n expected = ts - ts\n tm.assert_series_equal(result, expected)\n\n # datetime diff (GH#3100)\n s = Series(date_range(\"20130102\", periods=5))\n result = s.diff()\n expected = s - s.shift(1)\n tm.assert_series_equal(result, expected)\n\n # timedelta diff\n result = result - result.shift(1) # previous result\n expected = expected.diff() # previously expected\n tm.assert_series_equal(result, expected)\n\n # with tz\n s = Series(\n date_range(\"2000-01-01 09:00:00\", periods=5, tz=\"US/Eastern\"), name=\"foo\"\n )\n result = s.diff()\n expected = Series(TimedeltaIndex([\"NaT\"] + [\"1 days\"] * 4), name=\"foo\")\n tm.assert_series_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"input,output,diff\",\n [([False, True, True, False, False], [np.nan, True, False, True, False], 1)],\n )\n def test_diff_bool(self, input, output, diff):\n # boolean series (test for fixing #17294)\n s = Series(input)\n result = s.diff()\n expected = Series(output)\n tm.assert_series_equal(result, expected)\n\n def test_diff_object_dtype(self):\n # object series\n s = Series([False, True, 5.0, np.nan, True, False])\n result = s.diff()\n expected = s - s.shift(1)\n tm.assert_series_equal(result, expected)\n",
"import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas.core.internals import ObjectBlock\n\nfrom .base import BaseExtensionTests\n\n\nclass BaseCastingTests(BaseExtensionTests):\n \"\"\"Casting to and from ExtensionDtypes\"\"\"\n\n def test_astype_object_series(self, all_data):\n ser = pd.Series(all_data, name=\"A\")\n result = ser.astype(object)\n assert isinstance(result._mgr.blocks[0], ObjectBlock)\n\n def test_astype_object_frame(self, all_data):\n df = pd.DataFrame({\"A\": all_data})\n\n result = df.astype(object)\n blk = result._data.blocks[0]\n assert isinstance(blk, ObjectBlock), type(blk)\n\n # FIXME: these currently fail; dont leave commented-out\n # check that we can compare the dtypes\n # cmp = result.dtypes.equals(df.dtypes)\n # assert not cmp.any()\n\n def test_tolist(self, data):\n result = pd.Series(data).tolist()\n expected = list(data)\n assert result == expected\n\n def test_astype_str(self, data):\n result = pd.Series(data[:5]).astype(str)\n expected = pd.Series([str(x) for x in data[:5]], dtype=str)\n self.assert_series_equal(result, expected)\n\n def test_astype_string(self, data):\n # GH-33465\n result = pd.Series(data[:5]).astype(\"string\")\n expected = pd.Series([str(x) for x in data[:5]], dtype=\"string\")\n self.assert_series_equal(result, expected)\n\n def test_to_numpy(self, data):\n expected = np.asarray(data)\n\n result = data.to_numpy()\n self.assert_equal(result, expected)\n\n result = pd.Series(data).to_numpy()\n self.assert_equal(result, expected)\n\n def test_astype_empty_dataframe(self, dtype):\n # https://github.com/pandas-dev/pandas/issues/33113\n df = pd.DataFrame()\n result = df.astype(dtype)\n self.assert_frame_equal(result, df)\n\n @pytest.mark.parametrize(\"copy\", [True, False])\n def test_astype_own_type(self, data, copy):\n # ensure that astype returns the original object for equal dtype and copy=False\n # https://github.com/pandas-dev/pandas/issues/28488\n result = data.astype(data.dtype, copy=copy)\n assert (result is data) is (not copy)\n self.assert_extension_array_equal(result, data)\n",
"import datetime as dt\nfrom datetime import datetime\nfrom itertools import combinations\n\nimport dateutil\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import DataFrame, Index, Series, Timestamp, concat, isna\nimport pandas._testing as tm\n\n\nclass TestAppend:\n def test_append(self, sort, float_frame):\n mixed_frame = float_frame.copy()\n mixed_frame[\"foo\"] = \"bar\"\n\n begin_index = float_frame.index[:5]\n end_index = float_frame.index[5:]\n\n begin_frame = float_frame.reindex(begin_index)\n end_frame = float_frame.reindex(end_index)\n\n appended = begin_frame.append(end_frame)\n tm.assert_almost_equal(appended[\"A\"], float_frame[\"A\"])\n\n del end_frame[\"A\"]\n partial_appended = begin_frame.append(end_frame, sort=sort)\n assert \"A\" in partial_appended\n\n partial_appended = end_frame.append(begin_frame, sort=sort)\n assert \"A\" in partial_appended\n\n # mixed type handling\n appended = mixed_frame[:5].append(mixed_frame[5:])\n tm.assert_frame_equal(appended, mixed_frame)\n\n # what to test here\n mixed_appended = mixed_frame[:5].append(float_frame[5:], sort=sort)\n mixed_appended2 = float_frame[:5].append(mixed_frame[5:], sort=sort)\n\n # all equal except 'foo' column\n tm.assert_frame_equal(\n mixed_appended.reindex(columns=[\"A\", \"B\", \"C\", \"D\"]),\n mixed_appended2.reindex(columns=[\"A\", \"B\", \"C\", \"D\"]),\n )\n\n def test_append_empty(self, float_frame):\n empty = DataFrame()\n\n appended = float_frame.append(empty)\n tm.assert_frame_equal(float_frame, appended)\n assert appended is not float_frame\n\n appended = empty.append(float_frame)\n tm.assert_frame_equal(float_frame, appended)\n assert appended is not float_frame\n\n def test_append_overlap_raises(self, float_frame):\n msg = \"Indexes have overlapping values\"\n with pytest.raises(ValueError, match=msg):\n float_frame.append(float_frame, verify_integrity=True)\n\n def test_append_new_columns(self):\n # see gh-6129: new columns\n df = DataFrame({\"a\": {\"x\": 1, \"y\": 2}, \"b\": {\"x\": 3, \"y\": 4}})\n row = Series([5, 6, 7], index=[\"a\", \"b\", \"c\"], name=\"z\")\n expected = DataFrame(\n {\n \"a\": {\"x\": 1, \"y\": 2, \"z\": 5},\n \"b\": {\"x\": 3, \"y\": 4, \"z\": 6},\n \"c\": {\"z\": 7},\n }\n )\n result = df.append(row)\n tm.assert_frame_equal(result, expected)\n\n def test_append_length0_frame(self, sort):\n df = DataFrame(columns=[\"A\", \"B\", \"C\"])\n df3 = DataFrame(index=[0, 1], columns=[\"A\", \"B\"])\n df5 = df.append(df3, sort=sort)\n\n expected = DataFrame(index=[0, 1], columns=[\"A\", \"B\", \"C\"])\n tm.assert_frame_equal(df5, expected)\n\n def test_append_records(self):\n arr1 = np.zeros((2,), dtype=(\"i4,f4,a10\"))\n arr1[:] = [(1, 2.0, \"Hello\"), (2, 3.0, \"World\")]\n\n arr2 = np.zeros((3,), dtype=(\"i4,f4,a10\"))\n arr2[:] = [(3, 4.0, \"foo\"), (5, 6.0, \"bar\"), (7.0, 8.0, \"baz\")]\n\n df1 = DataFrame(arr1)\n df2 = DataFrame(arr2)\n\n result = df1.append(df2, ignore_index=True)\n expected = DataFrame(np.concatenate((arr1, arr2)))\n tm.assert_frame_equal(result, expected)\n\n # rewrite sort fixture, since we also want to test default of None\n def test_append_sorts(self, sort):\n df1 = DataFrame({\"a\": [1, 2], \"b\": [1, 2]}, columns=[\"b\", \"a\"])\n df2 = DataFrame({\"a\": [1, 2], \"c\": [3, 4]}, index=[2, 3])\n\n with tm.assert_produces_warning(None):\n result = df1.append(df2, sort=sort)\n\n # for None / True\n expected = DataFrame(\n {\"b\": [1, 2, None, None], \"a\": [1, 2, 1, 2], \"c\": [None, None, 3, 4]},\n columns=[\"a\", \"b\", \"c\"],\n )\n if sort is False:\n expected = expected[[\"b\", \"a\", \"c\"]]\n tm.assert_frame_equal(result, expected)\n\n def test_append_different_columns(self, sort):\n df = DataFrame(\n {\n \"bools\": np.random.randn(10) > 0,\n \"ints\": np.random.randint(0, 10, 10),\n \"floats\": np.random.randn(10),\n \"strings\": [\"foo\", \"bar\"] * 5,\n }\n )\n\n a = df[:5].loc[:, [\"bools\", \"ints\", \"floats\"]]\n b = df[5:].loc[:, [\"strings\", \"ints\", \"floats\"]]\n\n appended = a.append(b, sort=sort)\n assert isna(appended[\"strings\"][0:4]).all()\n assert isna(appended[\"bools\"][5:]).all()\n\n def test_append_many(self, sort, float_frame):\n chunks = [\n float_frame[:5],\n float_frame[5:10],\n float_frame[10:15],\n float_frame[15:],\n ]\n\n result = chunks[0].append(chunks[1:])\n tm.assert_frame_equal(result, float_frame)\n\n chunks[-1] = chunks[-1].copy()\n chunks[-1][\"foo\"] = \"bar\"\n result = chunks[0].append(chunks[1:], sort=sort)\n tm.assert_frame_equal(result.loc[:, float_frame.columns], float_frame)\n assert (result[\"foo\"][15:] == \"bar\").all()\n assert result[\"foo\"][:15].isna().all()\n\n def test_append_preserve_index_name(self):\n # #980\n df1 = DataFrame(columns=[\"A\", \"B\", \"C\"])\n df1 = df1.set_index([\"A\"])\n df2 = DataFrame(data=[[1, 4, 7], [2, 5, 8], [3, 6, 9]], columns=[\"A\", \"B\", \"C\"])\n df2 = df2.set_index([\"A\"])\n\n result = df1.append(df2)\n assert result.index.name == \"A\"\n\n indexes_can_append = [\n pd.RangeIndex(3),\n Index([4, 5, 6]),\n Index([4.5, 5.5, 6.5]),\n Index(list(\"abc\")),\n pd.CategoricalIndex(\"A B C\".split()),\n pd.CategoricalIndex(\"D E F\".split(), ordered=True),\n pd.IntervalIndex.from_breaks([7, 8, 9, 10]),\n pd.DatetimeIndex(\n [\n dt.datetime(2013, 1, 3, 0, 0),\n dt.datetime(2013, 1, 3, 6, 10),\n dt.datetime(2013, 1, 3, 7, 12),\n ]\n ),\n ]\n\n indexes_cannot_append_with_other = [\n pd.MultiIndex.from_arrays([\"A B C\".split(), \"D E F\".split()])\n ]\n\n all_indexes = indexes_can_append + indexes_cannot_append_with_other\n\n @pytest.mark.parametrize(\"index\", all_indexes, ids=lambda x: type(x).__name__)\n def test_append_same_columns_type(self, index):\n # GH18359\n\n # df wider than ser\n df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=index)\n ser_index = index[:2]\n ser = Series([7, 8], index=ser_index, name=2)\n result = df.append(ser)\n expected = DataFrame(\n [[1.0, 2.0, 3.0], [4, 5, 6], [7, 8, np.nan]], index=[0, 1, 2], columns=index\n )\n tm.assert_frame_equal(result, expected)\n\n # ser wider than df\n ser_index = index\n index = index[:2]\n df = DataFrame([[1, 2], [4, 5]], columns=index)\n ser = Series([7, 8, 9], index=ser_index, name=2)\n result = df.append(ser)\n expected = DataFrame(\n [[1, 2, np.nan], [4, 5, np.nan], [7, 8, 9]],\n index=[0, 1, 2],\n columns=ser_index,\n )\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"df_columns, series_index\",\n combinations(indexes_can_append, r=2),\n ids=lambda x: type(x).__name__,\n )\n def test_append_different_columns_types(self, df_columns, series_index):\n # GH18359\n # See also test 'test_append_different_columns_types_raises' below\n # for errors raised when appending\n\n df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=df_columns)\n ser = Series([7, 8, 9], index=series_index, name=2)\n\n result = df.append(ser)\n idx_diff = ser.index.difference(df_columns)\n combined_columns = Index(df_columns.tolist()).append(idx_diff)\n expected = DataFrame(\n [\n [1.0, 2.0, 3.0, np.nan, np.nan, np.nan],\n [4, 5, 6, np.nan, np.nan, np.nan],\n [np.nan, np.nan, np.nan, 7, 8, 9],\n ],\n index=[0, 1, 2],\n columns=combined_columns,\n )\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"index_can_append\", indexes_can_append, ids=lambda x: type(x).__name__\n )\n @pytest.mark.parametrize(\n \"index_cannot_append_with_other\",\n indexes_cannot_append_with_other,\n ids=lambda x: type(x).__name__,\n )\n def test_append_different_columns_types_raises(\n self, index_can_append, index_cannot_append_with_other\n ):\n # GH18359\n # Dataframe.append will raise if MultiIndex appends\n # or is appended to a different index type\n #\n # See also test 'test_append_different_columns_types' above for\n # appending without raising.\n\n df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=index_can_append)\n ser = Series([7, 8, 9], index=index_cannot_append_with_other, name=2)\n msg = (\n r\"Expected tuple, got (int|long|float|str|\"\n r\"pandas._libs.interval.Interval)|\"\n r\"object of type '(int|float|Timestamp|\"\n r\"pandas._libs.interval.Interval)' has no len\\(\\)|\"\n )\n with pytest.raises(TypeError, match=msg):\n df.append(ser)\n\n df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=index_cannot_append_with_other)\n ser = Series([7, 8, 9], index=index_can_append, name=2)\n\n with pytest.raises(TypeError, match=msg):\n df.append(ser)\n\n def test_append_dtype_coerce(self, sort):\n\n # GH 4993\n # appending with datetime will incorrectly convert datetime64\n\n df1 = DataFrame(\n index=[1, 2],\n data=[dt.datetime(2013, 1, 1, 0, 0), dt.datetime(2013, 1, 2, 0, 0)],\n columns=[\"start_time\"],\n )\n df2 = DataFrame(\n index=[4, 5],\n data=[\n [dt.datetime(2013, 1, 3, 0, 0), dt.datetime(2013, 1, 3, 6, 10)],\n [dt.datetime(2013, 1, 4, 0, 0), dt.datetime(2013, 1, 4, 7, 10)],\n ],\n columns=[\"start_time\", \"end_time\"],\n )\n\n expected = concat(\n [\n Series(\n [\n pd.NaT,\n pd.NaT,\n dt.datetime(2013, 1, 3, 6, 10),\n dt.datetime(2013, 1, 4, 7, 10),\n ],\n name=\"end_time\",\n ),\n Series(\n [\n dt.datetime(2013, 1, 1, 0, 0),\n dt.datetime(2013, 1, 2, 0, 0),\n dt.datetime(2013, 1, 3, 0, 0),\n dt.datetime(2013, 1, 4, 0, 0),\n ],\n name=\"start_time\",\n ),\n ],\n axis=1,\n sort=sort,\n )\n result = df1.append(df2, ignore_index=True, sort=sort)\n if sort:\n expected = expected[[\"end_time\", \"start_time\"]]\n else:\n expected = expected[[\"start_time\", \"end_time\"]]\n\n tm.assert_frame_equal(result, expected)\n\n def test_append_missing_column_proper_upcast(self, sort):\n df1 = DataFrame({\"A\": np.array([1, 2, 3, 4], dtype=\"i8\")})\n df2 = DataFrame({\"B\": np.array([True, False, True, False], dtype=bool)})\n\n appended = df1.append(df2, ignore_index=True, sort=sort)\n assert appended[\"A\"].dtype == \"f8\"\n assert appended[\"B\"].dtype == \"O\"\n\n def test_append_empty_frame_to_series_with_dateutil_tz(self):\n # GH 23682\n date = Timestamp(\"2018-10-24 07:30:00\", tz=dateutil.tz.tzutc())\n s = Series({\"date\": date, \"a\": 1.0, \"b\": 2.0})\n df = DataFrame(columns=[\"c\", \"d\"])\n result_a = df.append(s, ignore_index=True)\n expected = DataFrame(\n [[np.nan, np.nan, 1.0, 2.0, date]], columns=[\"c\", \"d\", \"a\", \"b\", \"date\"]\n )\n # These columns get cast to object after append\n expected[\"c\"] = expected[\"c\"].astype(object)\n expected[\"d\"] = expected[\"d\"].astype(object)\n tm.assert_frame_equal(result_a, expected)\n\n expected = DataFrame(\n [[np.nan, np.nan, 1.0, 2.0, date]] * 2, columns=[\"c\", \"d\", \"a\", \"b\", \"date\"]\n )\n expected[\"c\"] = expected[\"c\"].astype(object)\n expected[\"d\"] = expected[\"d\"].astype(object)\n\n result_b = result_a.append(s, ignore_index=True)\n tm.assert_frame_equal(result_b, expected)\n\n # column order is different\n expected = expected[[\"c\", \"d\", \"date\", \"a\", \"b\"]]\n result = df.append([s, s], ignore_index=True)\n tm.assert_frame_equal(result, expected)\n\n def test_append_empty_tz_frame_with_datetime64ns(self):\n # https://github.com/pandas-dev/pandas/issues/35460\n df = DataFrame(columns=[\"a\"]).astype(\"datetime64[ns, UTC]\")\n\n # pd.NaT gets inferred as tz-naive, so append result is tz-naive\n result = df.append({\"a\": pd.NaT}, ignore_index=True)\n expected = DataFrame({\"a\": [pd.NaT]}).astype(\"datetime64[ns]\")\n tm.assert_frame_equal(result, expected)\n\n # also test with typed value to append\n df = DataFrame(columns=[\"a\"]).astype(\"datetime64[ns, UTC]\")\n result = df.append(\n Series({\"a\": pd.NaT}, dtype=\"datetime64[ns]\"), ignore_index=True\n )\n expected = DataFrame({\"a\": [pd.NaT]}).astype(\"datetime64[ns]\")\n tm.assert_frame_equal(result, expected)\n",
"from datetime import datetime\n\nimport pytest\n\nfrom pandas._libs import tslib\n\n\[email protected](\n \"date_str, exp\",\n [\n (\"2011-01-02\", datetime(2011, 1, 2)),\n (\"2011-1-2\", datetime(2011, 1, 2)),\n (\"2011-01\", datetime(2011, 1, 1)),\n (\"2011-1\", datetime(2011, 1, 1)),\n (\"2011 01 02\", datetime(2011, 1, 2)),\n (\"2011.01.02\", datetime(2011, 1, 2)),\n (\"2011/01/02\", datetime(2011, 1, 2)),\n (\"2011\\\\01\\\\02\", datetime(2011, 1, 2)),\n (\"2013-01-01 05:30:00\", datetime(2013, 1, 1, 5, 30)),\n (\"2013-1-1 5:30:00\", datetime(2013, 1, 1, 5, 30)),\n ],\n)\ndef test_parsers_iso8601(date_str, exp):\n # see gh-12060\n #\n # Test only the ISO parser - flexibility to\n # different separators and leading zero's.\n actual = tslib._test_parse_iso8601(date_str)\n assert actual == exp\n\n\[email protected](\n \"date_str\",\n [\n \"2011-01/02\",\n \"2011=11=11\",\n \"201401\",\n \"201111\",\n \"200101\",\n # Mixed separated and unseparated.\n \"2005-0101\",\n \"200501-01\",\n \"20010101 12:3456\",\n \"20010101 1234:56\",\n # HHMMSS must have two digits in\n # each component if unseparated.\n \"20010101 1\",\n \"20010101 123\",\n \"20010101 12345\",\n \"20010101 12345Z\",\n ],\n)\ndef test_parsers_iso8601_invalid(date_str):\n msg = f'Error parsing datetime string \"{date_str}\"'\n\n with pytest.raises(ValueError, match=msg):\n tslib._test_parse_iso8601(date_str)\n\n\ndef test_parsers_iso8601_invalid_offset_invalid():\n date_str = \"2001-01-01 12-34-56\"\n msg = f'Timezone hours offset out of range in datetime string \"{date_str}\"'\n\n with pytest.raises(ValueError, match=msg):\n tslib._test_parse_iso8601(date_str)\n\n\ndef test_parsers_iso8601_leading_space():\n # GH#25895 make sure isoparser doesn't overflow with long input\n date_str, expected = (\"2013-1-1 5:30:00\", datetime(2013, 1, 1, 5, 30))\n actual = tslib._test_parse_iso8601(\" \" * 200 + date_str)\n assert actual == expected\n",
"from datetime import timedelta\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import DataFrame, Series\nimport pandas._testing as tm\nfrom pandas.core.indexes.timedeltas import timedelta_range\n\n\ndef test_asfreq_bug():\n df = DataFrame(data=[1, 3], index=[timedelta(), timedelta(minutes=3)])\n result = df.resample(\"1T\").asfreq()\n expected = DataFrame(\n data=[1, np.nan, np.nan, 3],\n index=timedelta_range(\"0 day\", periods=4, freq=\"1T\"),\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef test_resample_with_nat():\n # GH 13223\n index = pd.to_timedelta([\"0s\", pd.NaT, \"2s\"])\n result = DataFrame({\"value\": [2, 3, 5]}, index).resample(\"1s\").mean()\n expected = DataFrame(\n {\"value\": [2.5, np.nan, 5.0]},\n index=timedelta_range(\"0 day\", periods=3, freq=\"1S\"),\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef test_resample_as_freq_with_subperiod():\n # GH 13022\n index = timedelta_range(\"00:00:00\", \"00:10:00\", freq=\"5T\")\n df = DataFrame(data={\"value\": [1, 5, 10]}, index=index)\n result = df.resample(\"2T\").asfreq()\n expected_data = {\"value\": [1, np.nan, np.nan, np.nan, np.nan, 10]}\n expected = DataFrame(\n data=expected_data, index=timedelta_range(\"00:00:00\", \"00:10:00\", freq=\"2T\")\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef test_resample_with_timedeltas():\n\n expected = DataFrame({\"A\": np.arange(1480)})\n expected = expected.groupby(expected.index // 30).sum()\n expected.index = pd.timedelta_range(\"0 days\", freq=\"30T\", periods=50)\n\n df = DataFrame(\n {\"A\": np.arange(1480)}, index=pd.to_timedelta(np.arange(1480), unit=\"T\")\n )\n result = df.resample(\"30T\").sum()\n\n tm.assert_frame_equal(result, expected)\n\n s = df[\"A\"]\n result = s.resample(\"30T\").sum()\n tm.assert_series_equal(result, expected[\"A\"])\n\n\ndef test_resample_single_period_timedelta():\n\n s = Series(list(range(5)), index=pd.timedelta_range(\"1 day\", freq=\"s\", periods=5))\n result = s.resample(\"2s\").sum()\n expected = Series(\n [1, 5, 4], index=pd.timedelta_range(\"1 day\", freq=\"2s\", periods=3)\n )\n tm.assert_series_equal(result, expected)\n\n\ndef test_resample_timedelta_idempotency():\n\n # GH 12072\n index = pd.timedelta_range(\"0\", periods=9, freq=\"10L\")\n series = Series(range(9), index=index)\n result = series.resample(\"10L\").mean()\n expected = series\n tm.assert_series_equal(result, expected)\n\n\ndef test_resample_offset_with_timedeltaindex():\n # GH 10530 & 31809\n rng = timedelta_range(start=\"0s\", periods=25, freq=\"s\")\n ts = Series(np.random.randn(len(rng)), index=rng)\n\n with_base = ts.resample(\"2s\", offset=\"5s\").mean()\n without_base = ts.resample(\"2s\").mean()\n\n exp_without_base = timedelta_range(start=\"0s\", end=\"25s\", freq=\"2s\")\n exp_with_base = timedelta_range(start=\"5s\", end=\"29s\", freq=\"2s\")\n\n tm.assert_index_equal(without_base.index, exp_without_base)\n tm.assert_index_equal(with_base.index, exp_with_base)\n\n\ndef test_resample_categorical_data_with_timedeltaindex():\n # GH #12169\n df = DataFrame({\"Group_obj\": \"A\"}, index=pd.to_timedelta(list(range(20)), unit=\"s\"))\n df[\"Group\"] = df[\"Group_obj\"].astype(\"category\")\n result = df.resample(\"10s\").agg(lambda x: (x.value_counts().index[0]))\n expected = DataFrame(\n {\"Group_obj\": [\"A\", \"A\"], \"Group\": [\"A\", \"A\"]},\n index=pd.TimedeltaIndex([0, 10], unit=\"s\", freq=\"10s\"),\n )\n expected = expected.reindex([\"Group_obj\", \"Group\"], axis=1)\n expected[\"Group\"] = expected[\"Group_obj\"]\n tm.assert_frame_equal(result, expected)\n\n\ndef test_resample_timedelta_values():\n # GH 13119\n # check that timedelta dtype is preserved when NaT values are\n # introduced by the resampling\n\n times = timedelta_range(\"1 day\", \"6 day\", freq=\"4D\")\n df = DataFrame({\"time\": times}, index=times)\n\n times2 = timedelta_range(\"1 day\", \"6 day\", freq=\"2D\")\n exp = Series(times2, index=times2, name=\"time\")\n exp.iloc[1] = pd.NaT\n\n res = df.resample(\"2D\").first()[\"time\"]\n tm.assert_series_equal(res, exp)\n res = df[\"time\"].resample(\"2D\").first()\n tm.assert_series_equal(res, exp)\n\n\[email protected](\n \"start, end, freq, resample_freq\",\n [\n (\"8H\", \"21h59min50s\", \"10S\", \"3H\"), # GH 30353 example\n (\"3H\", \"22H\", \"1H\", \"5H\"),\n (\"527D\", \"5006D\", \"3D\", \"10D\"),\n (\"1D\", \"10D\", \"1D\", \"2D\"), # GH 13022 example\n # tests that worked before GH 33498:\n (\"8H\", \"21h59min50s\", \"10S\", \"2H\"),\n (\"0H\", \"21h59min50s\", \"10S\", \"3H\"),\n (\"10D\", \"85D\", \"D\", \"2D\"),\n ],\n)\ndef test_resample_timedelta_edge_case(start, end, freq, resample_freq):\n # GH 33498\n # check that the timedelta bins does not contains an extra bin\n idx = pd.timedelta_range(start=start, end=end, freq=freq)\n s = Series(np.arange(len(idx)), index=idx)\n result = s.resample(resample_freq).min()\n expected_index = pd.timedelta_range(freq=resample_freq, start=start, end=end)\n tm.assert_index_equal(result.index, expected_index)\n assert result.index.freq == expected_index.freq\n assert not np.isnan(result[-1])\n\n\ndef test_resample_with_timedelta_yields_no_empty_groups():\n # GH 10603\n df = DataFrame(\n np.random.normal(size=(10000, 4)),\n index=pd.timedelta_range(start=\"0s\", periods=10000, freq=\"3906250n\"),\n )\n result = df.loc[\"1s\":, :].resample(\"3s\").apply(lambda x: len(x))\n\n expected = DataFrame(\n [[768.0] * 4] * 12 + [[528.0] * 4],\n index=pd.timedelta_range(start=\"1s\", periods=13, freq=\"3s\"),\n )\n tm.assert_frame_equal(result, expected)\n\n\ndef test_resample_quantile_timedelta():\n # GH: 29485\n df = DataFrame(\n {\"value\": pd.to_timedelta(np.arange(4), unit=\"s\")},\n index=pd.date_range(\"20200101\", periods=4, tz=\"UTC\"),\n )\n result = df.resample(\"2D\").quantile(0.99)\n expected = DataFrame(\n {\n \"value\": [\n pd.Timedelta(\"0 days 00:00:00.990000\"),\n pd.Timedelta(\"0 days 00:00:02.990000\"),\n ]\n },\n index=pd.date_range(\"20200101\", periods=2, tz=\"UTC\", freq=\"2D\"),\n )\n tm.assert_frame_equal(result, expected)\n"
] | [
[
"pandas.compat.is_platform_windows",
"numpy.random.choice",
"numpy.arange",
"pandas.Index",
"pandas.DataFrame",
"numpy.random.normal",
"numpy.random.randn",
"pandas._testing.close",
"pandas._testing.RNGContext"
],
[
"pandas._testing.assert_produces_warning",
"pandas.MultiIndex.from_tuples",
"pandas.DataFrame",
"numpy.array",
"pandas.Timestamp",
"pandas._testing.assert_index_equal"
],
[
"pandas.io.json.read_json",
"pandas._testing.assert_produces_warning",
"pandas.DataFrame"
],
[
"pandas.core.dtypes.inference.is_list_like",
"pandas.compat._optional.import_optional_dependency",
"pandas.io.common.stringify_path"
],
[
"numpy.random.choice",
"numpy.arange",
"pandas.Index",
"pandas.DataFrame",
"pandas.MultiIndex.from_arrays",
"numpy.random.randn",
"numpy.random.rand",
"pandas.date_range",
"numpy.random.randint"
],
[
"pandas.Series",
"pandas.TimedeltaIndex",
"numpy.arange",
"pandas._testing.makeTimeSeries",
"numpy.diff",
"pandas.date_range",
"pandas._testing.assert_series_equal"
],
[
"numpy.asarray",
"pandas.Series",
"pandas.DataFrame"
],
[
"numpy.array",
"pandas._testing.assert_almost_equal",
"pandas._testing.assert_produces_warning",
"pandas.Series",
"pandas.RangeIndex",
"pandas.Index",
"pandas.DataFrame",
"pandas.IntervalIndex.from_breaks",
"numpy.concatenate",
"numpy.random.randn",
"pandas.isna",
"pandas._testing.assert_frame_equal",
"numpy.zeros",
"numpy.random.randint"
],
[
"pandas._libs.tslib._test_parse_iso8601"
],
[
"pandas.timedelta_range",
"pandas.Series",
"pandas.TimedeltaIndex",
"numpy.isnan",
"numpy.arange",
"pandas.DataFrame",
"pandas.Timedelta",
"pandas._testing.assert_series_equal",
"numpy.random.normal",
"pandas.date_range",
"pandas.to_timedelta",
"pandas.core.indexes.timedeltas.timedelta_range",
"pandas._testing.assert_frame_equal",
"pandas._testing.assert_index_equal"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"0.19",
"1.1",
"1.5",
"1.2",
"0.24",
"0.20",
"1.0",
"0.25",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.1",
"1.5",
"1.2",
"1.0",
"1.3"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [
"0.23",
"0.21",
"2.0",
"1.4",
"1.3",
"0.19",
"1.1",
"1.5",
"0.24",
"0.20",
"1.0",
"0.25",
"1.2"
],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
rey-allan/rl | [
"6124bcfe5de8a9a316c41fb75b50a3e9babfc970"
] | [
"policy_gradient.py"
] | [
"\"\"\"Implementation of different policy gradient methods\"\"\"\nimport argparse\nimport numpy as np\nimport plot as plt\nimport random\n\nfrom collections import namedtuple\nfrom env import Action, Easy21, State\nfrom tqdm import tqdm\nfrom typing import Callable, List\n\n# For reproducibility\nrandom.seed(0)\nnp.random.seed(0)\n\nTrajectory = namedtuple(\"Trajectory\", [\"state\", \"action\", \"reward\"])\n\n\ndef encode(s: State, a: Action) -> np.ndarray:\n \"\"\"\n Encodes the given state-action pair using coarse coding as specified in the Easy21 assignment:\n\n A binary feature vector rho(s, a) with 3 ∗ 6 ∗ 2 = 36 features. Each binary feature\n has a value of 1 iff (s, a) lies within the cuboid of state-space corresponding to\n that feature, and the action corresponding to that feature. The cuboids have the\n following overlapping intervals:\n\n - dealer(s) = {[1, 4], [4, 7], [7, 10]}\n - player(s) = {[1, 6], [4, 9], [7, 12], [10, 15], [13, 18], [16, 21]}\n - a = {hit, stick}\n\n :param State s: The state to encode\n :param Action a: The action to encode\n :return: A binary feature vector representing the encoded state-action pair\n :rtype: np.ndarray\n \"\"\"\n # `range` is end-exclusive so we add a 1 to make sure we capture the intervals inclusive ends\n dealer = [range(1, 5), range(4, 8), range(7, 11)]\n player = [range(1, 7), range(4, 10), range(7, 13), range(10, 16), range(13, 19), range(16, 22)]\n encoded = np.zeros((3, 6, 2))\n\n for i, d in enumerate(dealer):\n for j, p in enumerate(player):\n for k, action in enumerate([Action.hit, Action.stick]):\n if s.dealer_first_card in d and s.player_sum in p and a == action:\n encoded[i, j, k] = 1\n\n return encoded.flatten()\n\n\ndef softmax(x: np.ndarray) -> np.ndarray:\n \"\"\"\n Computes the softmax of the given array\n\n :param np.ndarray x: The input array\n :return: The softmax of each element of the input array\n :rtype: np.ndarray\n \"\"\"\n return np.exp(x) / np.sum(np.exp(x))\n\n\nclass REINFORCEWithBaseline:\n \"\"\"\n REINFORCE algorithm with baseline\n\n Uses softmax on linear action preferences for the policy, and\n linear approximation for the value function. Feature vectors\n are computed using coarse coding as described in the Easy21\n assignment.\n \"\"\"\n\n def __init__(self):\n self._env = Easy21(seed=24)\n\n def learn(self, epochs=200, alpha_policy=0.01, alpha_value=0.01, gamma=0.9, verbose=False, **kwargs) -> np.ndarray:\n \"\"\"\n Learns the optimal value function.\n\n :param int epochs: The number of epochs to take to learn the value function\n :param float alpha_policy: The learning rate for the policy approximation\n :param float alpha_value: The learning rate for the value approximation\n :param float gamma: The discount factor\n :param bool verbose: Whether to use verbose mode or not\n :return: The optimal value function\n :rtype: np.ndarray\n \"\"\"\n # Value function\n w = np.random.rand(36)\n value_approximator = lambda s: [np.dot(w, encode(s, a)) for a in [Action.hit, Action.stick]]\n # Policy function\n theta = np.random.rand(36)\n pi = lambda s, theta: softmax(np.array([np.dot(theta, encode(s, a)) for a in [Action.hit, Action.stick]]))\n\n for _ in tqdm(range(epochs), disable=not verbose):\n trajectories = self._sample_episode(pi, theta)\n # Reverse the list so we start backpropagating the return from the last episode\n trajectories.reverse()\n\n # Learn from the episode\n g = 0\n for i, t in enumerate(trajectories):\n g = t.reward + gamma * g\n x = encode(t.state, t.action)\n\n # Baseline\n v = np.dot(w, x)\n delta = g - v\n\n # SGD update of the value function\n w += alpha_value * delta * x\n\n # SGD update of the policy function\n probs = pi(t.state, theta)\n eligibility_vector = x - np.sum([p * encode(t.state, a) for a, p in enumerate(probs)])\n theta += alpha_policy * gamma ** i * delta * eligibility_vector\n\n # Compute the optimal value function which is simply the value of the best action in each state\n values = np.zeros(self._env.state_space)\n for d in range(self._env.state_space[0]):\n for p in range(self._env.state_space[1]):\n values[d, p] = np.max(value_approximator(State(d, p)))\n\n return values\n\n def _sample_episode(self, pi: Callable[[State, Action, np.ndarray], float], theta: np.ndarray) -> List[Trajectory]:\n # Samples trajectories following policy `pi` with an optional starting state-action pair\n trajectories = []\n\n s = self._env.reset()\n # The policy selects the action with some constant exploration as in the Easy21 assignment\n policy = (\n lambda s: random.choice([Action.hit, Action.stick]) if random.random() < 0.05 else np.argmax(pi(s, theta))\n )\n a = policy(s)\n\n while True:\n s_prime, r, done = self._env.step(a)\n trajectories.append(Trajectory(s, a, r))\n\n if done:\n break\n\n s = s_prime\n a = policy(s)\n\n return trajectories\n\n\nclass OneStepActorCritic:\n \"\"\"\n One-step Actor-Critic\n\n Uses softmax on linear action preferences for the policy, and\n linear approximation for the value function. Feature vectors\n are computed using coarse coding as described in the Easy21\n assignment.\n \"\"\"\n\n def __init__(self):\n self._env = Easy21(seed=24)\n\n def learn(self, epochs=200, alpha_policy=0.01, alpha_value=0.01, gamma=0.9, verbose=False, **kwargs) -> np.ndarray:\n \"\"\"\n Learns the optimal value function.\n\n :param int epochs: The number of epochs to take to learn the value function\n :param float alpha_policy: The learning rate for the policy approximation\n :param float alpha_value: The learning rate for the value approximation\n :param float gamma: The discount factor\n :param bool verbose: Whether to use verbose mode or not\n :return: The optimal value function\n :rtype: np.ndarray\n \"\"\"\n # Value function\n w = np.random.rand(36)\n value_approximator = lambda s: [np.dot(w, encode(s, a)) for a in [Action.hit, Action.stick]]\n # Policy function\n theta = np.random.rand(36)\n pi = lambda s, theta: softmax(np.array([np.dot(theta, encode(s, a)) for a in [Action.hit, Action.stick]]))\n # The policy selects the action with some constant exploration as in the Easy21 assignment\n policy = (\n lambda s: random.choice([Action.hit, Action.stick]) if random.random() < 0.05 else np.argmax(pi(s, theta))\n )\n\n for _ in tqdm(range(epochs), disable=not verbose):\n I = 1\n s = self._env.reset()\n done = False\n\n while not done:\n a = policy(s)\n s_prime, r, done = self._env.step(a)\n\n # Compute the delta\n if done:\n delta = r - np.dot(w, encode(s, a))\n else:\n delta = r + gamma * np.max(value_approximator(s_prime)) - np.dot(w, encode(s, a))\n\n # SGD update of the value function\n x = encode(s, a)\n w += alpha_value * delta * x\n\n # SGD update of the policy function\n probs = pi(s, theta)\n eligibility_vector = x - np.sum([p * encode(s, a) for a, p in enumerate(probs)])\n theta += alpha_policy * I * delta * eligibility_vector\n\n I *= gamma\n s = s_prime\n\n # Compute the optimal value function which is simply the value of the best action in each state\n values = np.zeros(self._env.state_space)\n for d in range(self._env.state_space[0]):\n for p in range(self._env.state_space[1]):\n values[d, p] = np.max(value_approximator(State(d, p)))\n\n return values\n\n\nclass ActorCriticWithEligibilityTraces:\n \"\"\"\n Actor-Critic with eligibility traces\n\n Uses softmax on linear action preferences for the policy, and\n linear approximation for the value function. Feature vectors\n are computed using coarse coding as described in the Easy21\n assignment.\n \"\"\"\n\n def __init__(self):\n self._env = Easy21(seed=24)\n\n def learn(\n self,\n epochs=200,\n alpha_policy=0.01,\n alpha_value=0.01,\n gamma=0.9,\n lambda_value=1.0,\n lambda_policy=1.0,\n verbose=False,\n **kwargs\n ) -> np.ndarray:\n \"\"\"\n Learns the optimal value function.\n\n :param int epochs: The number of epochs to take to learn the value function\n :param float alpha_policy: The learning rate for the policy approximation\n :param float alpha_value: The learning rate for the value approximation\n :param float gamma: The discount factor\n :param float lambda_value: The trace decay rate for the value approximation\n :param float lambda_policy: The trace decay rate for the policy approximation\n :param bool verbose: Whether to use verbose mode or not\n :return: The optimal value function\n :rtype: np.ndarray\n \"\"\"\n # Value function\n w = np.random.rand(36)\n value_approximator = lambda s: [np.dot(w, encode(s, a)) for a in [Action.hit, Action.stick]]\n # Policy function\n theta = np.random.rand(36)\n pi = lambda s, theta: softmax(np.array([np.dot(theta, encode(s, a)) for a in [Action.hit, Action.stick]]))\n # The policy selects the action with some constant exploration as in the Easy21 assignment\n policy = (\n lambda s: random.choice([Action.hit, Action.stick]) if random.random() < 0.05 else np.argmax(pi(s, theta))\n )\n\n for _ in tqdm(range(epochs), disable=not verbose):\n I = 1\n s = self._env.reset()\n done = False\n z_w = np.zeros_like(w)\n z_theta = np.zeros_like(theta)\n\n while not done:\n a = policy(s)\n s_prime, r, done = self._env.step(a)\n\n # Compute the delta\n if done:\n delta = r - np.dot(w, encode(s, a))\n else:\n delta = r + gamma * np.max(value_approximator(s_prime)) - np.dot(w, encode(s, a))\n\n # SGD update of the value function\n x = encode(s, a)\n z_w = gamma * lambda_value * z_w + x\n w += alpha_value * delta * z_w\n\n # SGD update of the policy function\n probs = pi(s, theta)\n eligibility_vector = x - np.sum([p * encode(s, a) for a, p in enumerate(probs)])\n z_theta = gamma * lambda_policy * z_theta + I * eligibility_vector\n theta += alpha_policy * delta * z_theta\n\n I *= gamma\n s = s_prime\n\n # Compute the optimal value function which is simply the value of the best action in each state\n values = np.zeros(self._env.state_space)\n for d in range(self._env.state_space[0]):\n for p in range(self._env.state_space[1]):\n values[d, p] = np.max(value_approximator(State(d, p)))\n\n return values\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Run policy gradient methods\")\n parser.add_argument(\"--reinforce-with-baseline\", action=\"store_true\", help=\"Execute REINFORCE with Baseline\")\n parser.add_argument(\"--one-step-ac\", action=\"store_true\", help=\"Execute One-step Actor-Critic\")\n parser.add_argument(\n \"--ac-eligibility-traces\", action=\"store_true\", help=\"Execute Actor-Critic with eligibility traces\"\n )\n parser.add_argument(\"--epochs\", type=int, default=200, help=\"Epochs to train\")\n parser.add_argument(\n \"--alpha-value\", type=float, default=0.01, help=\"Learning rate to use for the value function approximation\"\n )\n parser.add_argument(\n \"--alpha-policy\", type=float, default=0.01, help=\"Learning rate to use for the policy function approximation\"\n )\n parser.add_argument(\n \"--lambda-value\", type=float, default=1.0, help=\"Trace decay rate to use for the value function approximation\"\n )\n parser.add_argument(\n \"--lambda-policy\", type=float, default=1.0, help=\"Trace decay rate to use for the policy function approximation\"\n )\n parser.add_argument(\"--gamma\", type=float, default=0.9, help=\"Discount factor\")\n parser.add_argument(\"--verbose\", action=\"store_true\", help=\"Run in verbose mode\")\n args = parser.parse_args()\n\n # The optimal value function obtained\n V = None\n # The algorithm to run\n policy_grad = None\n # The title of the plot\n title = None\n\n if args.reinforce_with_baseline:\n print(\"Running REINFORCE with Baseline\")\n policy_grad = REINFORCEWithBaseline()\n title = \"reinforce_with_baseline\"\n elif args.one_step_ac:\n print(\"Running One-step Actor-Critic\")\n policy_grad = OneStepActorCritic()\n title = \"one_step_actor_critic\"\n elif args.ac_eligibility_traces:\n print(\"Running Actor-Critic with eligibility traces\")\n policy_grad = ActorCriticWithEligibilityTraces()\n title = \"actor_critic_eligibility_traces\"\n\n if policy_grad is not None:\n V = policy_grad.learn(\n epochs=args.epochs,\n alpha_value=args.alpha_value,\n alpha_policy=args.alpha_policy,\n lambda_value=args.lambda_value,\n lambda_policy=args.lambda_policy,\n gamma=args.gamma,\n verbose=args.verbose,\n )\n\n if V is not None:\n # Plot the value function as a surface\n # Remove the state where the dealer's first card is 0 and the player's sum is 0 because these are not possible\n # They were kept in the value function to avoid having to deal with 0-index vs 1-index\n plt.plot_value_function(range(1, Easy21.state_space[0]), range(1, Easy21.state_space[1]), V[1:, 1:], title)\n"
] | [
[
"numpy.dot",
"numpy.random.seed",
"numpy.zeros_like",
"numpy.random.rand",
"numpy.exp",
"numpy.zeros"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Novixous/Emotion-Trainer | [
"a71d7c6ac3a0686e28ad7ee0b3a5489289ee233d"
] | [
"src/emotions_tpu.py"
] | [
"import numpy as np\nimport argparse\nimport matplotlib.pyplot as plt\nimport cv2\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten\nfrom tensorflow.keras.layers import Conv2D\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.layers import MaxPooling2D\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"-1\"\n\n# command line argument\nap = argparse.ArgumentParser()\nap.add_argument(\"--mode\",help=\"train/display\")\nmode = ap.parse_args().mode\n\ndef combine_gen(*gens):\n while True:\n for g in gens:\n yield next(g)\n\n# plots accuracy and loss curves\ndef plot_model_history(model_history):\n \"\"\"\n Plot Accuracy and Loss curves given the model_history\n \"\"\"\n fig, axs = plt.subplots(1,2,figsize=(15,5))\n # summarize history for accuracy\n axs[0].plot(range(1,len(model_history.history['accuracy'])+1),model_history.history['accuracy'])\n axs[0].plot(range(1,len(model_history.history['val_accuracy'])+1),model_history.history['val_accuracy'])\n axs[0].set_title('Model Accuracy')\n axs[0].set_ylabel('Accuracy')\n axs[0].set_xlabel('Epoch')\n axs[0].set_xticks(np.arange(1,len(model_history.history['accuracy'])+1),len(model_history.history['accuracy'])/10)\n axs[0].legend(['train', 'val'], loc='best')\n # summarize history for loss\n axs[1].plot(range(1,len(model_history.history['loss'])+1),model_history.history['loss'])\n axs[1].plot(range(1,len(model_history.history['val_loss'])+1),model_history.history['val_loss'])\n axs[1].set_title('Model Loss')\n axs[1].set_ylabel('Loss')\n axs[1].set_xlabel('Epoch')\n axs[1].set_xticks(np.arange(1,len(model_history.history['loss'])+1),len(model_history.history['loss'])/10)\n axs[1].legend(['train', 'val'], loc='best')\n fig.savefig('plot.png')\n plt.show()\n\n# Define data generators\ntrain_dir = 'data/train'\nval_dir = 'data/test'\neval_dir = 'data/evaluate'\nclone_time = 30\nnum_train = 28709 * clone_time\nnum_val = 7178\nbatch_size = 64\nnum_epoch = 10\n\ntrain_datagen = ImageDataGenerator(\n rescale=1./255, \n brightness_range=[0.2,1.5],\n horizontal_flip=True)\nval_datagen = ImageDataGenerator(rescale=1./255)\neval_datagen = ImageDataGenerator(rescale=1./255)\n\ntrain_generators = []\nfor x in range(clone_time):\n train_generators.append(train_datagen.flow_from_directory(\n train_dir,\n target_size=(48,48),\n batch_size=batch_size,\n color_mode=\"grayscale\",\n class_mode='categorical'))\n\nvalidation_generator = val_datagen.flow_from_directory(\n val_dir,\n target_size=(48,48),\n batch_size=batch_size,\n color_mode=\"grayscale\",\n class_mode='categorical')\n\nevaluation_generator = eval_datagen.flow_from_directory(\n eval_dir,\n target_size=(48,48),\n batch_size=batch_size,\n color_mode=\"grayscale\",\n class_mode='categorical')\n\n\n# Create the model\nmodel = Sequential()\n\nmodel.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(48,48,1)))\nmodel.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Conv2D(128, kernel_size=(3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(1024, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(7, activation='softmax'))\nmodel.summary()\n\n# If you want to train the same model or try other models, go for this\nif mode == \"train\":\n model.compile(loss='categorical_crossentropy',optimizer=Adam(lr=0.0001, decay=1e-6),metrics=['accuracy'])\n model_info = model.fit(\n combine_gen(*train_generators),\n steps_per_epoch=num_train // batch_size,\n epochs=num_epoch,\n validation_data=validation_generator,\n validation_steps=num_val // batch_size)\n # plot_model_history(model_info)\n model.save_weights('model-epoch-augmentated{}.h5'.format(num_epoch))\n\n# emotions will be displayed on your face from the webcam feed\nelif mode == \"display\":\n model.load_weights('model-epoch-augmentated{}.h5'.format(num_epoch))\n\n # prevents openCL usage and unnecessary logging messages\n cv2.ocl.setUseOpenCL(False)\n\n # dictionary which assigns each label an emotion (alphabetical order)\n emotion_dict = {0: \"Angry\", 1: \"Disgusted\", 2: \"Fearful\", 3: \"Happy\", 4: \"Neutral\", 5: \"Sad\", 6: \"Surprised\"}\n\n # start the webcam feed\n cap = cv2.VideoCapture(0)\n fourcc = cv2.VideoWriter_fourcc(*'XVID')\n while True:\n # Find haar cascade to draw bounding box around face\n ret, frame = cap.read()\n if not ret:\n break\n frame = cv2.flip(frame, 1)\n facecasc = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n faces = facecasc.detectMultiScale(gray,scaleFactor=1.3, minNeighbors=5)\n\n for (x, y, w, h) in faces:\n cv2.rectangle(frame, (x, y-50), (x+w, y+h+10), (255, 0, 0), 2)\n roi_gray = gray[y:y + h, x:x + w]\n cropped_img = np.expand_dims(np.expand_dims(cv2.resize(roi_gray, (48, 48)), -1), 0)\n prediction = model.predict(cropped_img)\n np.set_printoptions(formatter={'float': '{: 0.3f}'.format})\n print(prediction)\n # finalArr.append(prediction)\n maxindex = int(np.argmax(prediction))\n cv2.putText(frame, emotion_dict[maxindex], (x+20, y-60), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)\n\n cv2.imshow('Video', cv2.resize(frame,(1600,960),interpolation = cv2.INTER_CUBIC))\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n cap.release()\n # np.set_printoptions(formatter={'float': '{: 0.3f}'.format})\n # for x in finalArr:\n # print(x)\n cv2.destroyAllWindows()\nelif mode == \"evaluate\":\n model.compile(loss='categorical_crossentropy',optimizer=Adam(lr=0.0001, decay=1e-6),metrics=['accuracy'])\n model.load_weights('model-epoch-augmentated{}.h5'.format(num_epoch))\n result = model.evaluate(evaluation_generator)\n"
] | [
[
"tensorflow.keras.preprocessing.image.ImageDataGenerator",
"tensorflow.keras.layers.Dense",
"numpy.set_printoptions",
"tensorflow.keras.layers.Conv2D",
"matplotlib.pyplot.subplots",
"tensorflow.keras.layers.MaxPooling2D",
"tensorflow.keras.optimizers.Adam",
"numpy.argmax",
"tensorflow.keras.layers.Dropout",
"matplotlib.pyplot.show",
"tensorflow.keras.models.Sequential",
"tensorflow.keras.layers.Flatten"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"2.7",
"2.2",
"2.3",
"2.4",
"2.5",
"2.6"
]
}
] |
mitchelldaneker/deepxde | [
"62e09b62ceaab6bda2ebbd02dc30ad99c2990302",
"961e7e2bf1624374e74bf8d2da6b9c3e0eb8b0cc",
"62e09b62ceaab6bda2ebbd02dc30ad99c2990302"
] | [
"deepxde/model.py",
"deepxde/nn/pytorch/fnn.py",
"deepxde/geometry/geometry_3d.py"
] | [
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n__all__ = [\"Model\", \"TrainState\", \"LossHistory\"]\n\n\nimport pickle\nfrom collections import OrderedDict\n\nimport numpy as np\n\nfrom . import config\nfrom . import display\nfrom . import gradients as grad\nfrom . import losses as losses_module\nfrom . import metrics as metrics_module\nfrom . import optimizers\nfrom . import utils\nfrom .backend import backend_name, tf, torch\nfrom .callbacks import CallbackList\n\n\nclass Model(object):\n \"\"\"A ``Model`` trains a ``NN`` on a ``Data``.\n\n Args:\n data: ``deepxde.data.Data`` instance.\n net: ``deepxde.nn.NN`` instance.\n \"\"\"\n\n def __init__(self, data, net):\n self.data = data\n self.net = net\n\n self.opt_name = None\n self.batch_size = None\n self.callbacks = None\n self.metrics = None\n self.external_trainable_variables = []\n self.train_state = TrainState()\n self.losshistory = LossHistory()\n self.stop_training = False\n\n # Backend-dependent attributes\n self.opt = None\n # Tensor or callable\n self.outputs = None\n self.outputs_losses = None\n self.train_step = None\n if backend_name == \"tensorflow.compat.v1\":\n self.sess = None\n self.saver = None\n\n @utils.timing\n def compile(\n self,\n optimizer,\n lr=None,\n loss=\"MSE\",\n metrics=None,\n decay=None,\n loss_weights=None,\n external_trainable_variables=None,\n ):\n \"\"\"Configures the model for training.\n\n Args:\n optimizer: String. Name of optimizer.\n lr: A Tensor or a floating point value. The learning rate. For L-BFGS, use\n `dde.optimizers.set_LBFGS_options` to set the hyperparameters.\n loss: If the same loss is used for all errors, then `loss` is a String (name\n of objective function) or objective function. If different errors use\n different losses, then `loss` is a list whose size is equal to the\n number of errors.\n metrics: List of metrics to be evaluated by the model during training.\n decay: Tuple. Name and parameters of decay to the initial learning rate. One\n of the following options:\n\n - `inverse time decay <https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/schedules/InverseTimeDecay>`_: (\"inverse time\", decay_steps, decay_rate)\n - `cosine decay <https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/schedules/CosineDecay>`_: (\"cosine\", decay_steps, alpha)\n\n loss_weights: A list specifying scalar coefficients (Python floats) to\n weight the loss contributions. The loss value that will be minimized by\n the model will then be the weighted sum of all individual losses,\n weighted by the loss_weights coefficients.\n external_trainable_variables: A trainable ``tf.Variable`` object or a list\n of trainable ``tf.Variable`` objects. The unknown parameters in the\n physics systems that need to be recovered. If the backend is\n tensorflow.compat.v1, `external_trainable_variables` is ignored, and all\n trainable ``tf.Variable`` objects are automatically collected.\n \"\"\"\n print(\"Compiling model...\")\n\n self.opt_name = optimizer\n loss_fn = losses_module.get(loss)\n if external_trainable_variables is None:\n self.external_trainable_variables = []\n else:\n if backend_name == \"tensorflow.compat.v1\":\n print(\n \"Warning: For the backend tensorflow.compat.v1, \"\n \"`external_trainable_variables` is ignored, and all trainable \"\n \"``tf.Variable`` objects are automatically collected.\"\n )\n if not isinstance(external_trainable_variables, list):\n external_trainable_variables = [external_trainable_variables]\n self.external_trainable_variables = external_trainable_variables\n\n if backend_name == \"tensorflow.compat.v1\":\n self._compile_tensorflow_compat_v1(lr, loss_fn, decay, loss_weights)\n elif backend_name == \"tensorflow\":\n self._compile_tensorflow(lr, loss_fn, decay, loss_weights)\n elif backend_name == \"pytorch\":\n self._compile_pytorch(lr, loss_fn, decay, loss_weights)\n\n # metrics may use model variables such as self.net, and thus are instantiated\n # after backend compile.\n metrics = metrics or []\n self.metrics = [metrics_module.get(m) for m in metrics]\n\n def _compile_tensorflow_compat_v1(self, lr, loss_fn, decay, loss_weights):\n \"\"\"tensorflow.compat.v1\"\"\"\n if not self.net.built:\n self.net.build()\n if self.sess is None:\n self.sess = tf.Session()\n self.saver = tf.train.Saver(max_to_keep=None)\n\n # Data losses\n losses = self.data.losses(self.net.targets, self.net.outputs, loss_fn, self)\n if not isinstance(losses, list):\n losses = [losses]\n # Regularization loss\n if self.net.regularizer is not None:\n losses.append(tf.losses.get_regularization_loss())\n losses = tf.convert_to_tensor(losses)\n # Weighted losses\n if loss_weights is not None:\n losses *= loss_weights\n self.losshistory.set_loss_weights(loss_weights)\n total_loss = tf.math.reduce_sum(losses)\n\n # Tensors\n self.outputs = self.net.outputs\n self.outputs_losses = [self.net.outputs, losses]\n self.train_step = optimizers.get(\n total_loss, self.opt_name, learning_rate=lr, decay=decay\n )\n\n def _compile_tensorflow(self, lr, loss_fn, decay, loss_weights):\n \"\"\"tensorflow\"\"\"\n\n # TODO: Avoid creating multiple graphs by using tf.TensorSpec.\n @tf.function\n def outputs(training, inputs):\n return self.net(inputs, training=training)\n\n # TODO: Avoid creating multiple graphs by using tf.TensorSpec.\n @tf.function\n def outputs_losses(training, inputs, targets, auxiliary_vars):\n self.net.training = training\n self.net.inputs = inputs\n self.net.auxiliary_vars = auxiliary_vars\n # Don't call outputs() decorated by @tf.function above, otherwise the\n # gradient of outputs wrt inputs will be lost here.\n outputs_ = self.net(inputs, training=training)\n # Data losses\n losses = self.data.losses(targets, outputs_, loss_fn, self)\n if not isinstance(losses, list):\n losses = [losses]\n # Regularization loss\n if self.net.regularizer is not None:\n losses += [tf.math.reduce_sum(self.net.losses)]\n losses = tf.convert_to_tensor(losses)\n # Weighted losses\n if loss_weights is not None:\n losses *= loss_weights\n self.losshistory.set_loss_weights(loss_weights)\n return outputs_, losses\n\n opt = optimizers.get(self.opt_name, learning_rate=lr, decay=decay)\n\n @tf.function\n def train_step(inputs, targets, auxiliary_vars):\n # inputs and targets are np.ndarray and automatically converted to Tensor.\n with tf.GradientTape() as tape:\n losses = outputs_losses(True, inputs, targets, auxiliary_vars)[1]\n total_loss = tf.math.reduce_sum(losses)\n trainable_variables = (\n self.net.trainable_variables + self.external_trainable_variables\n )\n grads = tape.gradient(total_loss, trainable_variables)\n opt.apply_gradients(zip(grads, trainable_variables))\n\n def train_step_tfp(\n inputs, targets, auxiliary_vars, previous_optimizer_results=None\n ):\n def build_loss():\n losses = outputs_losses(True, inputs, targets, auxiliary_vars)[1]\n return tf.math.reduce_sum(losses)\n\n trainable_variables = (\n self.net.trainable_variables + self.external_trainable_variables\n )\n return opt(trainable_variables, build_loss, previous_optimizer_results)\n\n # Callables\n self.outputs = outputs\n self.outputs_losses = outputs_losses\n self.train_step = (\n train_step\n if not optimizers.is_external_optimizer(self.opt_name)\n else train_step_tfp\n )\n\n def _compile_pytorch(self, lr, loss_fn, decay, loss_weights):\n \"\"\"pytorch\"\"\"\n\n def outputs(training, inputs):\n self.net.train(mode=training)\n with torch.no_grad():\n return self.net(torch.as_tensor(inputs))\n\n def outputs_losses(training, inputs, targets):\n self.net.train(mode=training)\n self.net.inputs = torch.as_tensor(inputs)\n self.net.inputs.requires_grad_()\n outputs_ = self.net(self.net.inputs)\n # Data losses\n if targets is not None:\n targets = torch.as_tensor(targets)\n losses = self.data.losses(targets, outputs_, loss_fn, self)\n if not isinstance(losses, list):\n losses = [losses]\n # TODO: regularization\n losses = torch.stack(losses)\n # Weighted losses\n if loss_weights is not None:\n losses *= torch.as_tensor(loss_weights)\n self.losshistory.set_loss_weights(loss_weights)\n # Clear cached Jacobians and Hessians.\n grad.clear()\n return outputs_, losses\n\n # Another way is using per-parameter options\n # https://pytorch.org/docs/stable/optim.html#per-parameter-options,\n # but not all optimizers (such as L-BFGS) support this.\n trainable_variables = (\n list(self.net.parameters()) + self.external_trainable_variables\n )\n self.opt = optimizers.get(\n trainable_variables, self.opt_name, learning_rate=lr, decay=decay\n )\n\n def train_step(inputs, targets):\n def closure():\n losses = outputs_losses(True, inputs, targets)[1]\n total_loss = torch.sum(losses)\n self.opt.zero_grad()\n total_loss.backward()\n return total_loss\n\n self.opt.step(closure)\n\n # Callables\n self.outputs = outputs\n self.outputs_losses = outputs_losses\n self.train_step = train_step\n\n def _outputs(self, training, inputs):\n if backend_name == \"tensorflow.compat.v1\":\n feed_dict = self.net.feed_dict(training, inputs)\n return self.sess.run(self.outputs, feed_dict=feed_dict)\n # tensorflow and pytorch\n outs = self.outputs(training, inputs)\n return utils.to_numpy(outs)\n\n def _outputs_losses(self, training, inputs, targets, auxiliary_vars):\n if backend_name == \"tensorflow.compat.v1\":\n feed_dict = self.net.feed_dict(training, inputs, targets, auxiliary_vars)\n return self.sess.run(self.outputs_losses, feed_dict=feed_dict)\n if backend_name == \"tensorflow\":\n outs = self.outputs_losses(training, inputs, targets, auxiliary_vars)\n elif backend_name == \"pytorch\":\n # TODO: auxiliary_vars\n self.net.requires_grad_(requires_grad=False)\n outs = self.outputs_losses(training, inputs, targets)\n self.net.requires_grad_()\n return utils.to_numpy(outs)\n\n def _train_step(self, inputs, targets, auxiliary_vars):\n if backend_name == \"tensorflow.compat.v1\":\n feed_dict = self.net.feed_dict(True, inputs, targets, auxiliary_vars)\n self.sess.run(self.train_step, feed_dict=feed_dict)\n elif backend_name == \"tensorflow\":\n self.train_step(inputs, targets, auxiliary_vars)\n elif backend_name == \"pytorch\":\n # TODO: auxiliary_vars\n self.train_step(inputs, targets)\n\n @utils.timing\n def train(\n self,\n epochs=None,\n batch_size=None,\n display_every=1000,\n disregard_previous_best=False,\n callbacks=None,\n model_restore_path=None,\n model_save_path=None,\n ):\n \"\"\"Trains the model for a fixed number of epochs (iterations on a dataset).\n\n Args:\n epochs: Integer. Number of iterations to train the model. Note: It is the\n number of iterations, not the number of epochs.\n batch_size: Integer or ``None``. If you solve PDEs via ``dde.data.PDE`` or\n ``dde.data.TimePDE``, do not use `batch_size`, and instead use\n `dde.callbacks.PDEResidualResampler\n <https://deepxde.readthedocs.io/en/latest/modules/deepxde.html#deepxde.callbacks.PDEResidualResampler>`_,\n see an `example <https://github.com/lululxvi/deepxde/blob/master/examples/diffusion_1d_resample.py>`_.\n display_every: Integer. Print the loss and metrics every this steps.\n disregard_previous_best: If ``True``, disregard the previous saved best\n model.\n callbacks: List of ``dde.callbacks.Callback`` instances. List of callbacks\n to apply during training.\n model_restore_path: String. Path where parameters were previously saved.\n See ``save_path`` in `tf.train.Saver.restore <https://www.tensorflow.org/api_docs/python/tf/compat/v1/train/Saver#restore>`_.\n model_save_path: String. Prefix of filenames created for the checkpoint.\n See ``save_path`` in `tf.train.Saver.save <https://www.tensorflow.org/api_docs/python/tf/compat/v1/train/Saver#save>`_.\n \"\"\"\n self.batch_size = batch_size\n self.callbacks = CallbackList(callbacks=callbacks)\n self.callbacks.set_model(self)\n if disregard_previous_best:\n self.train_state.disregard_best()\n\n if backend_name == \"tensorflow.compat.v1\":\n if self.train_state.step == 0:\n print(\"Initializing variables...\")\n self.sess.run(tf.global_variables_initializer())\n else:\n utils.guarantee_initialized_variables(self.sess)\n\n if model_restore_path is not None:\n self.restore(model_restore_path, verbose=1)\n\n print(\"Training model...\\n\")\n self.stop_training = False\n self.train_state.set_data_train(*self.data.train_next_batch(self.batch_size))\n self.train_state.set_data_test(*self.data.test())\n self._test()\n self.callbacks.on_train_begin()\n if optimizers.is_external_optimizer(self.opt_name):\n if backend_name == \"tensorflow.compat.v1\":\n self._train_tensorflow_compat_v1_scipy(display_every)\n elif backend_name == \"tensorflow\":\n self._train_tensorflow_tfp()\n elif backend_name == \"pytorch\":\n self._train_pytorch_lbfgs()\n else:\n if epochs is None:\n raise ValueError(\"No epochs for {}.\".format(self.opt_name))\n self._train_sgd(epochs, display_every)\n self.callbacks.on_train_end()\n\n print(\"\")\n display.training_display.summary(self.train_state)\n if model_save_path is not None:\n self.save(model_save_path, verbose=1)\n return self.losshistory, self.train_state\n\n def _train_sgd(self, epochs, display_every):\n for i in range(epochs):\n self.callbacks.on_epoch_begin()\n self.callbacks.on_batch_begin()\n\n self.train_state.set_data_train(\n *self.data.train_next_batch(self.batch_size)\n )\n self._train_step(\n self.train_state.X_train,\n self.train_state.y_train,\n self.train_state.train_aux_vars,\n )\n\n self.train_state.epoch += 1\n self.train_state.step += 1\n if self.train_state.step % display_every == 0 or i + 1 == epochs:\n self._test()\n\n self.callbacks.on_batch_end()\n self.callbacks.on_epoch_end()\n\n if self.stop_training:\n break\n\n def _train_tensorflow_compat_v1_scipy(self, display_every):\n def loss_callback(loss_train):\n self.train_state.epoch += 1\n self.train_state.step += 1\n if self.train_state.step % display_every == 0:\n self.train_state.loss_train = loss_train\n self.train_state.loss_test = None\n self.train_state.metrics_test = None\n self.losshistory.append(\n self.train_state.step, self.train_state.loss_train, None, None\n )\n display.training_display(self.train_state)\n\n self.train_state.set_data_train(*self.data.train_next_batch(self.batch_size))\n feed_dict = self.net.feed_dict(\n True,\n self.train_state.X_train,\n self.train_state.y_train,\n self.train_state.train_aux_vars,\n )\n self.train_step.minimize(\n self.sess,\n feed_dict=feed_dict,\n fetches=[self.outputs_losses[1]],\n loss_callback=loss_callback,\n )\n self._test()\n\n def _train_tensorflow_tfp(self):\n # There is only one optimization step. If using multiple steps with/without\n # previous_optimizer_results, L-BFGS failed to reach a small error. The reason\n # could be that tfp.optimizer.lbfgs_minimize will start from scratch for each\n # call.\n n_iter = 0\n while n_iter < optimizers.LBFGS_options[\"maxiter\"]:\n self.train_state.set_data_train(\n *self.data.train_next_batch(self.batch_size)\n )\n results = self.train_step(\n self.train_state.X_train,\n self.train_state.y_train,\n self.train_state.train_aux_vars,\n )\n n_iter += results.num_iterations.numpy()\n self.train_state.epoch += results.num_iterations.numpy()\n self.train_state.step += results.num_iterations.numpy()\n self._test()\n\n if results.converged or results.failed:\n break\n\n def _train_pytorch_lbfgs(self):\n prev_n_iter = 0\n while prev_n_iter < optimizers.LBFGS_options[\"maxiter\"]:\n self.callbacks.on_epoch_begin()\n self.callbacks.on_batch_begin()\n\n self.train_state.set_data_train(\n *self.data.train_next_batch(self.batch_size)\n )\n self._train_step(\n self.train_state.X_train,\n self.train_state.y_train,\n self.train_state.train_aux_vars,\n )\n\n n_iter = self.opt.state_dict()[\"state\"][0][\"n_iter\"]\n if prev_n_iter == n_iter:\n # Converged\n break\n\n self.train_state.epoch += n_iter - prev_n_iter\n self.train_state.step += n_iter - prev_n_iter\n prev_n_iter = n_iter\n self._test()\n\n self.callbacks.on_batch_end()\n self.callbacks.on_epoch_end()\n\n if self.stop_training:\n break\n\n def _test(self):\n (\n self.train_state.y_pred_train,\n self.train_state.loss_train,\n ) = self._outputs_losses(\n True,\n self.train_state.X_train,\n self.train_state.y_train,\n self.train_state.train_aux_vars,\n )\n self.train_state.y_pred_test, self.train_state.loss_test = self._outputs_losses(\n False,\n self.train_state.X_test,\n self.train_state.y_test,\n self.train_state.test_aux_vars,\n )\n\n if isinstance(self.train_state.y_test, (list, tuple)):\n self.train_state.metrics_test = [\n m(self.train_state.y_test[i], self.train_state.y_pred_test[i])\n for m in self.metrics\n for i in range(len(self.train_state.y_test))\n ]\n else:\n self.train_state.metrics_test = [\n m(self.train_state.y_test, self.train_state.y_pred_test)\n for m in self.metrics\n ]\n\n self.train_state.update_best()\n self.losshistory.append(\n self.train_state.step,\n self.train_state.loss_train,\n self.train_state.loss_test,\n self.train_state.metrics_test,\n )\n display.training_display(self.train_state)\n\n def predict(self, x, operator=None, callbacks=None):\n \"\"\"Generates output predictions for the input samples.\"\"\"\n if isinstance(x, tuple):\n x = tuple(np.array(xi, dtype=config.real(np)) for xi in x)\n else:\n x = np.array(x, dtype=config.real(np))\n self.callbacks = CallbackList(callbacks=callbacks)\n self.callbacks.set_model(self)\n self.callbacks.on_predict_begin()\n if operator is None:\n y = self._outputs(False, x)\n else:\n # TODO: predict operator with auxiliary_vars\n if backend_name == \"tensorflow.compat.v1\":\n if utils.get_num_args(operator) == 2:\n op = operator(self.net.inputs, self.net.outputs)\n elif utils.get_num_args(operator) == 3:\n op = operator(self.net.inputs, self.net.outputs, x)\n y = self.sess.run(op, feed_dict=self.net.feed_dict(False, x))\n elif backend_name == \"tensorflow\":\n if utils.get_num_args(operator) == 2:\n\n @tf.function\n def op(inputs):\n y = self.net(inputs)\n return operator(inputs, y)\n\n elif utils.get_num_args(operator) == 3:\n\n @tf.function\n def op(inputs):\n y = self.net(inputs)\n return operator(inputs, y, x)\n\n y = op(x)\n y = utils.to_numpy(y)\n elif backend_name == \"pytorch\":\n inputs = torch.as_tensor(x)\n inputs.requires_grad_()\n outputs = self.net(inputs)\n if utils.get_num_args(operator) == 2:\n y = operator(inputs, outputs)\n elif utils.get_num_args(operator) == 3:\n y = operator(inputs, outputs, x)\n y = utils.to_numpy(y)\n self.callbacks.on_predict_end()\n return y\n\n # def evaluate(self, x, y, callbacks=None):\n # \"\"\"Returns the loss values & metrics values for the model in test mode.\"\"\"\n # raise NotImplementedError(\n # \"Model.evaluate to be implemented. Alternatively, use Model.predict.\"\n # )\n\n def state_dict(self):\n \"\"\"Returns a dictionary containing all variables.\"\"\"\n # TODO: backend tensorflow, pytorch\n if backend_name != \"tensorflow.compat.v1\":\n raise NotImplementedError(\n \"state_dict hasn't been implemented for this backend.\"\n )\n destination = OrderedDict()\n variables_names = [v.name for v in tf.global_variables()]\n values = self.sess.run(variables_names)\n for k, v in zip(variables_names, values):\n destination[k] = v\n return destination\n\n def save(self, save_path, protocol=\"tf.train.Saver\", verbose=0):\n \"\"\"Saves all variables to a disk file.\n\n Args:\n protocol (string): If `protocol` is \"tf.train.Saver\", save using\n `tf.train.Save <https://www.tensorflow.org/api_docs/python/tf/compat/v1/train/Saver#attributes>`_.\n If `protocol` is \"pickle\", save using the Python pickle module. Only\n \"tf.train.Saver\" protocol supports ``restore()``.\n \"\"\"\n # TODO: backend tensorflow, pytorch\n if backend_name != \"tensorflow.compat.v1\":\n raise NotImplementedError(\n \"state_dict hasn't been implemented for this backend.\"\n )\n if verbose > 0:\n print(\n \"Epoch {}: saving model to {}-{} ...\\n\".format(\n self.train_state.epoch, save_path, self.train_state.epoch\n )\n )\n if protocol == \"tf.train.Saver\":\n self.saver.save(self.sess, save_path, global_step=self.train_state.epoch)\n elif protocol == \"pickle\":\n with open(\"{}-{}.pkl\".format(save_path, self.train_state.epoch), \"wb\") as f:\n pickle.dump(self.state_dict(), f)\n\n def restore(self, save_path, verbose=0):\n \"\"\"Restore all variables from a disk file.\"\"\"\n # TODO: backend tensorflow, pytorch\n if backend_name != \"tensorflow.compat.v1\":\n raise NotImplementedError(\n \"state_dict hasn't been implemented for this backend.\"\n )\n if verbose > 0:\n print(\"Restoring model from {} ...\\n\".format(save_path))\n self.saver.restore(self.sess, save_path)\n\n def print_model(self):\n \"\"\"Prints all trainable variables.\"\"\"\n # TODO: backend tensorflow, pytorch\n if backend_name != \"tensorflow.compat.v1\":\n raise NotImplementedError(\n \"state_dict hasn't been implemented for this backend.\"\n )\n variables_names = [v.name for v in tf.trainable_variables()]\n values = self.sess.run(variables_names)\n for k, v in zip(variables_names, values):\n print(\"Variable: {}, Shape: {}\".format(k, v.shape))\n print(v)\n\n\nclass TrainState(object):\n def __init__(self):\n self.epoch = 0\n self.step = 0\n\n # Current data\n self.X_train = None\n self.y_train = None\n self.train_aux_vars = None\n self.X_test = None\n self.y_test = None\n self.test_aux_vars = None\n\n # Results of current step\n # Train results\n self.loss_train = None\n self.y_pred_train = None\n # Test results\n self.loss_test = None\n self.y_pred_test = None\n self.y_std_test = None\n self.metrics_test = None\n\n # The best results correspond to the min train loss\n self.best_step = 0\n self.best_loss_train = np.inf\n self.best_loss_test = np.inf\n self.best_y = None\n self.best_ystd = None\n self.best_metrics = None\n\n def set_data_train(self, X_train, y_train, train_aux_vars=None):\n self.X_train = X_train\n self.y_train = y_train\n self.train_aux_vars = train_aux_vars\n\n def set_data_test(self, X_test, y_test, test_aux_vars=None):\n self.X_test = X_test\n self.y_test = y_test\n self.test_aux_vars = test_aux_vars\n\n def update_best(self):\n if self.best_loss_train > np.sum(self.loss_train):\n self.best_step = self.step\n self.best_loss_train = np.sum(self.loss_train)\n self.best_loss_test = np.sum(self.loss_test)\n self.best_y = self.y_pred_test\n self.best_ystd = self.y_std_test\n self.best_metrics = self.metrics_test\n\n def disregard_best(self):\n self.best_loss_train = np.inf\n\n def packed_data(self):\n def merge_values(values):\n if values is None:\n return None\n return np.hstack(values) if isinstance(values, (list, tuple)) else values\n\n X_train = merge_values(self.X_train)\n y_train = merge_values(self.y_train)\n X_test = merge_values(self.X_test)\n y_test = merge_values(self.y_test)\n best_y = merge_values(self.best_y)\n best_ystd = merge_values(self.best_ystd)\n return X_train, y_train, X_test, y_test, best_y, best_ystd\n\n\nclass LossHistory(object):\n def __init__(self):\n self.steps = []\n self.loss_train = []\n self.loss_test = []\n self.metrics_test = []\n self.loss_weights = 1\n\n def set_loss_weights(self, loss_weights):\n self.loss_weights = loss_weights\n\n def append(self, step, loss_train, loss_test, metrics_test):\n self.steps.append(step)\n self.loss_train.append(loss_train)\n if loss_test is None:\n loss_test = self.loss_test[-1]\n if metrics_test is None:\n metrics_test = self.metrics_test[-1]\n self.loss_test.append(loss_test)\n self.metrics_test.append(metrics_test)\n",
"import torch\n\nfrom .nn import NN\nfrom .. import activations\nfrom .. import initializers\n\n\nclass FNN(NN):\n \"\"\"Fully-connected neural network.\"\"\"\n\n def __init__(self, layer_sizes, activation, kernel_initializer):\n super(FNN, self).__init__()\n self.activation = activations.get(activation)\n initializer = initializers.get(kernel_initializer)\n initializer_zero = initializers.get(\"zeros\")\n\n self.linears = torch.nn.ModuleList()\n for i in range(1, len(layer_sizes)):\n self.linears.append(torch.nn.Linear(layer_sizes[i - 1], layer_sizes[i]))\n initializer(self.linears[-1].weight)\n initializer_zero(self.linears[-1].bias)\n\n def forward(self, inputs):\n x = inputs\n if self._input_transform is not None:\n x = self._input_transform(x)\n for linear in self.linears[:-1]:\n x = self.activation(linear(x))\n x = self.linears[-1](x)\n if self._output_transform is not None:\n x = self._output_transform(inputs, x)\n return x\n",
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport itertools\n\nimport numpy as np\n\nfrom .geometry_2d import Rectangle\nfrom .geometry_nd import Hypercube, Hypersphere\n\n\nclass Cuboid(Hypercube):\n \"\"\"\n Args:\n xmin: Coordinate of bottom left corner.\n xmax: Coordinate of top right corner.\n \"\"\"\n\n def __init__(self, xmin, xmax):\n super(Cuboid, self).__init__(xmin, xmax)\n dx = self.xmax - self.xmin\n self.area = 2 * np.sum(dx * np.roll(dx, 2))\n\n def random_boundary_points(self, n, random=\"pseudo\"):\n pts = []\n density = n / self.area\n rect = Rectangle(self.xmin[:-1], self.xmax[:-1])\n for z in [self.xmin[-1], self.xmax[-1]]:\n u = rect.random_points(int(np.ceil(density * rect.area)), random=random)\n pts.append(np.hstack((u, np.full((len(u), 1), z))))\n rect = Rectangle(self.xmin[::2], self.xmax[::2])\n for y in [self.xmin[1], self.xmax[1]]:\n u = rect.random_points(int(np.ceil(density * rect.area)), random=random)\n pts.append(np.hstack((u[:, 0:1], np.full((len(u), 1), y), u[:, 1:])))\n rect = Rectangle(self.xmin[1:], self.xmax[1:])\n for x in [self.xmin[0], self.xmax[0]]:\n u = rect.random_points(int(np.ceil(density * rect.area)), random=random)\n pts.append(np.hstack((np.full((len(u), 1), x), u)))\n pts = np.vstack(pts)\n if len(pts) > n:\n return pts[np.random.choice(len(pts), size=n, replace=False)]\n return pts\n\n def uniform_boundary_points(self, n):\n h = (self.area / n) ** 0.5\n nx, ny, nz = np.ceil((self.xmax - self.xmin) / h).astype(int) + 1\n x = np.linspace(self.xmin[0], self.xmax[0], num=nx)\n y = np.linspace(self.xmin[1], self.xmax[1], num=ny)\n z = np.linspace(self.xmin[2], self.xmax[2], num=nz)\n\n pts = []\n for v in [self.xmin[-1], self.xmax[-1]]:\n u = list(itertools.product(x, y))\n pts.append(np.hstack((u, np.full((len(u), 1), v))))\n if nz > 2:\n for v in [self.xmin[1], self.xmax[1]]:\n u = np.array(list(itertools.product(x, z[1:-1])))\n pts.append(np.hstack((u[:, 0:1], np.full((len(u), 1), v), u[:, 1:])))\n if ny > 2 and nz > 2:\n for v in [self.xmin[0], self.xmax[0]]:\n u = list(itertools.product(y[1:-1], z[1:-1]))\n pts.append(np.hstack((np.full((len(u), 1), v), u)))\n pts = np.vstack(pts)\n if n != len(pts):\n print(\n \"Warning: {} points required, but {} points sampled.\".format(\n n, len(pts)\n )\n )\n return pts\n\n\nclass Sphere(Hypersphere):\n \"\"\"\n Args:\n center: Center of the sphere.\n radius: Radius of the sphere.\n \"\"\"\n\n def __init__(self, center, radius):\n super(Sphere, self).__init__(center, radius)\n"
] | [
[
"numpy.hstack",
"numpy.sum"
],
[
"torch.nn.Linear",
"torch.nn.ModuleList"
],
[
"numpy.ceil",
"numpy.roll",
"numpy.vstack",
"numpy.linspace"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
pyguan88/EDSR_WDSR_PyTorch | [
"8212c63f0905f2126dffef7678269b83342b290b"
] | [
"src/dataloader.py"
] | [
"import sys\nimport threading\nimport queue\nimport random\nimport collections\n\nimport torch\nimport torch.multiprocessing as multiprocessing\n\n# from torch._C import _set_worker_signal_handlers, _update_worker_pids, \\\n# _remove_worker_pids, _error_if_any_worker_fails\n# from torch.utils.data.dataloader import DataLoader\n# from torch.utils.data.dataloader import _DataLoaderIter\n# from torch.utils.data.dataloader import ManagerWatchdog\n# from torch.utils.data.dataloader import _pin_memory_loop\n# from torch.utils.data.dataloader import MP_STATUS_CHECK_INTERVAL\n\n# from torch.utils.data.dataloader import ExceptionWrapper\n# from torch.utils.data.dataloader import _use_shared_memory\n# from torch.utils.data.dataloader import numpy_type_map\n# from torch.utils.data.dataloader import default_collate\n# from torch.utils.data.dataloader import pin_memory_batch\n# from torch.utils.data.dataloader import _SIGCHLD_handler_set\n# from torch.utils.data.dataloader import _set_SIGCHLD_handler\n\n###for pytorch 1.1\nfrom torch._C import _set_worker_signal_handlers\nfrom torch.utils.data import _utils\nfrom torch.utils.data.dataloader import DataLoader\nfrom torch.utils.data.dataloader import _DataLoaderIter\n \n_use_shared_memory = False\n\n\nif sys.version_info[0] == 2:\n import Queue as queue\nelse:\n import queue\n\ndef _ms_loop(dataset, index_queue, data_queue, done_event, collate_fn, scale, seed, init_fn, worker_id):\n try:\n global _use_shared_memory\n _use_shared_memory = True\n _set_worker_signal_handlers()\n\n torch.set_num_threads(1)\n random.seed(seed)\n torch.manual_seed(seed)\n data_queue.cancel_join_thread()\n\n if init_fn is not None:\n init_fn(worker_id)\n\n# watchdog = ManagerWatchdog()\n watchdog = _utils.worker.ManagerWatchdog()\n\n while watchdog.is_alive():\n# try:\n# r = index_queue.get(timeout=MP_STATUS_CHECK_INTERVAL)\n try:\n r = index_queue.get(timeout=_utils.MP_STATUS_CHECK_INTERVAL)\n except queue.Empty:\n continue\n\n if r is None:\n assert done_event.is_set()\n return\n elif done_event.is_set():\n continue\n idx, batch_indices = r\n try:\n idx_scale = 0\n if len(scale) > 1 and dataset.train:\n idx_scale = random.randrange(0, len(scale))\n dataset.set_scale(idx_scale)\n\n samples = collate_fn([dataset[i] for i in batch_indices])\n samples.append(idx_scale)\n# except Exception:\n# data_queue.put((idx, ExceptionWrapper(sys.exc_info())))\n except Exception:\n data_queue.put((idx, _utils.ExceptionWrapper(sys.exc_info())))\n else:\n data_queue.put((idx, samples))\n except KeyboardInterrupt:\n pass\n\nclass _MSDataLoaderIter(_DataLoaderIter):\n def __init__(self, loader):\n self.dataset = loader.dataset\n self.scale = loader.scale\n self.collate_fn = loader.collate_fn\n self.batch_sampler = loader.batch_sampler\n self.num_workers = loader.num_workers\n self.pin_memory = loader.pin_memory and torch.cuda.is_available()\n self.timeout = loader.timeout\n\n self.sample_iter = iter(self.batch_sampler)\n\n base_seed = torch.LongTensor(1).random_().item()\n\n if self.num_workers > 0:\n self.worker_init_fn = loader.worker_init_fn\n self.worker_queue_idx = 0\n self.worker_result_queue = multiprocessing.Queue()\n self.batches_outstanding = 0\n self.worker_pids_set = False\n self.shutdown = False\n self.send_idx = 0\n self.rcvd_idx = 0\n self.reorder_dict = {}\n self.done_event = multiprocessing.Event()\n\n base_seed = torch.LongTensor(1).random_()[0]\n\n self.index_queues = []\n self.workers = []\n for i in range(self.num_workers):\n index_queue = multiprocessing.Queue()\n index_queue.cancel_join_thread()\n w = multiprocessing.Process(\n target=_ms_loop,\n args=(\n self.dataset,\n index_queue,\n self.worker_result_queue,\n self.done_event,\n self.collate_fn,\n self.scale,\n base_seed + i,\n self.worker_init_fn,\n i\n )\n )\n w.start()\n self.index_queues.append(index_queue)\n self.workers.append(w)\n\n if self.pin_memory:\n self.data_queue = queue.Queue()\n pin_memory_thread = threading.Thread(\n# target=_pin_memory_loop,\n target=_utils.pin_memory._pin_memory_loop,\n args=(\n self.worker_result_queue,\n self.data_queue,\n torch.cuda.current_device(),\n self.done_event\n )\n )\n pin_memory_thread.daemon = True\n pin_memory_thread.start()\n self.pin_memory_thread = pin_memory_thread\n else:\n self.data_queue = self.worker_result_queue\n\n# _update_worker_pids(id(self), tuple(w.pid for w in self.workers))\n# _set_SIGCHLD_handler()\n _utils.signal_handling._set_worker_pids(id(self), tuple(w.pid for w in self.workers))\n _utils.signal_handling._set_SIGCHLD_handler()\n self.worker_pids_set = True\n\n for _ in range(2 * self.num_workers):\n self._put_indices()\n\nclass MSDataLoader(DataLoader):\n def __init__(\n self, args, dataset, batch_size=1, shuffle=False,\n sampler=None, batch_sampler=None,\n collate_fn=_utils.collate.default_collate, pin_memory=False, drop_last=False,\n timeout=0, worker_init_fn=None):\n\n super(MSDataLoader, self).__init__(\n dataset,\n batch_size=batch_size,\n shuffle=shuffle,\n sampler=sampler,\n batch_sampler=batch_sampler,\n num_workers=args.n_threads,\n collate_fn=collate_fn,\n pin_memory=pin_memory,\n drop_last=drop_last,\n timeout=timeout,\n worker_init_fn=worker_init_fn\n )\n\n self.scale = args.scale\n\n def __iter__(self):\n return _MSDataLoaderIter(self)\n"
] | [
[
"torch._C._set_worker_signal_handlers",
"torch.LongTensor",
"torch.multiprocessing.Queue",
"torch.cuda.current_device",
"torch.utils.data._utils.worker.ManagerWatchdog",
"torch.manual_seed",
"torch.multiprocessing.Event",
"torch.set_num_threads",
"torch.utils.data._utils.signal_handling._set_SIGCHLD_handler",
"torch.cuda.is_available",
"torch.multiprocessing.Process"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
druzhkov-paul/T2T-ViT | [
"819c3ddc4cb6f464d4a9866d8713c7ace42ebf6c"
] | [
"models/transformer_block.py"
] | [
"# Copyright (c) [2012]-[2021] Shanghai Yitu Technology Co., Ltd.\n#\n# This source code is licensed under the Clear BSD License\n# LICENSE file in the root directory of this file\n# All rights reserved.\n\"\"\"\nBorrow from timm(https://github.com/rwightman/pytorch-image-models)\n\"\"\"\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom timm.models.layers import DropPath\n\nclass Mlp(nn.Module):\n def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):\n super().__init__()\n out_features = out_features or in_features\n hidden_features = hidden_features or in_features\n self.fc1 = nn.Linear(in_features, hidden_features)\n self.act = act_layer()\n self.fc2 = nn.Linear(hidden_features, out_features)\n self.drop = nn.Dropout(drop)\n\n def forward(self, x):\n x = self.fc1(x)\n x = self.act(x)\n x = self.drop(x)\n x = self.fc2(x)\n x = self.drop(x)\n return x\n\nclass Attention(nn.Module):\n def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.):\n super().__init__()\n self.num_heads = num_heads\n head_dim = dim // num_heads\n\n self.scale = qk_scale or head_dim ** -0.5\n\n self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)\n self.attn_drop = nn.Dropout(attn_drop)\n self.proj = nn.Linear(dim, dim)\n self.proj_drop = nn.Dropout(proj_drop)\n\n def forward(self, x):\n B, N, C = original_shape = x.shape\n C = int(C)\n qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)\n q, k, v = qkv[0], qkv[1], qkv[2]\n\n attn = (q @ k.transpose(-2, -1)) * self.scale\n attn = attn.softmax(dim=-1)\n attn = self.attn_drop(attn)\n\n x = (attn @ v).transpose(1, 2).reshape(*original_shape)\n x = self.proj(x)\n x = self.proj_drop(x)\n return x\n\nclass Block(nn.Module):\n\n def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,\n drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm):\n super().__init__()\n self.norm1 = norm_layer(dim)\n self.attn = Attention(\n dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)\n self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()\n self.norm2 = norm_layer(dim)\n mlp_hidden_dim = int(dim * mlp_ratio)\n self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)\n\n def forward(self, x):\n x = x + self.drop_path(self.attn(self.norm1(x)))\n x = x + self.drop_path(self.mlp(self.norm2(x)))\n return x\n\n\ndef get_sinusoid_encoding(n_position, d_hid):\n ''' Sinusoid position encoding table '''\n\n def get_position_angle_vec(position):\n return [position / np.power(10000, 2 * (hid_j // 2) / d_hid) for hid_j in range(d_hid)]\n\n sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(n_position)])\n sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i\n sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1\n\n return torch.FloatTensor(sinusoid_table).unsqueeze(0)\n\n\ndef get_sinusoid_encoding_pt(n_position, d_hid):\n ''' Sinusoid position encoding table '''\n pos = torch.arange(n_position).reshape(-1, 1).float()\n dh = torch.pow(10000, 2 * (torch.arange(d_hid) // 2) / d_hid).reshape(1, -1).float()\n sinusoid_table = pos / dh\n shape = sinusoid_table.shape\n sinusoid_table = sinusoid_table.reshape(-1, 2)\n sinusoid_table = torch.stack([torch.sin(sinusoid_table[..., 0]), torch.cos(sinusoid_table[..., 1])], dim=1)\n sinusoid_table = sinusoid_table.reshape(1, *shape)\n # sinusoid_table[:, 0::2] = torch.sin(sinusoid_table[:, 0::2]) # dim 2i\n # sinusoid_table[:, 1::2] = torch.cos(sinusoid_table[:, 1::2]) # dim 2i+1\n return sinusoid_table\n"
] | [
[
"torch.nn.Dropout",
"torch.sin",
"numpy.power",
"numpy.cos",
"numpy.sin",
"torch.nn.Linear",
"torch.nn.Identity",
"torch.FloatTensor",
"torch.arange",
"torch.cos"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
madisoth/sdcflows | [
"c2f01e4f9b19dbd89ac1b54e3cfb0643fc3fd4f2"
] | [
"sdcflows/workflows/tests/test_ancillary.py"
] | [
"# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-\n# vi: set ft=python sts=4 ts=4 sw=4 et:\n#\n# Copyright 2021 The NiPreps Developers <[email protected]>\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# We support and encourage derived works from this project, please read\n# about our expectations at\n#\n# https://www.nipreps.org/community/licensing/\n#\n\"\"\"Check the tools submodule.\"\"\"\nimport os\nimport pytest\nfrom nipype.pipeline import engine as pe\nfrom nipype.interfaces import utility as niu\nfrom niworkflows.interfaces.reportlets.masks import SimpleShowMaskRPT\nfrom ..ancillary import init_brainextraction_wf\n\n\[email protected](os.getenv(\"GITHUB_ACTIONS\") == \"true\", reason=\"this is GH Actions\")\[email protected](\"folder\", [\"magnitude/ds000054\", \"magnitude/ds000217\"])\ndef test_brainmasker(tmpdir, datadir, workdir, outdir, folder):\n \"\"\"Exercise the brain masking tool.\"\"\"\n tmpdir.chdir()\n\n wf = pe.Workflow(name=f\"test_mask_{folder.replace('/', '_')}\")\n if workdir:\n wf.base_dir = str(workdir)\n\n input_files = [\n str(f) for f in (datadir / \"brain-extraction-tests\" / folder).glob(\"*.nii.gz\")\n ]\n\n inputnode = pe.Node(niu.IdentityInterface(fields=(\"in_file\",)), name=\"inputnode\")\n inputnode.iterables = (\"in_file\", input_files)\n merger = pe.Node(niu.Function(function=_merge), name=\"merger\")\n\n brainmask_wf = init_brainextraction_wf()\n\n # fmt:off\n wf.connect([\n (inputnode, merger, [(\"in_file\", \"in_file\")]),\n (merger, brainmask_wf, [(\"out\", \"inputnode.in_file\")]),\n ])\n # fmt:on\n\n if outdir:\n out_path = outdir / \"masks\" / folder.split(\"/\")[-1]\n out_path.mkdir(exist_ok=True, parents=True)\n report = pe.Node(SimpleShowMaskRPT(), name=\"report\")\n report.interface._always_run = True\n\n def _report_name(fname, out_path):\n from pathlib import Path\n\n return str(\n out_path\n / Path(fname)\n .name.replace(\".nii\", \"_mask.svg\")\n .replace(\"_magnitude\", \"_desc-magnitude\")\n .replace(\".gz\", \"\")\n )\n\n # fmt: off\n wf.connect([\n (inputnode, report, [((\"in_file\", _report_name, out_path), \"out_report\")]),\n (brainmask_wf, report, [(\"outputnode.out_mask\", \"mask_file\"),\n (\"outputnode.out_file\", \"background_file\")]),\n ])\n # fmt: on\n\n wf.run()\n\n\ndef _merge(in_file):\n import nibabel as nb\n import numpy as np\n\n img = nb.squeeze_image(nb.load(in_file))\n\n data = np.asanyarray(img.dataobj)\n if data.ndim == 3:\n return in_file\n\n from pathlib import Path\n\n data = data.mean(-1)\n out_file = (Path() / \"merged.nii.gz\").absolute()\n img.__class__(data, img.affine, img.header).to_filename(out_file)\n return str(out_file)\n"
] | [
[
"numpy.asanyarray"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
mengkai94/training_results_v0.6 | [
"43dc3e250f8da47b5f8833197d74cb8cf1004fc9",
"d59320c764bd09474775e1b292f3c05c27743d24",
"43dc3e250f8da47b5f8833197d74cb8cf1004fc9",
"d59320c764bd09474775e1b292f3c05c27743d24",
"f5bb59aa0f8b18b602763abe47d1d24d0d54b197",
"43dc3e250f8da47b5f8833197d74cb8cf1004fc9",
"43dc3e250f8da47b5f8833197d74cb8cf1004fc9",
"43dc3e250f8da47b5f8833197d74cb8cf1004fc9",
"43dc3e250f8da47b5f8833197d74cb8cf1004fc9",
"43dc3e250f8da47b5f8833197d74cb8cf1004fc9",
"43dc3e250f8da47b5f8833197d74cb8cf1004fc9",
"43dc3e250f8da47b5f8833197d74cb8cf1004fc9",
"d59320c764bd09474775e1b292f3c05c27743d24",
"43dc3e250f8da47b5f8833197d74cb8cf1004fc9",
"d59320c764bd09474775e1b292f3c05c27743d24",
"43dc3e250f8da47b5f8833197d74cb8cf1004fc9"
] | [
"Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/horovod/setup.py",
"Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/tests/python/contrib/test_sparse.py",
"NVIDIA/benchmarks/transformer/implementations/pytorch/fairseq/models/fused_layer_norm.py",
"Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/topi/tests/python/test_topi_depthwise_conv2d_back_input.py",
"NVIDIA/benchmarks/transformer/implementations/pytorch/eval_lm.py",
"Google/benchmarks/ssd/implementations/tpu-v3-512-ssd/ssd/utils.py",
"Google/benchmarks/transformer/implementations/tpu-v3-512-transformer/dataset_preproc/data_generators/cnn_dailymail.py",
"Google/benchmarks/mask/implementations/tpu-v3-256-mask/mask_rcnn/mask_rcnn_main.py",
"NVIDIA/benchmarks/gnmt/implementations/pytorch/seq2seq/utils.py",
"Google/benchmarks/transformer/implementations/tpu-v3-512-transformer/dataset_preproc/data_generators/timeseries_test.py",
"Google/benchmarks/gnmt/implementations/tpu-v3-512-gnmt/nmt/utils/vocab_utils.py",
"Fujitsu/benchmarks/resnet/implementations/mxnet/sockeye/sockeye/image_captioning/visualize.py",
"Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/topi/tests/python_cpp/test_topi_l2norm.py",
"Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/nnvm/tests/python/compiler/test_top_level1.py",
"Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/tutorials/nnvm/from_coreml.py",
"Google/benchmarks/mask/implementations/tpu-v3-32-mask/mask_rcnn/lr_policy.py"
] | [
"# Copyright 2017 Uber Technologies, Inc. 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# ==============================================================================\nfrom __future__ import print_function\n\nimport os\nfrom setuptools import setup, Extension, find_packages\nfrom setuptools.command.build_ext import build_ext\nfrom distutils.errors import CompileError, DistutilsError, DistutilsPlatformError, LinkError\nimport shlex\nimport subprocess\nimport sys\nimport textwrap\nimport traceback\n\nfrom horovod import __version__\n\n\ncommon_mpi_lib = Extension('horovod.common.mpi_lib', [])\ntensorflow_mpi_lib = Extension('horovod.tensorflow.mpi_lib', [])\ntorch_mpi_lib = Extension('horovod.torch.mpi_lib', [])\ntorch_mpi_lib_impl = Extension('horovod.torch.mpi_lib_impl', [])\n\n\ndef is_build_action():\n if len(sys.argv) <= 1:\n return False\n\n if sys.argv[1].startswith('build'):\n return True\n\n if sys.argv[1].startswith('bdist'):\n return True\n\n if sys.argv[1].startswith('install'):\n return True\n\n\ndef check_tf_version():\n try:\n import tensorflow as tf\n if tf.__version__ < '1.1.0':\n raise DistutilsPlatformError(\n 'Your TensorFlow version %s is outdated. '\n 'Horovod requires tensorflow>=1.1.0' % tf.__version__)\n except ImportError:\n raise DistutilsPlatformError(\n 'import tensorflow failed, is it installed?\\n\\n%s' % traceback.format_exc())\n except AttributeError:\n # This means that tf.__version__ was not exposed, which makes it *REALLY* old.\n raise DistutilsPlatformError(\n 'Your TensorFlow version is outdated. Horovod requires tensorflow>=1.1.0')\n\n\ndef get_cpp_flags(build_ext):\n last_err = None\n default_flags = ['-std=c++11', '-fPIC', '-O2']\n if sys.platform == 'darwin':\n # Darwin most likely will have Clang, which has libc++.\n flags_to_try = [default_flags + ['-stdlib=libc++'], default_flags]\n else:\n flags_to_try = [default_flags, default_flags + ['-stdlib=libc++']]\n for cpp_flags in flags_to_try:\n try:\n test_compile(build_ext, 'test_cpp_flags', extra_preargs=cpp_flags,\n code=textwrap.dedent('''\\\n #include <unordered_map>\n void test() {\n }\n '''))\n\n return cpp_flags\n except (CompileError, LinkError):\n last_err = 'Unable to determine C++ compilation flags (see error above).'\n except Exception:\n last_err = 'Unable to determine C++ compilation flags. ' \\\n 'Last error:\\n\\n%s' % traceback.format_exc()\n\n raise DistutilsPlatformError(last_err)\n\n\ndef get_tf_include_dirs():\n import tensorflow as tf\n tf_inc = tf.sysconfig.get_include()\n return [tf_inc, '%s/external/nsync/public' % tf_inc]\n\n\ndef get_tf_lib_dirs():\n import tensorflow as tf\n tf_lib = tf.sysconfig.get_lib()\n return [tf_lib]\n\n\ndef get_tf_libs(build_ext, lib_dirs, cpp_flags):\n last_err = None\n for tf_libs in [['tensorflow_framework'], []]:\n try:\n lib_file = test_compile(build_ext, 'test_tensorflow_libs',\n library_dirs=lib_dirs, libraries=tf_libs,\n extra_preargs=cpp_flags,\n code=textwrap.dedent('''\\\n void test() {\n }\n '''))\n\n from tensorflow.python.framework import load_library\n load_library.load_op_library(lib_file)\n\n return tf_libs\n except (CompileError, LinkError):\n last_err = 'Unable to determine -l link flags to use with TensorFlow (see error above).'\n except Exception:\n last_err = 'Unable to determine -l link flags to use with TensorFlow. ' \\\n 'Last error:\\n\\n%s' % traceback.format_exc()\n\n raise DistutilsPlatformError(last_err)\n\n\ndef get_tf_abi(build_ext, include_dirs, lib_dirs, libs, cpp_flags):\n last_err = None\n cxx11_abi_macro = '_GLIBCXX_USE_CXX11_ABI'\n for cxx11_abi in ['0', '1']:\n try:\n lib_file = test_compile(build_ext, 'test_tensorflow_abi',\n macros=[(cxx11_abi_macro, cxx11_abi)],\n include_dirs=include_dirs, library_dirs=lib_dirs,\n libraries=libs, extra_preargs=cpp_flags,\n code=textwrap.dedent('''\\\n #include <string>\n #include \"tensorflow/core/framework/op.h\"\n #include \"tensorflow/core/framework/op_kernel.h\"\n #include \"tensorflow/core/framework/shape_inference.h\"\n void test() {\n auto ignore = tensorflow::strings::StrCat(\"a\", \"b\");\n }\n '''))\n\n from tensorflow.python.framework import load_library\n load_library.load_op_library(lib_file)\n\n return cxx11_abi_macro, cxx11_abi\n except (CompileError, LinkError):\n last_err = 'Unable to determine CXX11 ABI to use with TensorFlow (see error above).'\n except Exception:\n last_err = 'Unable to determine CXX11 ABI to use with TensorFlow. ' \\\n 'Last error:\\n\\n%s' % traceback.format_exc()\n\n raise DistutilsPlatformError(last_err)\n\n\ndef get_tf_flags(build_ext, cpp_flags):\n import tensorflow as tf\n try:\n return tf.sysconfig.get_compile_flags(), tf.sysconfig.get_link_flags()\n except AttributeError:\n # fallback to the previous logic\n tf_include_dirs = get_tf_include_dirs()\n tf_lib_dirs = get_tf_lib_dirs()\n tf_libs = get_tf_libs(build_ext, tf_lib_dirs, cpp_flags)\n tf_abi = get_tf_abi(build_ext, tf_include_dirs,\n tf_lib_dirs, tf_libs, cpp_flags)\n\n compile_flags = []\n for include_dir in tf_include_dirs:\n compile_flags.append('-I%s' % include_dir)\n if tf_abi:\n compile_flags.append('-D%s=%s' % tf_abi)\n\n link_flags = []\n for lib_dir in tf_lib_dirs:\n link_flags.append('-L%s' % lib_dir)\n for lib in tf_libs:\n link_flags.append('-l%s' % lib)\n\n return compile_flags, link_flags\n\n\ndef get_mpi_flags():\n show_command = os.environ.get('HOROVOD_MPICXX_SHOW', 'mpicxx -show')\n try:\n mpi_show_output = subprocess.check_output(\n shlex.split(show_command), universal_newlines=True).strip()\n mpi_show_args = shlex.split(mpi_show_output)\n if not mpi_show_args[0].startswith('-'):\n # Open MPI and MPICH print compiler name as a first word, skip it\n mpi_show_args = mpi_show_args[1:]\n # strip off compiler call portion and always escape each arg\n return ' '.join(['\"' + arg.replace('\"', '\"\\'\"\\'\"') + '\"'\n for arg in mpi_show_args])\n except Exception:\n raise DistutilsPlatformError(\n '%s failed (see error below), is MPI in $PATH?\\n'\n 'Note: If your version of MPI has a custom command to show compilation flags, '\n 'please specify it with the HOROVOD_MPICXX_SHOW environment variable.\\n\\n'\n '%s' % (show_command, traceback.format_exc()))\n\n\ndef test_compile(build_ext, name, code, libraries=None, include_dirs=None, library_dirs=None, macros=None,\n extra_preargs=None):\n test_compile_dir = os.path.join(build_ext.build_temp, 'test_compile')\n if not os.path.exists(test_compile_dir):\n os.makedirs(test_compile_dir)\n\n source_file = os.path.join(test_compile_dir, '%s.cc' % name)\n with open(source_file, 'w') as f:\n f.write(code)\n\n compiler = build_ext.compiler\n [object_file] = compiler.object_filenames([source_file])\n shared_object_file = compiler.shared_object_filename(\n name, output_dir=test_compile_dir)\n\n compiler.compile([source_file], extra_preargs=extra_preargs,\n include_dirs=include_dirs, macros=macros)\n compiler.link_shared_object(\n [object_file], shared_object_file, libraries=libraries, library_dirs=library_dirs)\n\n return shared_object_file\n\n\ndef get_cuda_dirs(build_ext, cpp_flags):\n cuda_include_dirs = []\n cuda_lib_dirs = []\n\n cuda_home = os.environ.get('HOROVOD_CUDA_HOME')\n if cuda_home:\n cuda_include_dirs += ['%s/include' % cuda_home]\n cuda_lib_dirs += ['%s/lib' % cuda_home, '%s/lib64' % cuda_home]\n\n cuda_include = os.environ.get('HOROVOD_CUDA_INCLUDE')\n if cuda_include:\n cuda_include_dirs += [cuda_include]\n\n cuda_lib = os.environ.get('HOROVOD_CUDA_LIB')\n if cuda_lib:\n cuda_lib_dirs += [cuda_lib]\n\n if not cuda_include_dirs and not cuda_lib_dirs:\n # default to /usr/local/cuda\n cuda_include_dirs += ['/usr/local/cuda/include']\n cuda_lib_dirs += ['/usr/local/cuda/lib', '/usr/local/cuda/lib64']\n\n try:\n test_compile(build_ext, 'test_cuda', libraries=['cudart'], include_dirs=cuda_include_dirs,\n library_dirs=cuda_lib_dirs, extra_preargs=cpp_flags, code=textwrap.dedent('''\\\n #include <cuda_runtime.h>\n void test() {\n cudaSetDevice(0);\n }\n '''))\n except (CompileError, LinkError):\n raise DistutilsPlatformError(\n 'CUDA library was not found (see error above).\\n'\n 'Please specify correct CUDA location with the HOROVOD_CUDA_HOME '\n 'environment variable or combination of HOROVOD_CUDA_INCLUDE and '\n 'HOROVOD_CUDA_LIB environment variables.\\n\\n'\n 'HOROVOD_CUDA_HOME - path where CUDA include and lib directories can be found\\n'\n 'HOROVOD_CUDA_INCLUDE - path to CUDA include directory\\n'\n 'HOROVOD_CUDA_LIB - path to CUDA lib directory')\n\n return cuda_include_dirs, cuda_lib_dirs\n\n\ndef get_nccl_vals(build_ext, cuda_include_dirs, cuda_lib_dirs, cpp_flags):\n nccl_include_dirs = []\n nccl_lib_dirs = []\n nccl_libs = []\n\n nccl_home = os.environ.get('HOROVOD_NCCL_HOME')\n if nccl_home:\n nccl_include_dirs += ['%s/include' % nccl_home]\n nccl_lib_dirs += ['%s/lib' % nccl_home, '%s/lib64' % nccl_home]\n\n nccl_include_dir = os.environ.get('HOROVOD_NCCL_INCLUDE')\n if nccl_include_dir:\n nccl_include_dirs += [nccl_include_dir]\n\n nccl_lib_dir = os.environ.get('HOROVOD_NCCL_LIB')\n if nccl_lib_dir:\n nccl_lib_dirs += [nccl_lib_dir]\n\n nccl_link_mode = os.environ.get('HOROVOD_NCCL_LINK', 'STATIC')\n if nccl_link_mode.upper() == 'SHARED':\n nccl_libs += ['nccl']\n else:\n nccl_libs += ['nccl_static']\n\n try:\n test_compile(build_ext, 'test_nccl', libraries=nccl_libs, include_dirs=nccl_include_dirs + cuda_include_dirs,\n library_dirs=nccl_lib_dirs + cuda_lib_dirs, extra_preargs=cpp_flags, code=textwrap.dedent('''\\\n #include <nccl.h>\n #if NCCL_MAJOR < 2\n #error Horovod requires NCCL 2.0 or later version, please upgrade.\n #endif\n void test() {\n ncclUniqueId nccl_id;\n ncclGetUniqueId(&nccl_id);\n }\n '''))\n except (CompileError, LinkError):\n raise DistutilsPlatformError(\n 'NCCL 2.0 library or its later version was not found (see error above).\\n'\n 'Please specify correct NCCL location with the HOROVOD_NCCL_HOME '\n 'environment variable or combination of HOROVOD_NCCL_INCLUDE and '\n 'HOROVOD_NCCL_LIB environment variables.\\n\\n'\n 'HOROVOD_NCCL_HOME - path where NCCL include and lib directories can be found\\n'\n 'HOROVOD_NCCL_INCLUDE - path to NCCL include directory\\n'\n 'HOROVOD_NCCL_LIB - path to NCCL lib directory')\n\n return nccl_include_dirs, nccl_lib_dirs, nccl_libs\n\ndef get_ddl_dirs():\n # Default DDL home\n ddl_home = '/opt/DL/ddl'\n ddl_include_dir = '%s/include' % ddl_home\n ddl_lib_dir = '%s/lib' % ddl_home\n\n if not os.path.exists(ddl_lib_dir):\n raise DistutilsPlatformError('DDL lib was not found. Please, make sure \\'ddl\\' package is installed.')\n if not os.path.exists(ddl_include_dir):\n raise DistutilsPlatformError('DDL include was not found. Please, make sure \\'ddl-dev\\' package is installed.')\n\n return [ddl_include_dir], [ddl_lib_dir]\n\n\ndef get_common_options(build_ext):\n cpp_flags = get_cpp_flags(build_ext)\n mpi_flags = get_mpi_flags()\n\n gpu_allreduce = os.environ.get('HOROVOD_GPU_ALLREDUCE')\n if gpu_allreduce and gpu_allreduce != 'MPI' and gpu_allreduce != 'NCCL' and \\\n gpu_allreduce != 'DDL':\n raise DistutilsError('HOROVOD_GPU_ALLREDUCE=%s is invalid, supported '\n 'values are \"\", \"MPI\", \"NCCL\", \"DDL\".' % gpu_allreduce)\n\n gpu_allgather = os.environ.get('HOROVOD_GPU_ALLGATHER')\n if gpu_allgather and gpu_allgather != 'MPI':\n raise DistutilsError('HOROVOD_GPU_ALLGATHER=%s is invalid, supported '\n 'values are \"\", \"MPI\".' % gpu_allgather)\n\n gpu_broadcast = os.environ.get('HOROVOD_GPU_BROADCAST')\n if gpu_broadcast and gpu_broadcast != 'MPI':\n raise DistutilsError('HOROVOD_GPU_BROADCAST=%s is invalid, supported '\n 'values are \"\", \"MPI\".' % gpu_broadcast)\n\n if gpu_allreduce or gpu_allgather or gpu_broadcast:\n have_cuda = True\n cuda_include_dirs, cuda_lib_dirs = get_cuda_dirs(build_ext, cpp_flags)\n else:\n have_cuda = False\n cuda_include_dirs = cuda_lib_dirs = []\n\n if gpu_allreduce == 'NCCL':\n have_nccl = True\n nccl_include_dirs, nccl_lib_dirs, nccl_libs = get_nccl_vals(\n build_ext, cuda_include_dirs, cuda_lib_dirs, cpp_flags)\n else:\n have_nccl = False\n nccl_include_dirs = nccl_lib_dirs = nccl_libs = []\n\n if gpu_allreduce == 'DDL':\n have_ddl = True\n ddl_include_dirs, ddl_lib_dirs = get_ddl_dirs()\n else:\n have_ddl = False\n ddl_include_dirs = ddl_lib_dirs = []\n\n MACROS = []\n INCLUDES = []\n SOURCES = []\n COMPILE_FLAGS = cpp_flags + shlex.split(mpi_flags)\n LINK_FLAGS = shlex.split(mpi_flags)\n LIBRARY_DIRS = []\n LIBRARIES = []\n\n if have_cuda:\n MACROS += [('HAVE_CUDA', '1')]\n INCLUDES += cuda_include_dirs\n LIBRARY_DIRS += cuda_lib_dirs\n LIBRARIES += ['cudart']\n\n if have_nccl:\n MACROS += [('HAVE_NCCL', '1')]\n INCLUDES += nccl_include_dirs\n LINK_FLAGS += ['-Wl,--version-script=hide_nccl.lds']\n LIBRARY_DIRS += nccl_lib_dirs\n LIBRARIES += nccl_libs\n\n if have_ddl:\n MACROS += [('HAVE_DDL', '1')]\n INCLUDES += ddl_include_dirs\n LIBRARY_DIRS += ddl_lib_dirs\n LIBRARIES += ['ddl', 'ddl_pack']\n\n if gpu_allreduce:\n MACROS += [('HOROVOD_GPU_ALLREDUCE', \"'%s'\" % gpu_allreduce[0])]\n\n if gpu_allgather:\n MACROS += [('HOROVOD_GPU_ALLGATHER', \"'%s'\" % gpu_allgather[0])]\n\n if gpu_broadcast:\n MACROS += [('HOROVOD_GPU_BROADCAST', \"'%s'\" % gpu_broadcast[0])]\n\n return dict(MACROS=MACROS,\n INCLUDES=INCLUDES,\n SOURCES=SOURCES,\n COMPILE_FLAGS=COMPILE_FLAGS,\n LINK_FLAGS=LINK_FLAGS,\n LIBRARY_DIRS=LIBRARY_DIRS,\n LIBRARIES=LIBRARIES)\n\n\ndef build_common_extension(build_ext, options, abi_compile_flags):\n common_mpi_lib.define_macros = options['MACROS']\n common_mpi_lib.include_dirs = options['INCLUDES']\n common_mpi_lib.sources = options['SOURCES'] + ['horovod/common/common.cc',\n 'horovod/common/mpi_message.cc',\n 'horovod/common/operations.cc',\n 'horovod/common/timeline.cc']\n common_mpi_lib.extra_compile_args = options['COMPILE_FLAGS'] + \\\n abi_compile_flags\n common_mpi_lib.extra_link_args = options['LINK_FLAGS']\n common_mpi_lib.library_dirs = options['LIBRARY_DIRS']\n common_mpi_lib.libraries = options['LIBRARIES']\n\n build_ext.build_extension(common_mpi_lib)\n\n\ndef build_tf_extension(build_ext, options):\n check_tf_version()\n tf_compile_flags, tf_link_flags = get_tf_flags(\n build_ext, options['COMPILE_FLAGS'])\n\n tensorflow_mpi_lib.define_macros = options['MACROS']\n tensorflow_mpi_lib.include_dirs = options['INCLUDES']\n tensorflow_mpi_lib.sources = options['SOURCES'] + \\\n ['horovod/tensorflow/mpi_ops.cc']\n tensorflow_mpi_lib.extra_compile_args = options['COMPILE_FLAGS'] + \\\n tf_compile_flags\n tensorflow_mpi_lib.extra_link_args = options['LINK_FLAGS'] + tf_link_flags\n tensorflow_mpi_lib.library_dirs = options['LIBRARY_DIRS']\n tensorflow_mpi_lib.libraries = options['LIBRARIES']\n\n build_ext.build_extension(tensorflow_mpi_lib)\n\n # Return ABI flags used for TensorFlow compilation. We will use this flag\n # to compile all the libraries.\n return [flag for flag in tf_compile_flags if '_GLIBCXX_USE_CXX11_ABI' in flag]\n\n\ndef dummy_import_torch():\n try:\n import torch\n except:\n pass\n\n\ndef check_torch_import():\n try:\n import torch\n except ImportError:\n raise DistutilsPlatformError(\n 'import torch failed, is it installed?\\n\\n%s' % traceback.format_exc())\n\n\ndef is_torch_cuda():\n try:\n from torch.utils.ffi import create_extension\n cuda_test_ext = create_extension(\n name='horovod.torch.test_cuda',\n headers=['horovod/torch/dummy.h'],\n sources=[],\n with_cuda=True,\n extra_compile_args=['-std=c11', '-fPIC', '-O2']\n )\n cuda_test_ext.build()\n return True\n except:\n print('INFO: Above error indicates that this PyTorch installation does not support CUDA.')\n return False\n\n\ndef check_macro(macros, key):\n return any(k == key and v for k, v in macros)\n\n\ndef set_macro(macros, key, new_value):\n if any(k == key for k, _ in macros):\n return [(k, new_value if k == key else v) for k, v in macros]\n else:\n return macros + [(key, new_value)]\n\n\nclass protect_files(object):\n def __init__(self, *files):\n self.files = files\n\n def __enter__(self):\n for file in self.files:\n os.rename(file, file + '.protected')\n\n def __exit__(self, type, value, traceback):\n for file in self.files:\n os.rename(file + '.protected', file)\n\n\ndef build_torch_extension(build_ext, options, abi_compile_flags):\n check_torch_import()\n\n have_cuda = is_torch_cuda()\n if not have_cuda and check_macro(options['MACROS'], 'HAVE_CUDA'):\n raise DistutilsPlatformError(\n 'Horovod build with GPU support was requested, but this PyTorch '\n 'installation does not support CUDA.')\n\n # Update HAVE_CUDA to mean that PyTorch supports CUDA. Internally, we will be checking\n # HOROVOD_GPU_(ALLREDUCE|ALLGATHER|BROADCAST) to decide whether we should use GPU\n # version or transfer tensors to CPU memory for those operations.\n updated_macros = set_macro(\n options['MACROS'], 'HAVE_CUDA', str(int(have_cuda)))\n\n # Create_extension overwrites these files which are customized, we need to protect them.\n with protect_files('horovod/torch/mpi_lib/__init__.py',\n 'horovod/torch/mpi_lib_impl/__init__.py'):\n from torch.utils.ffi import create_extension\n ffi_iface = create_extension(\n name='horovod.torch.mpi_lib',\n headers=['horovod/torch/interface.h'] +\n (['horovod/torch/interface_cuda.h'] if have_cuda else []),\n with_cuda=have_cuda,\n language='c',\n package=True,\n sources=[],\n extra_compile_args=['-std=c11', '-fPIC', '-O2']\n )\n ffi_impl = create_extension(\n name='horovod.torch.mpi_lib_impl',\n headers=[],\n with_cuda=have_cuda,\n language='c++',\n package=True,\n source_extension='.cc',\n define_macros=updated_macros,\n include_dirs=options['INCLUDES'],\n sources=options['SOURCES'] + ['horovod/torch/mpi_ops.cc',\n 'horovod/torch/handle_manager.cc',\n 'horovod/torch/ready_event.cc',\n 'horovod/torch/tensor_util.cc',\n 'horovod/torch/cuda_util.cc',\n 'horovod/torch/adapter.cc'],\n extra_compile_args=options['COMPILE_FLAGS'] + abi_compile_flags,\n extra_link_args=options['LINK_FLAGS'],\n library_dirs=options['LIBRARY_DIRS'],\n libraries=options['LIBRARIES']\n )\n\n for ffi, setuptools_ext in [(ffi_iface, torch_mpi_lib),\n (ffi_impl, torch_mpi_lib_impl)]:\n ffi_ext = ffi.distutils_extension()\n # ffi_ext is distutils Extension, not setuptools Extension\n for k, v in ffi_ext.__dict__.items():\n setuptools_ext.__dict__[k] = v\n build_ext.build_extension(setuptools_ext)\n\n\n# run the customize_compiler\nclass custom_build_ext(build_ext):\n def build_extensions(self):\n options = get_common_options(self)\n abi_compile_flags = []\n built_plugins = []\n # If PyTorch is installed, it must be imported before TensorFlow, otherwise\n # we may get an error: dlopen: cannot load any more object with static TLS\n dummy_import_torch()\n if not os.environ.get('HOROVOD_WITHOUT_TENSORFLOW'):\n try:\n abi_compile_flags = build_tf_extension(self, options)\n built_plugins.append(True)\n except:\n if not os.environ.get('HOROVOD_WITH_TENSORFLOW'):\n print('INFO: Unable to build TensorFlow plugin, will skip it.\\n\\n'\n '%s' % traceback.format_exc(), file=sys.stderr)\n built_plugins.append(False)\n else:\n raise\n if not os.environ.get('HOROVOD_WITHOUT_PYTORCH'):\n try:\n build_torch_extension(self, options, abi_compile_flags)\n built_plugins.append(True)\n except:\n if not os.environ.get('HOROVOD_WITH_PYTORCH'):\n print('INFO: Unable to build PyTorch plugin, will skip it.\\n\\n'\n '%s' % traceback.format_exc(), file=sys.stderr)\n built_plugins.append(False)\n else:\n raise\n if not built_plugins:\n raise DistutilsError(\n 'Both TensorFlow and PyTorch plugins were excluded from build. Aborting.')\n if not any(built_plugins):\n raise DistutilsError(\n 'Neither TensorFlow nor PyTorch plugins were built. See errors above.')\n build_common_extension(self, options, abi_compile_flags)\n\n\nsetup(name='horovod',\n version=__version__,\n packages=find_packages(),\n description='Distributed training framework for TensorFlow, Keras, and PyTorch.',\n author='Uber Technologies, Inc.',\n long_description=textwrap.dedent('''\\\n Horovod is a distributed training framework for TensorFlow, Keras, and PyTorch.\n The goal of Horovod is to make distributed Deep Learning fast and easy to use.'''),\n url='https://github.com/uber/horovod',\n classifiers=[\n 'License :: OSI Approved :: Apache Software License'\n ],\n ext_modules=[common_mpi_lib, tensorflow_mpi_lib,\n torch_mpi_lib, torch_mpi_lib_impl],\n cmdclass={'build_ext': custom_build_ext},\n # cffi is required for PyTorch\n # If cffi is specified in setup_requires, it will need libffi to be installed on the machine,\n # which is undesirable. Luckily, `install` action will install cffi before executing build,\n # so it's only necessary for `build*` or `bdist*` actions.\n setup_requires=['cffi>=1.4.0'] if is_build_action() else [],\n install_requires=['cffi>=1.4.0'],\n zip_safe=False)\n",
"import tvm\nimport tvm.contrib.sparse as tvmsp\nimport tvm.ndarray as _nd\nimport numpy as np\nfrom collections import namedtuple\n\ndef test_static_tensor():\n dtype = 'float32'\n stype = 'csr'\n target = 'llvm'\n ctx = tvm.context(target, 0)\n m = tvm.var('m')\n n = tvm.var('n')\n A = tvmsp.placeholder(shape=(m, n), name='A', dtype=dtype)\n assert(A.stype == 'csr')\n n = 3\n a = np.maximum(np.random.uniform(size=(n,n)).astype(dtype)-.6, 0.)\n a = tvmsp.array(a, ctx)\n A.data = tvm.placeholder(a.data.shape, dtype, name='A_data')\n Ab = tvm.decl_buffer(a.data.shape, dtype, name='A_data')\n binds = {A.data: Ab}\n C = tvm.compute(A.data.shape, lambda i: A.data[i] * 2., tag='cs_scatter')\n s = tvm.create_schedule(C.op)\n f = tvm.build(s, [A.data, C], target, binds=binds)\n c = tvmsp.array(np.zeros((n,n), dtype), ctx)\n c.data = tvm.nd.empty(a.data.shape, dtype)\n c.indices = a.indices\n c.indptr = a.indptr\n f(a.data, c.data)\n np.testing.assert_allclose(c.asnumpy(), a.asnumpy() * 2., rtol=1e-5)\n\ndef test_dynamic_tensor():\n dtype = 'float32'\n stype = 'csr'\n target = 'llvm'\n ctx = tvm.context(target, 0)\n nr, nc, n = tvm.var('nr'), tvm.var('nc'), tvm.var('n')\n A = tvmsp.placeholder(shape=(nr, nc), nonzeros=n, name='A', dtype=dtype)\n assert(A.stype == 'csr')\n C = tvm.compute(A.data.shape, lambda i: A.data[i] * 2., tag='cs_scatter')\n s = tvm.create_schedule(C.op)\n _nr, _nc = 3, 5\n a = np.maximum(np.random.uniform(size=(_nr, _nc)).astype(dtype)-.6, 0.)\n a = tvmsp.array(a, ctx)\n assert a.data.dtype == a.dtype\n Ab = namedtuple('CSRBuffer', ['data', 'indices', 'indptr'])\n Ab.data = tvm.decl_buffer(a.data.shape, a.data.dtype, name='A_data')\n Ab.indices = tvm.decl_buffer(a.data.shape, a.data.dtype, name='A_indices')\n binds = {A.data: Ab.data, A.indices: Ab.indices}\n f = tvm.build(s, [nr, A.data, C], target, binds=binds)\n c = tvmsp.array(np.zeros((_nr, _nc), dtype), ctx)\n c.data = tvm.nd.empty(a.data.shape, dtype)\n c.indices = a.indices\n c.indptr = a.indptr\n f(a.data.shape[0], a.data, c.data)\n np.testing.assert_allclose(c.asnumpy(), a.asnumpy() * 2., rtol=1e-5)\n\ndef test_sparse_array_tuple():\n dtype, itype = 'float32', 'int32'\n stype = 'csr'\n target = 'llvm'\n ctx = tvm.context(target, 0)\n nr, nc, n = tvm.var('nr'), tvm.var('nc'), tvm.var('n')\n A = tvmsp.placeholder(shape=(nr, nc), nonzeros=n, name='A', dtype=dtype)\n assert(A.stype == 'csr')\n C = tvm.compute(A.data.shape, lambda i: A.data[i] * 2., tag='cs_scatter')\n s = tvm.create_schedule(C.op)\n _nr, _nc = 3, 5\n a = np.maximum(np.random.uniform(size=(_nr, _nc)).astype(dtype)-.6, 0.)\n # convert to sparse array tuple\n source_array = a\n ridx, cidx = np.nonzero(source_array)\n data = source_array[ridx, cidx]\n a_data = _nd.array(data, ctx)\n indices = np.nonzero(source_array)[1].astype(itype)\n a_indices = _nd.array(indices, ctx)\n indptr = [0]+np.apply_along_axis(np.count_nonzero, axis=1, arr=source_array).tolist()\n indptr = np.cumsum(np.array(indptr, itype)).astype(itype)\n a_indptr = _nd.array(indptr, ctx)\n a_init = (a_data, a_indices, a_indptr)\n # construct tvm sparse array with tuple\n a = tvmsp.array(a_init, shape=source_array.shape, ctx=ctx)\n assert a.data.dtype == a.dtype\n Ab = namedtuple('CSRBuffer', ['data', 'indices', 'indptr'])\n Ab.data = tvm.decl_buffer(a.data.shape, a.data.dtype, name='A_data')\n Ab.indices = tvm.decl_buffer(a.data.shape, a.data.dtype, name='A_indices')\n binds = {A.data: Ab.data, A.indices: Ab.indices}\n f = tvm.build(s, [nr, A.data, C], target, binds=binds)\n c = tvmsp.array(np.zeros((_nr, _nc), dtype), ctx)\n c.data = tvm.nd.empty(a.data.shape, dtype)\n c.indices = a.indices\n c.indptr = a.indptr\n f(a.data.shape[0], a.data, c.data)\n np.testing.assert_allclose(c.asnumpy(), a.asnumpy() * 2., rtol=1e-5)\n\nif __name__ == \"__main__\":\n test_static_tensor()\n test_dynamic_tensor()\n test_sparse_array_tuple()\n\n",
"import math\nimport torch\nimport numbers\nfrom torch.nn.parameter import Parameter\nfrom torch.nn import init\n\nimport fused_layer_norm_cuda\n\nclass FusedLayerNormAffineFunction(torch.autograd.Function):\n def __init__(self, normalized_shape, eps=1e-6):\n self.normalized_shape = normalized_shape\n self.eps = eps\n\n def forward(self, input, weight, bias):\n input_ = input.contiguous()\n weight_ = weight.contiguous()\n bias_ = bias.contiguous()\n output, mean, invvar = fused_layer_norm_cuda.forward_affine(\n input_, self.normalized_shape, weight_, bias_, self.eps)\n self.save_for_backward(input_, weight_, bias_, mean, invvar)\n return output\n\n def backward(self, grad_output):\n input_, weight_, bias_, mean, invvar = self.saved_tensors\n grad_input = grad_weight = grad_bias = None\n grad_input, grad_weight, grad_bias = fused_layer_norm_cuda.backward_affine(\n grad_output.contiguous(), mean, invvar,\n input_, self.normalized_shape, \n weight_, bias_, self.eps)\n return grad_input, grad_weight, grad_bias;\n \nclass FusedLayerNormFunction(torch.autograd.Function):\n def __init__(self, normalized_shape, eps=1e-6):\n self.normalized_shape = normalized_shape\n self.eps = eps\n\n def forward(self, input):\n input_ = input.contiguous()\n output, mean, invvar = fused_layer_norm_cuda.forward(\n input_, self.normalized_shape, self.eps)\n self.save_for_backward(input_, mean, invvar)\n return output\n\n def backward(self, grad_output):\n input_, mean, invvar = self.saved_tensors\n grad_input = None\n grad_input = fused_layer_norm_cuda.backward(\n grad_output.contiguous(), mean, invvar,\n input_, self.normalized_shape,\n self.eps)\n return grad_input\n\ndef fused_layer_norm_affine(input, normalized_shape, weight, bias, eps=1e-6):\n return FusedLayerNormAffineFunction(normalized_shape,eps)(input, weight, bias)\n\ndef fused_layer_norm(input, normalized_shape, eps=1e-6):\n return FusedLayerNormFunction(normalized_shape,eps)(input)\n\nclass FusedLayerNorm(torch.nn.Module):\n r\"\"\"Applies Layer Normalization over a mini-batch of inputs as described in\n the paper `Layer Normalization`_ .\n\n .. math::\n y = \\frac{x - \\mathrm{E}[x]}{ \\sqrt{\\mathrm{Var}[x] + \\epsilon}} * \\gamma + \\beta\n\n The mean and standard-deviation are calculated separately over the last\n certain number dimensions which have to be of the shape specified by\n :attr:`normalized_shape`.\n :math:`\\gamma` and :math:`\\beta` are learnable affine transform parameters of\n :attr:`normalized_shape` if :attr:`elementwise_affine` is ``True``.\n\n .. note::\n Unlike Batch Normalization and Instance Normalization, which applies\n scalar scale and bias for each entire channel/plane with the\n :attr:`affine` option, Layer Normalization applies per-element scale and\n bias with :attr:`elementwise_affine`.\n\n This layer uses statistics computed from input data in both training and\n evaluation modes.\n\n Args:\n normalized_shape (int or list or torch.Size): input shape from an expected input\n of size\n\n .. math::\n [* \\times \\text{normalized\\_shape}[0] \\times \\text{normalized\\_shape}[1]\n \\times \\ldots \\times \\text{normalized\\_shape}[-1]]\n\n If a single integer is used, it is treated as a singleton list, and this module will\n normalize over the last dimension which is expected to be of that specific size.\n eps: a value added to the denominator for numerical stability. Default: 1e-5\n elementwise_affine: a boolean value that when set to ``True``, this module\n has learnable per-element affine parameters initialized to ones (for weights)\n and zeros (for biases). Default: ``True``.\n\n Shape:\n - Input: :math:`(N, *)`\n - Output: :math:`(N, *)` (same shape as input)\n\n Examples::\n\n >>> input = torch.randn(20, 5, 10, 10)\n >>> # With Learnable Parameters\n >>> m = nn.LayerNorm(input.size()[1:])\n >>> # Without Learnable Parameters\n >>> m = nn.LayerNorm(input.size()[1:], elementwise_affine=False)\n >>> # Normalize over last two dimensions\n >>> m = nn.LayerNorm([10, 10])\n >>> # Normalize over last dimension of size 10\n >>> m = nn.LayerNorm(10)\n >>> # Activating the module\n >>> output = m(input)\n\n .. _`Layer Normalization`: https://arxiv.org/abs/1607.06450\n \"\"\"\n def __init__(self, normalized_shape, eps=1e-5, elementwise_affine=True):\n super(FusedLayerNorm, self).__init__()\n if isinstance(normalized_shape, numbers.Integral):\n normalized_shape = (normalized_shape,)\n self.normalized_shape = torch.Size(normalized_shape)\n self.eps = eps\n self.elementwise_affine = elementwise_affine\n if self.elementwise_affine:\n self.weight = Parameter(torch.Tensor(*normalized_shape))\n self.bias = Parameter(torch.Tensor(*normalized_shape))\n else:\n self.register_parameter('weight', None)\n self.register_parameter('bias', None)\n self.reset_parameters()\n\n def reset_parameters(self):\n if self.elementwise_affine:\n init.ones_(self.weight)\n init.zeros_(self.bias)\n\n def forward(self, input):\n if self.elementwise_affine:\n return FusedLayerNormAffineFunction(self.normalized_shape,self.eps)(\n input, self.weight, self.bias)\n else:\n return FusedLayerNormFunction(self.normalized_shape,self.eps)(\n input)\n\n def extra_repr(self):\n return '{normalized_shape}, eps={eps}, ' \\\n 'elementwise_affine={elementwise_affine}'.format(**self.__dict__)\n",
"import tvm\nimport topi\nimport numpy as np\nfrom tvm.contrib.pickle_memoize import memoize\nfrom scipy import signal\nfrom topi.util import get_const_tuple\nfrom topi.nn.util import get_pad_tuple\nimport topi.testing\nfrom topi.cuda.depthwise_conv2d import schedule_depthwise_conv2d_backward_input_nhwc\n\n\ndef verify_depthwise_conv2d_back_input(batch, in_channel, in_h, channel_multiplier, filter_h, stride_h, padding_h):\n in_w = in_h\n filter_channel = in_channel\n filter_w = filter_h\n stride_w = stride_h\n padding_w = padding_h\n\n out_h = np.int((in_h+2*padding_h-filter_h)/stride_h+1)\n out_w = np.int((in_w+2*padding_w-filter_w)/stride_w+1)\n out_channel = in_channel * channel_multiplier\n\n ishape = [batch, in_h, in_w, in_channel]\n oshape = [batch, out_h, out_w, out_channel]\n\n # placeholder\n Out_grad = tvm.placeholder(oshape, name='Out_grad')\n Filter = tvm.placeholder((filter_h, filter_w, filter_channel, channel_multiplier))\n # declare\n In_grad = topi.nn.depthwise_conv2d_backward_input_nhwc(Filter, Out_grad, oshape, ishape,\n stride=[stride_h, stride_w], padding=[padding_h, padding_w])\n # schedule\n schedule = schedule_depthwise_conv2d_backward_input_nhwc(In_grad)\n\n def check_device(device):\n ctx = tvm.context(device, 0)\n if not ctx.exist:\n print(\"Skip because %s is not enabled\" % device)\n return\n print(\"Running on target: %s\" % device)\n # build the kernel\n f = tvm.build(schedule, [Filter, Out_grad, In_grad], device)\n # prepare pod type for test data closure\n dtype = Out_grad.dtype\n out_grad_shape = get_const_tuple(Out_grad.shape)\n filter_shape = get_const_tuple(Filter.shape)\n\n # use memoize to pickle the test data for next time use\n @memoize(\"topi.tests.test_topi_depthwise_conv2d_backward_input.nhwc\")\n def get_ref_data():\n out_grad_np = np.random.uniform(size=out_grad_shape).astype(dtype)\n filter_np = np.random.uniform(size=filter_shape).astype(dtype)\n dilated_out_grad_np = topi.testing.dilate_python(out_grad_np, [1, stride_h, stride_w, 1])\n # padding params in forward propagation\n fpad_top, fpad_left, fpad_bottom, fpad_right = get_pad_tuple([padding_h, padding_w], (filter_h, filter_w))\n # padding params in backward propagation\n bpad_top = filter_h - 1 - fpad_top\n bpad_bottom = (filter_h - 1 - fpad_bottom) + (stride_h - 1)\n bpad_left = filter_w - 1 - fpad_left\n bpad_right = (filter_w - 1 - fpad_right) + (stride_w - 1)\n\n padded_out_grad = np.zeros((batch, dilated_out_grad_np.shape[1]+bpad_top+bpad_bottom,\n dilated_out_grad_np.shape[2]+bpad_left+bpad_right, out_channel))\n padded_out_grad[:, bpad_top:dilated_out_grad_np.shape[1]+bpad_top,\n bpad_left:dilated_out_grad_np.shape[2]+bpad_left, :] = dilated_out_grad_np\n\n in_grad_np = np.zeros((batch, in_h, in_w, in_channel))\n for b in range(batch):\n for c in range(in_channel):\n for m in range(channel_multiplier):\n in_grad_np[b, :, :, c] += signal.convolve2d(padded_out_grad[b, :, :, c*channel_multiplier+m], \\\n filter_np[:, :, c, m], mode='valid')[0:in_h, 0:in_w]\n return (out_grad_np, filter_np, in_grad_np)\n\n (out_grad_np, filter_np, in_grad_np) = get_ref_data()\n\n out_grad_tvm = tvm.nd.array(out_grad_np, ctx)\n filter_tvm = tvm.nd.array(filter_np, ctx)\n in_grad_tvm = tvm.nd.array(np.zeros(shape=ishape, dtype=dtype), ctx)\n # launch the kernel\n timer = f.time_evaluator(f.entry_name, ctx, number=1)\n tcost = timer(filter_tvm, out_grad_tvm, in_grad_tvm).mean\n np.testing.assert_allclose(in_grad_np, in_grad_tvm.asnumpy(), rtol=1e-5)\n\n check_device(\"opencl\")\n check_device(\"cuda\")\n check_device(\"metal\")\n check_device(\"rocm\")\n check_device(\"vulkan\")\n check_device(\"nvptx\")\n\ndef test_topi_depthwise_conv2d_backward_input_nhwc():\n verify_depthwise_conv2d_back_input(16, 256, 56, 1, 3, 1, 1)\n verify_depthwise_conv2d_back_input(16, 256, 56, 2, 3, 1, 1)\n verify_depthwise_conv2d_back_input(16, 256, 56, 1, 5, 1, 2)\n verify_depthwise_conv2d_back_input(16, 256, 56, 2, 5, 1, 2)\n verify_depthwise_conv2d_back_input(16, 256, 56, 1, 3, 2, 1)\n verify_depthwise_conv2d_back_input(16, 256, 56, 2, 3, 2, 1)\n verify_depthwise_conv2d_back_input(16, 256, 56, 1, 5, 2, 2)\n verify_depthwise_conv2d_back_input(16, 256, 56, 2, 5, 2, 2)\n\n verify_depthwise_conv2d_back_input(16, 256, 56, 1, 3, 1, 0)\n verify_depthwise_conv2d_back_input(16, 256, 56, 2, 3, 1, 0)\n verify_depthwise_conv2d_back_input(16, 256, 56, 1, 5, 1, 0)\n verify_depthwise_conv2d_back_input(16, 256, 56, 2, 5, 1, 0)\n verify_depthwise_conv2d_back_input(16, 256, 56, 1, 3, 2, 0)\n verify_depthwise_conv2d_back_input(16, 256, 56, 2, 3, 2, 0)\n verify_depthwise_conv2d_back_input(16, 256, 56, 1, 5, 2, 0)\n verify_depthwise_conv2d_back_input(16, 256, 56, 2, 5, 2, 0)\n\n\nif __name__ == \"__main__\":\n test_topi_depthwise_conv2d_backward_input_nhwc()\n",
"#!/usr/bin/env python3 -u\n# Copyright (c) 2017-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the LICENSE file in\n# the root directory of this source tree. An additional grant of patent rights\n# can be found in the PATENTS file in the same directory.\n\nimport numpy as np\nimport torch\n\nfrom fairseq import data, options, progress_bar, tasks, utils\nfrom fairseq.meters import StopwatchMeter, TimeMeter\nfrom fairseq.sequence_scorer import SequenceScorer\n\n\ndef main(args):\n assert args.path is not None, '--path required for evaluation!'\n\n args.tokens_per_sample = getattr(args, 'tokens_per_sample', 1024)\n print(args)\n\n use_cuda = torch.cuda.is_available() and not args.cpu\n\n # Load dataset splits\n task = tasks.setup_task(args)\n task.load_dataset(args.gen_subset)\n print('| {} {} {} examples'.format(args.data, args.gen_subset, len(task.dataset(args.gen_subset))))\n\n # Load ensemble\n print('| loading model(s) from {}'.format(args.path))\n models, _ = utils.load_ensemble_for_inference(args.path.split(':'), task)\n\n # Optimize ensemble for generation and set the source and dest dicts on the model (required by scorer)\n for model in models:\n model.make_generation_fast_()\n if args.fp16:\n model.half()\n\n assert len(models) > 0\n\n itr = data.EpochBatchIterator(\n dataset=task.dataset(args.gen_subset),\n max_tokens=args.max_tokens or 36000,\n max_sentences=args.max_sentences,\n max_positions=models[0].max_positions(),\n num_shards=args.num_shards,\n shard_id=args.shard_id,\n ignore_invalid_inputs=True,\n ).next_epoch_itr(shuffle=False)\n\n gen_timer = StopwatchMeter()\n scorer = SequenceScorer(models, task.target_dictionary)\n if use_cuda:\n scorer.cuda()\n\n score_sum = 0.\n count = 0\n\n if args.remove_bpe is not None:\n bpe_cont = args.remove_bpe.rstrip()\n bpe_toks = set(i for i in range(len(task.dictionary)) if task.dictionary[i].endswith(bpe_cont))\n bpe_len = len(bpe_cont)\n else:\n bpe_toks = None\n bpe_len = 0\n\n with progress_bar.build_progress_bar(args, itr) as t:\n results = scorer.score_batched_itr(t, cuda=use_cuda, timer=gen_timer)\n wps_meter = TimeMeter()\n for _, src_tokens, __, hypos in results:\n for hypo in hypos:\n pos_scores = hypo['positional_scores']\n\n skipped_toks = 0\n if bpe_toks is not None:\n for i in range(len(hypo['tokens']) - 1):\n if hypo['tokens'][i].item() in bpe_toks:\n skipped_toks += 1\n pos_scores[i + 1] += pos_scores[i]\n pos_scores[i] = 0\n\n inf_scores = pos_scores.eq(float('inf')) | pos_scores.eq(float('-inf'))\n if inf_scores.any():\n print('| Skipping tokens with inf scores:',\n task.target_dictionary.string(hypo['tokens'][inf_scores.nonzero()]))\n pos_scores = pos_scores[(~inf_scores).nonzero()]\n score_sum += pos_scores.sum()\n count += pos_scores.numel() - skipped_toks\n\n if args.output_word_probs:\n w = ''\n word_prob = []\n for i in range(len(hypo['tokens'])):\n w_ind = hypo['tokens'][i].item()\n w += task.dictionary[w_ind]\n if bpe_toks is not None and w_ind in bpe_toks:\n w = w[:-bpe_len]\n else:\n word_prob.append((w, pos_scores[i].item()))\n w = ''\n print('\\t'.join('{} [{:2f}]'.format(x[0], x[1]) for x in word_prob))\n\n wps_meter.update(src_tokens.size(0))\n t.log({'wps': round(wps_meter.avg)})\n\n avg_nll_loss = -score_sum / count\n print('| Evaluated {} tokens in {:.1f}s ({:.2f} tokens/s)'.format(gen_timer.n, gen_timer.sum, 1. / gen_timer.avg))\n print('| Loss: {:.4f}, Perplexity: {:.2f}'.format(avg_nll_loss, np.exp(avg_nll_loss)))\n\n\nif __name__ == '__main__':\n parser = options.get_eval_lm_parser()\n args = options.parse_args_and_arch(parser)\n main(args)\n",
"# Copyright 2018 Google. 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\"\"\"Utils for SSD train/eval with low level API.\"\"\"\n\nfrom absl import flags\n\nimport tensorflow as tf\n\nFLAGS = flags.FLAGS\n\n\ndef wrap_computation_in_while_loop(op_fn, n, host_name):\n \"\"\"Wraps the ops generated by `op_fn` in tf.while_loop.\"\"\"\n\n def computation(i):\n ops = op_fn()\n if not isinstance(ops, list):\n ops = [ops]\n with tf.control_dependencies(ops):\n return i + 1\n\n with tf.device(device_for_host(host_name)):\n return tf.while_loop(\n lambda i: tf.less(i, n),\n computation, [tf.constant(0)],\n parallel_iterations=1)\n\n\ndef device_for_host(host_name):\n return host_name + '/device:CPU:0'\n\n\ndef device_for_tpu_core(host_name, core=0):\n return host_name + '/device:TPU_REPLICATED_CORE:%d' % core\n\n\ndef tpu_ordinal_fn(shard_index_in_host):\n \"\"\"Return the TPU ordinal associated with a shard.\"\"\"\n return shard_index_in_host % FLAGS.num_shards_per_host\n\n\nclass InputDimsFlattener(object):\n \"\"\"\"Flatten input_partition_dims for spatial partition.\"\"\"\n\n def __init__(self, input_partition_dims):\n self._initialized = False\n self._flattened_input_dims = None\n\n # This should have been validated in TPUConfig.\n assert len(input_partition_dims) <= 2, 'must have 1 or 2 elements.'\n if len(input_partition_dims) == 2:\n self._feature_dims, self._label_dims = input_partition_dims\n else:\n self._feature_dims = input_partition_dims[0]\n self._label_dims = None\n\n assert self._feature_dims is not None, ('input_partition_dims[0] must not '\n 'be None')\n\n @property\n def flattened_input_dims(self):\n assert self._initialized, 'InputsStructureRecorder is not initialized.'\n return self._flattened_input_dims\n\n def validate_and_flatten_input_dims(self, features, labels):\n \"\"\"Flatten input dims with the same order as flattened input tensors.\"\"\"\n\n def _extract_key_names(tensor_or_dict):\n if isinstance(tensor_or_dict, dict):\n return sorted(tensor_or_dict.keys())\n return []\n\n if self._initialized:\n return self._flattened_input_dims\n\n has_labels = labels is not None\n feature_names = _extract_key_names(features)\n label_names = _extract_key_names(labels)\n feature_dims_names = _extract_key_names(self._feature_dims)\n if feature_dims_names != feature_names:\n raise ValueError('TPUConfig.input_partition_dims[0] mismatched feature'\n ' keys. Expected {}, got {}'.format(\n feature_names, feature_dims_names))\n\n label_dims_names = _extract_key_names(self._label_dims)\n if self._label_dims is not None and label_dims_names != label_names:\n raise ValueError('TPUConfig.input_partition_dims[1] mismatched label'\n ' keys. Expected {}, got {}'.format(\n label_names, label_dims_names))\n\n flattened_input_dims = []\n if feature_dims_names:\n # We need a fixed ordering for matching the tensors in features.\n flattened_input_dims.extend(\n [self._feature_dims[name] for name in feature_dims_names])\n else:\n flattened_input_dims.append(self._feature_dims)\n\n if label_dims_names:\n # We need a fixed ordering for matching the tensors in labels.\n flattened_input_dims.extend(\n [self._label_dims[name] for name in label_dims_names])\n else:\n if label_names:\n num_tensors_in_label = len(label_names)\n else:\n num_tensors_in_label = int(has_labels)\n # Setting `None` in input_partition_dims[1] will apply `None` to\n # all the tensors in labels, regardless of internal structure.\n flattened_input_dims.extend([self._label_dims] * num_tensors_in_label)\n\n self._flattened_input_dims = flattened_input_dims\n self._initialized = True\n",
"# coding=utf-8\n# Copyright 2018 The Tensor2Tensor Authors.\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\"\"\"Data generators for the CNN and Daily Mail datasets.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport hashlib\nimport io\nimport os\nimport tarfile\nimport six\nfrom tensor2tensor.data_generators import generator_utils\nfrom tensor2tensor.data_generators import problem\nfrom tensor2tensor.data_generators import text_encoder\nfrom tensor2tensor.data_generators import text_problems\nfrom tensor2tensor.utils import registry\n\nimport tensorflow as tf\n\n# Links to data from http://cs.nyu.edu/~kcho/DMQA/\n_CNN_STORIES_DRIVE_URL = \"https://drive.google.com/uc?export=download&id=0BwmD_VLjROrfTHk4NFg2SndKcjQ\"\n\n_DAILYMAIL_STORIES_DRIVE_URL = \"https://drive.google.com/uc?export=download&id=0BwmD_VLjROrfM1BxdkxVaTY2bWs\"\n\n# Note: using See et al. (2017) as reference for data generation\n# For more info, use the links below\n\n# Train/Dev/Test Splits for summarization data\n_TRAIN_URLS = \"https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_train.txt\"\n_DEV_URLS = \"https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_val.txt\"\n_TEST_URLS = \"https://raw.githubusercontent.com/abisee/cnn-dailymail/master/url_lists/all_test.txt\"\n\n# End-of-sentence marker.\nEOS = text_encoder.EOS_ID\n\n# Techniques for data prep from See et al. (2017)\ndm_single_close_quote = u\"\\u2019\" # unicode\ndm_double_close_quote = u\"\\u201d\"\n# Acceptable ways to end a sentence.\nEND_TOKENS = [\n u\".\", u\"!\", u\"?\", u\"...\", u\"'\", u\"`\", u\"\\\"\", dm_single_close_quote,\n dm_double_close_quote, u\")\"\n]\n\n\ndef _maybe_download_corpora(tmp_dir, dataset_split):\n \"\"\"Download corpora if necessary and unzip them.\n\n Args:\n tmp_dir: directory containing dataset.\n dataset_split: whether we're in train/dev/test mode.\n\n Returns:\n List of all files generated and path to file containing\n train/dev/test split info.\n \"\"\"\n cnn_filename = \"cnn_stories.tgz\"\n cnn_finalpath = os.path.join(tmp_dir, \"cnn/stories/\")\n dailymail_filename = \"dailymail_stories.tgz\"\n dailymail_finalpath = os.path.join(tmp_dir, \"dailymail/stories/\")\n if not tf.gfile.Exists(cnn_finalpath):\n cnn_file = generator_utils.maybe_download_from_drive(\n tmp_dir, cnn_filename, _CNN_STORIES_DRIVE_URL)\n with tarfile.open(cnn_file, \"r:gz\") as cnn_tar:\n cnn_tar.extractall(tmp_dir)\n if not tf.gfile.Exists(dailymail_finalpath):\n dailymail_file = generator_utils.maybe_download_from_drive(\n tmp_dir, dailymail_filename, _DAILYMAIL_STORIES_DRIVE_URL)\n with tarfile.open(dailymail_file, \"r:gz\") as dailymail_tar:\n dailymail_tar.extractall(tmp_dir)\n\n cnn_files = tf.gfile.Glob(cnn_finalpath + \"*\")\n dailymail_files = tf.gfile.Glob(dailymail_finalpath + \"*\")\n all_files = cnn_files + dailymail_files\n\n if dataset_split == problem.DatasetSplit.TRAIN:\n urls_path = generator_utils.maybe_download(tmp_dir, \"all_train.txt\",\n _TRAIN_URLS)\n elif dataset_split == problem.DatasetSplit.EVAL:\n urls_path = generator_utils.maybe_download(tmp_dir, \"all_val.txt\",\n _DEV_URLS)\n else:\n urls_path = generator_utils.maybe_download(tmp_dir, \"all_test.txt\",\n _TEST_URLS)\n\n return all_files, urls_path\n\n\ndef example_splits(url_file, all_files):\n \"\"\"Generate splits of the data.\"\"\"\n\n def generate_hash(inp):\n \"\"\"Generate a sha1 hash to match the raw url to the filename extracted.\"\"\"\n h = hashlib.sha1()\n h.update(inp)\n return h.hexdigest()\n\n all_files_map = {f.split(\"/\")[-1]: f for f in all_files}\n\n urls = []\n for line in tf.gfile.Open(url_file):\n urls.append(line.strip().encode(\"utf-8\"))\n\n filelist = []\n for url in urls:\n url_hash = generate_hash(url)\n filename = url_hash + \".story\"\n if filename not in all_files_map:\n tf.logging.info(\"Missing file: %s\" % url)\n continue\n filelist.append(all_files_map[filename])\n\n tf.logging.info(\"Found %d examples\" % len(filelist))\n\n return filelist\n\n\ndef example_generator(all_files, urls_path, sum_token):\n \"\"\"Generate examples.\"\"\"\n\n def fix_run_on_sents(line):\n if u\"@highlight\" in line:\n return line\n if not line:\n return line\n if line[-1] in END_TOKENS:\n return line\n return line + u\".\"\n\n filelist = example_splits(urls_path, all_files)\n story_summary_split_token = u\" <summary> \" if sum_token else \" \"\n\n for story_file in filelist:\n story = []\n summary = []\n reading_highlights = False\n for line in tf.gfile.Open(story_file, \"rb\"):\n if six.PY2:\n line = unicode(line.strip(), \"utf-8\")\n else:\n line = line.strip().decode(\"utf-8\")\n line = fix_run_on_sents(line)\n if not line:\n continue\n elif line.startswith(u\"@highlight\"):\n if not story:\n break # No article text.\n reading_highlights = True\n elif reading_highlights:\n summary.append(line)\n else:\n story.append(line)\n\n if (not story) or not summary:\n continue\n\n yield \" \".join(story) + story_summary_split_token + \" \".join(summary)\n\n\ndef _story_summary_split(story):\n split_str = u\" <summary> \"\n split_str_len = len(split_str)\n split_pos = story.find(split_str)\n return story[:split_pos], story[split_pos + split_str_len:] # story, summary\n\n\ndef write_raw_text_to_files(all_files, urls_path, dataset_split, tmp_dir):\n \"\"\"Write text to files.\"\"\"\n\n def write_to_file(all_files, urls_path, tmp_dir, filename):\n with io.open(os.path.join(tmp_dir, filename + \".source\"), \"w\") as fstory:\n with io.open(os.path.join(tmp_dir, filename + \".target\"),\n \"w\") as fsummary:\n for example in example_generator(all_files, urls_path, sum_token=True):\n story, summary = _story_summary_split(example)\n fstory.write(story + \"\\n\")\n fsummary.write(summary + \"\\n\")\n\n if dataset_split == problem.DatasetSplit.TRAIN:\n filename = \"cnndm.train\"\n elif dataset_split == problem.DatasetSplit.EVAL:\n filename = \"cnndm.dev\"\n else:\n filename = \"cnndm.test\"\n\n tf.logging.info(\"Writing %s\" % filename)\n write_to_file(all_files, urls_path, tmp_dir, filename)\n\n\[email protected]_problem\nclass SummarizeCnnDailymail32k(text_problems.Text2TextProblem):\n \"\"\"Summarize CNN and Daily Mail articles to their summary highlights.\"\"\"\n\n def generate_text_for_vocab(self, data_dir, tmp_dir):\n del data_dir\n all_files, urls_path = _maybe_download_corpora(tmp_dir,\n problem.DatasetSplit.TRAIN)\n return example_generator(all_files, urls_path, sum_token=False)\n\n @property\n def dataset_splits(self):\n \"\"\"Splits of data to produce and number of output shards for each.\"\"\"\n return [{\n \"split\": problem.DatasetSplit.TRAIN,\n \"shards\": 100,\n }, {\n \"split\": problem.DatasetSplit.EVAL,\n \"shards\": 10,\n }, {\n \"split\": problem.DatasetSplit.TEST,\n \"shards\": 10,\n }]\n\n def is_generate_per_split(self):\n return True\n\n def generate_samples(self, data_dir, tmp_dir, dataset_split):\n del data_dir\n all_files, urls_path = _maybe_download_corpora(tmp_dir, dataset_split)\n write_raw_text_to_files(all_files, urls_path, dataset_split, tmp_dir)\n for example in example_generator(all_files, urls_path, sum_token=True):\n story, summary = _story_summary_split(example)\n yield {\"inputs\": story, \"targets\": summary}\n",
"# Copyright 2018 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\"\"\"Training script for Mask-RCNN.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport multiprocessing\nfrom absl import app\nfrom absl import flags\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.ops import control_flow_util\n\nimport coco_metric\nimport dataloader\nimport mask_rcnn_model\nimport mask_rcnn_params\nimport mask_rcnn_runner\nimport runner_utils\nfrom mlp_log import mlp_log\n\n# Cloud TPU Cluster Resolvers\nflags.DEFINE_string(\n 'gcp_project', default=None,\n help='Project name for the Cloud TPU-enabled project. If not specified, we '\n 'will attempt to automatically detect the GCE project from metadata.')\nflags.DEFINE_string(\n 'tpu_zone', default=None,\n help='GCE zone where the Cloud TPU is located in. If not specified, we '\n 'will attempt to automatically detect the GCE project from metadata.')\nflags.DEFINE_string(\n 'tpu', default=None,\n help='Name of the Cloud TPU for Cluster Resolvers.')\nflags.DEFINE_string(\n 'master',\n default=None,\n help='Name of the Cloud TPU for Cluster Resolvers. You must specify either '\n 'this flag or --master.')\n\n# Model specific paramenters\nflags.DEFINE_string('tpu_job_name', default=None, help='The tpu worker name.')\nflags.DEFINE_string(\n 'eval_master', default='',\n help='GRPC URL of the eval master. Set to an appropiate value when running '\n 'on CPU/GPU')\nflags.DEFINE_bool('use_tpu', True, 'Use TPUs rather than CPUs')\nflags.DEFINE_string('hparams', '',\n 'Comma separated k=v pairs of hyperparameters.')\nflags.DEFINE_integer(\n 'num_cores', default=8, help='Number of TPU cores for training')\nflags.DEFINE_multi_integer(\n 'input_partition_dims', None,\n 'A list that describes the partition dims for all the tensors.')\n\nflags.DEFINE_string('model_dir', None, 'Location of model_dir')\nflags.DEFINE_string('resnet_checkpoint', '',\n 'Location of the ResNet50 checkpoint to use for model '\n 'initialization.')\nflags.DEFINE_string(\n 'training_file_pattern', None,\n 'Glob for training data files (e.g., COCO train - minival set)')\nflags.DEFINE_string(\n 'validation_file_pattern', None,\n 'Glob for evaluation tfrecords (e.g., COCO val2017 set)')\nflags.DEFINE_string(\n 'val_json_file',\n None,\n 'COCO validation JSON containing golden bounding boxes.')\n\nflags.DEFINE_string('mode', 'train',\n 'Mode to run: train or eval (default: train)')\nflags.DEFINE_bool('eval_after_training', False, 'Run one eval after the '\n 'training finishes.')\nflags.DEFINE_bool('use_fake_data', False, 'Use fake input.')\n\n# For Eval mode\nflags.DEFINE_integer('min_eval_interval', 180,\n 'Minimum seconds between evaluations.')\nflags.DEFINE_integer(\n 'eval_timeout', None,\n 'Maximum seconds between checkpoints before evaluation terminates.')\n\nFLAGS = flags.FLAGS\n\n\ndef main(argv):\n del argv # Unused.\n\n # TODO(b/132208296): remove this workaround that uses control flow v2.\n control_flow_util.ENABLE_CONTROL_FLOW_V2 = True\n\n tpu = FLAGS.tpu or FLAGS.master\n tpu_cluster_resolver = runner_utils.create_tpu_cluster_resolver(\n FLAGS.use_tpu, tpu, FLAGS.tpu_zone, FLAGS.gcp_project)\n if tpu_cluster_resolver:\n tpu_grpc_url = tpu_cluster_resolver.get_master()\n tf.Session.reset(tpu_grpc_url)\n\n # Check data path\n run_train = FLAGS.mode in ('train', 'train_and_eval')\n if run_train and FLAGS.training_file_pattern is None:\n raise RuntimeError('You must specify --training_file_pattern for training.')\n run_eval = FLAGS.mode in ('eval', 'train_and_eval') or (\n FLAGS.mode == 'train' and FLAGS.eval_after_training)\n if run_eval:\n if FLAGS.validation_file_pattern is None:\n raise RuntimeError('You must specify --validation_file_pattern '\n 'for evaluation.')\n if FLAGS.val_json_file is None:\n raise RuntimeError('You must specify --val_json_file for evaluation.')\n\n # Parse hparams\n hparams = mask_rcnn_params.default_hparams()\n hparams.parse(FLAGS.hparams)\n\n # The following is for spatial partitioning. `features` has one tensor while\n # `labels` has 4 + (`max_level` - `min_level` + 1) * 2 tensors. The input\n # partition is performed on `features` and all partitionable tensors of\n # `labels`, see the partition logic below.\n # Note: In the below code, TPUEstimator uses both `shard` and `replica` (with\n # the same meaning).\n # Note that spatial partition is part of the model-parallelism optimization.\n # See core_assignment_utils.py for more details about model parallelism.\n if FLAGS.input_partition_dims:\n labels_partition_dims = {\n 'gt_boxes': None,\n 'gt_classes': None,\n 'cropped_gt_masks': None,\n }\n for level in range(hparams.get('min_level'), hparams.get('max_level') + 1):\n labels_partition_dims['box_targets_%d' % level] = None\n labels_partition_dims['score_targets_%d' % level] = None\n num_cores_per_replica = int(np.prod(FLAGS.input_partition_dims))\n image_partition_dims = [\n FLAGS.input_partition_dims[i] for i in [1, 0, 2]\n ] if hparams.get('transpose_input') else FLAGS.input_partition_dims\n features_partition_dims = {\n 'images': image_partition_dims,\n 'source_ids': None,\n 'image_info': None,\n }\n input_partition_dims = [features_partition_dims, labels_partition_dims]\n num_shards = FLAGS.num_cores // num_cores_per_replica\n else:\n num_cores_per_replica = None\n input_partition_dims = None\n num_shards = FLAGS.num_cores\n\n params = dict(\n hparams.values(),\n num_shards=num_shards,\n num_cores_per_replica=num_cores_per_replica,\n use_tpu=FLAGS.use_tpu,\n resnet_checkpoint=FLAGS.resnet_checkpoint,\n val_json_file=FLAGS.val_json_file,\n model_dir=FLAGS.model_dir)\n\n tpu_config = tf.contrib.tpu.TPUConfig(\n params['iterations_per_loop'],\n num_shards=num_shards,\n num_cores_per_replica=params['num_cores_per_replica'],\n input_partition_dims=input_partition_dims,\n per_host_input_for_training=tf.contrib.tpu.InputPipelineConfig\n .PER_HOST_V2,\n tpu_job_name=FLAGS.tpu_job_name,\n )\n\n run_config = tf.contrib.tpu.RunConfig(\n cluster=tpu_cluster_resolver,\n model_dir=FLAGS.model_dir,\n log_step_count_steps=params['iterations_per_loop'],\n tpu_config=tpu_config,\n save_checkpoints_steps=params['iterations_per_loop'],\n )\n\n train_replicas_per_worker = (\n params['cores_per_worker'] // params['num_cores_per_replica']\n ) if params['num_cores_per_replica'] else params['cores_per_worker']\n train_params = dict(\n params,\n replicas_per_worker=train_replicas_per_worker,\n )\n eval_params = dict(\n params,\n input_rand_hflip=False,\n resnet_checkpoint=None,\n is_training_bn=False,\n )\n\n # MLPerf logging.\n mlp_log.mlperf_print(key='init_start', value=None)\n mlp_log.mlperf_print(key='global_batch_size',\n value=params['train_batch_size'])\n runner = None\n if run_train and run_eval:\n if params['train_use_tpu_estimator'] or params['eval_use_tpu_estimator']:\n raise RuntimeError('train_and_eval runner does not support TPUEstimator.')\n dist_eval_params = dict(\n eval_params,\n replicas_per_worker=train_replicas_per_worker,\n )\n runner = mask_rcnn_runner.TrainEvalRunner(\n model_fn=mask_rcnn_model.MaskRcnnModelFn(),\n input_fn=dataloader.InputReader(\n FLAGS.training_file_pattern,\n mode=tf.estimator.ModeKeys.TRAIN,\n use_fake_data=FLAGS.use_fake_data),\n eval_input_fn=dataloader.InputReader(\n FLAGS.validation_file_pattern, mode=tf.estimator.ModeKeys.PREDICT,\n distributed_eval=True),\n eval_metric=coco_metric.EvaluationMetric(\n FLAGS.val_json_file, use_cpp_extension=True),\n train_params=train_params,\n eval_params=dist_eval_params,\n run_config=run_config)\n elif run_train:\n # Check low-level train runner compatibility.\n if not params['train_use_tpu_estimator']:\n if FLAGS.mode == 'train_and_eval':\n raise RuntimeError('Low level train runner does not support mode '\n 'train_and_eval yet.')\n train_params = dict(\n params,\n replicas_per_worker=train_replicas_per_worker,\n )\n runner = mask_rcnn_runner.TrainRunner(\n model_fn=mask_rcnn_model.MaskRcnnModelFn(),\n input_fn=dataloader.InputReader(\n FLAGS.training_file_pattern,\n mode=tf.estimator.ModeKeys.TRAIN,\n use_fake_data=FLAGS.use_fake_data),\n params=train_params,\n run_config=run_config,\n use_tpu_estimator=train_params['train_use_tpu_estimator'])\n else:\n sidecar_eval_params = dict(\n eval_params,\n # sidecar eval only uses one worker and does not use spatial partition.\n replicas_per_worker=FLAGS.num_cores,)\n runner = mask_rcnn_runner.EvalRunner(\n mask_rcnn_model.MaskRcnnModelFn(),\n dataloader.InputReader(\n FLAGS.validation_file_pattern,\n mode=tf.estimator.ModeKeys.PREDICT),\n coco_metric.EvaluationMetric(\n FLAGS.val_json_file,\n use_cpp_extension=True),\n sidecar_eval_params,\n run_config,\n use_tpu_estimator=sidecar_eval_params['eval_use_tpu_estimator'])\n\n if FLAGS.mode == 'train':\n runner.train()\n elif FLAGS.mode == 'eval':\n\n def terminate_eval():\n tf.logging.info('Terminating eval after %d seconds of no checkpoints' %\n FLAGS.eval_timeout)\n return True\n\n run_success = False\n # Run evaluation when there's a new checkpoint\n for ckpt in tf.contrib.training.checkpoints_iterator(\n params['model_dir'],\n min_interval_secs=FLAGS.min_eval_interval,\n timeout=FLAGS.eval_timeout,\n timeout_fn=terminate_eval):\n\n tf.logging.info('Starting to evaluate.')\n try:\n\n eval_results = runner.evaluate(ckpt)\n current_step, _ = runner.get_step_and_epoch_number(ckpt)\n\n if (eval_results['AP'] >= mask_rcnn_params.BOX_EVAL_TARGET and\n eval_results['mask_AP'] >= mask_rcnn_params.MASK_EVAL_TARGET):\n mlp_log.mlperf_print(key='run_stop', metadata={'status': 'success'})\n run_success = True\n break\n\n if int(current_step) >= params['total_steps']:\n tf.logging.info('Evaluation finished after training step %d' %\n current_step)\n break\n\n except tf.errors.NotFoundError:\n # Since the coordinator is on a different job than the TPU worker,\n # sometimes the TPU worker does not finish initializing until long after\n # the CPU job tells it to start evaluating. In this case, the checkpoint\n # file could have been deleted already.\n tf.logging.info('Checkpoint %s no longer exists, skipping checkpoint' %\n ckpt)\n if not run_success:\n mlp_log.mlperf_print(key='run_stop', metadata={'status': 'aborted'})\n\n elif FLAGS.mode == 'train_and_eval':\n runner.train_and_eval()\n else:\n tf.logging.info('Mode not found.')\n\n\nif __name__ == '__main__':\n tf.logging.set_verbosity(tf.logging.INFO)\n app.run(main)\n",
"import ctypes\nimport logging.config\nimport os\nimport random\nimport sys\nimport time\nfrom contextlib import contextmanager\n\nimport numpy as np\nimport torch\nimport torch.distributed as dist\nimport torch.nn.init as init\nimport torch.utils.collect_env\nimport mlperf_compliance\n\n\ndef mlperf_print(*args, **kwargs):\n \"\"\"\n Wrapper for MLPerf compliance logging calls.\n All arguments but 'sync' and 'log_all_ranks' are passed to\n mlperf_compliance.mlperf_log.mlperf_print function.\n If 'sync' is set to True then the wrapper will synchronize all distributed\n workers. 'sync' should be set to True for all compliance tags that require\n accurate timing (RUN_START, RUN_STOP etc.)\n If 'log_all_ranks' is set to True then all distributed workers will print\n logging message, if set to False then only worker with rank=0 will print\n the message.\n \"\"\"\n if kwargs.pop('sync', False):\n barrier()\n\n if kwargs.pop('log_all_ranks', False):\n log = True\n else:\n log = (get_rank() == 0)\n\n if log:\n mlperf_compliance.mlperf_log.mlperf_print(*args, **kwargs)\n\n\ndef init_lstm_(lstm, init_weight=0.1):\n \"\"\"\n Initializes weights of LSTM layer.\n Weights and biases are initialized with uniform(-init_weight, init_weight)\n distribution.\n\n :param lstm: instance of torch.nn.LSTM\n :param init_weight: range for the uniform initializer\n \"\"\"\n # Initialize hidden-hidden weights\n init.uniform_(lstm.weight_hh_l0.data, -init_weight, init_weight)\n # Initialize input-hidden weights:\n init.uniform_(lstm.weight_ih_l0.data, -init_weight, init_weight)\n\n # Initialize bias. PyTorch LSTM has two biases, one for input-hidden GEMM\n # and the other for hidden-hidden GEMM. Here input-hidden bias is\n # initialized with uniform distribution and hidden-hidden bias is\n # initialized with zeros.\n init.uniform_(lstm.bias_ih_l0.data, -init_weight, init_weight)\n init.zeros_(lstm.bias_hh_l0.data)\n\n if lstm.bidirectional:\n init.uniform_(lstm.weight_hh_l0_reverse.data, -init_weight, init_weight)\n init.uniform_(lstm.weight_ih_l0_reverse.data, -init_weight, init_weight)\n\n init.uniform_(lstm.bias_ih_l0_reverse.data, -init_weight, init_weight)\n init.zeros_(lstm.bias_hh_l0_reverse.data)\n\n\ndef generate_seeds(rng, size):\n \"\"\"\n Generate list of random seeds\n\n :param rng: random number generator\n :param size: length of the returned list\n \"\"\"\n seeds = [rng.randint(0, 2**32 - 1) for _ in range(size)]\n return seeds\n\n\ndef broadcast_seeds(seeds, device):\n \"\"\"\n Broadcasts random seeds to all distributed workers.\n Returns list of random seeds (broadcasted from workers with rank 0).\n\n :param seeds: list of seeds (integers)\n :param device: torch.device\n \"\"\"\n if torch.distributed.is_available() and torch.distributed.is_initialized():\n seeds_tensor = torch.LongTensor(seeds).to(device)\n torch.distributed.broadcast(seeds_tensor, 0)\n seeds = seeds_tensor.tolist()\n return seeds\n\n\ndef setup_seeds(master_seed, epochs, device):\n \"\"\"\n Generates seeds from one master_seed.\n Function returns (worker_seeds, shuffling_seeds), worker_seeds are later\n used to initialize per-worker random number generators (mostly for\n dropouts), shuffling_seeds are for RNGs resposible for reshuffling the\n dataset before each epoch.\n Seeds are generated on worker with rank 0 and broadcasted to all other\n workers.\n\n :param master_seed: master RNG seed used to initialize other generators\n :param epochs: number of epochs\n :param device: torch.device (used for distributed.broadcast)\n \"\"\"\n if master_seed is None:\n # random master seed, random.SystemRandom() uses /dev/urandom on Unix\n master_seed = random.SystemRandom().randint(0, 2**32 - 1)\n if get_rank() == 0:\n # master seed is reported only from rank=0 worker, it's to avoid\n # confusion, seeds from rank=0 are later broadcasted to other\n # workers\n logging.info(f'Using random master seed: {master_seed}')\n else:\n # master seed was specified from command line\n logging.info(f'Using master seed from command line: {master_seed}')\n\n # initialize seeding RNG\n seeding_rng = random.Random(master_seed)\n\n # generate worker seeds, one seed for every distributed worker\n worker_seeds = generate_seeds(seeding_rng, get_world_size())\n\n # generate seeds for data shuffling, one seed for every epoch\n shuffling_seeds = generate_seeds(seeding_rng, epochs)\n\n # broadcast seeds from rank=0 to other workers\n worker_seeds = broadcast_seeds(worker_seeds, device)\n shuffling_seeds = broadcast_seeds(shuffling_seeds, device)\n return worker_seeds, shuffling_seeds\n\n\ndef barrier():\n \"\"\"\n Works as a temporary distributed barrier, currently pytorch\n doesn't implement barrier for NCCL backend.\n Calls all_reduce on dummy tensor and synchronizes with GPU.\n \"\"\"\n if torch.distributed.is_available() and torch.distributed.is_initialized():\n torch.distributed.all_reduce(torch.cuda.FloatTensor(1))\n torch.cuda.synchronize()\n\n\ndef get_rank():\n \"\"\"\n Gets distributed rank or returns zero if distributed is not initialized.\n \"\"\"\n if torch.distributed.is_available() and torch.distributed.is_initialized():\n rank = torch.distributed.get_rank()\n else:\n rank = 0\n return rank\n\n\ndef get_world_size():\n \"\"\"\n Gets total number of distributed workers or returns one if distributed is\n not initialized.\n \"\"\"\n if torch.distributed.is_available() and torch.distributed.is_initialized():\n world_size = torch.distributed.get_world_size()\n else:\n world_size = 1\n return world_size\n\n\n@contextmanager\ndef sync_workers():\n \"\"\"\n Yields distributed rank and synchronizes all workers on exit.\n \"\"\"\n rank = get_rank()\n yield rank\n barrier()\n\n\n@contextmanager\ndef timer(name, ndigits=2, sync_gpu=True):\n if sync_gpu:\n torch.cuda.synchronize()\n start = time.time()\n yield\n if sync_gpu:\n torch.cuda.synchronize()\n stop = time.time()\n elapsed = round(stop - start, ndigits)\n logging.info(f'TIMER {name} {elapsed}')\n\n\ndef setup_logging(log_all_ranks=True, log_file=os.devnull):\n \"\"\"\n Configures logging.\n By default logs from all workers are printed to the console, entries are\n prefixed with \"N: \" where N is the rank of the worker. Logs printed to the\n console don't include timestaps.\n Full logs with timestamps are saved to the log_file file.\n \"\"\"\n class RankFilter(logging.Filter):\n def __init__(self, rank, log_all_ranks):\n self.rank = rank\n self.log_all_ranks = log_all_ranks\n\n def filter(self, record):\n record.rank = self.rank\n if self.log_all_ranks:\n return True\n else:\n return (self.rank == 0)\n\n rank = get_rank()\n rank_filter = RankFilter(rank, log_all_ranks)\n\n logging_format = \"%(asctime)s - %(levelname)s - %(rank)s - %(message)s\"\n logging.basicConfig(level=logging.DEBUG,\n format=logging_format,\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n filename=log_file,\n filemode='w')\n console = logging.StreamHandler(sys.stdout)\n console.setLevel(logging.INFO)\n formatter = logging.Formatter('%(rank)s: %(message)s')\n console.setFormatter(formatter)\n logging.getLogger('').addHandler(console)\n logging.getLogger('').addFilter(rank_filter)\n\n\ndef set_device(cuda, local_rank):\n \"\"\"\n Sets device based on local_rank and returns instance of torch.device.\n\n :param cuda: if True: use cuda\n :param local_rank: local rank of the worker\n \"\"\"\n if cuda:\n torch.cuda.set_device(local_rank)\n device = torch.device('cuda')\n else:\n device = torch.device('cpu')\n return device\n\n\ndef init_distributed(cuda):\n \"\"\"\n Initializes distributed backend.\n\n :param cuda: (bool) if True initializes nccl backend, if False initializes\n gloo backend\n \"\"\"\n world_size = int(os.environ.get('WORLD_SIZE', 1))\n distributed = (world_size > 1)\n if distributed:\n backend = 'nccl' if cuda else 'gloo'\n dist.init_process_group(backend=backend,\n init_method='env://')\n assert dist.is_initialized()\n return distributed\n\n\ndef log_env_info():\n \"\"\"\n Prints information about execution environment.\n \"\"\"\n logging.info('Collecting environment information...')\n env_info = torch.utils.collect_env.get_pretty_env_info()\n logging.info(f'{env_info}')\n\n\ndef pad_vocabulary(math):\n if math == 'fp16' or math == 'amp_fp16':\n pad_vocab = 8\n elif math == 'fp32':\n pad_vocab = 1\n return pad_vocab\n\n\nclass AverageMeter:\n \"\"\"\n Computes and stores the average and current value\n \"\"\"\n def __init__(self, skip_first=True):\n self.reset()\n self.skip = skip_first\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n\n if self.skip:\n self.skip = False\n else:\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n def reduce(self, op):\n \"\"\"\n Reduces average value over all workers.\n\n :param op: 'sum' or 'mean', reduction operator\n \"\"\"\n if op not in ('sum', 'mean'):\n raise NotImplementedError\n\n distributed = (get_world_size() > 1)\n if distributed:\n # Backward/forward compatibility around\n # https://github.com/pytorch/pytorch/commit/540ef9b1fc5506369a48491af8a285a686689b36 and\n # https://github.com/pytorch/pytorch/commit/044d00516ccd6572c0d6ab6d54587155b02a3b86\n # To accomodate change in Pytorch's distributed API\n if hasattr(dist, \"get_backend\"):\n _backend = dist.get_backend()\n if hasattr(dist, \"DistBackend\"):\n backend_enum_holder = dist.DistBackend\n else:\n backend_enum_holder = dist.Backend\n else:\n _backend = dist._backend\n backend_enum_holder = dist.dist_backend\n\n cuda = _backend == backend_enum_holder.NCCL\n\n if cuda:\n avg = torch.cuda.FloatTensor([self.avg])\n _sum = torch.cuda.FloatTensor([self.sum])\n else:\n avg = torch.FloatTensor([self.avg])\n _sum = torch.FloatTensor([self.sum])\n\n dist.all_reduce(avg)\n dist.all_reduce(_sum)\n self.avg = avg.item()\n self.sum = _sum.item()\n\n if op == 'mean':\n self.avg /= get_world_size()\n self.sum /= get_world_size()\n\n\ndef debug_tensor(tensor, name):\n \"\"\"\n Simple utility which helps with debugging.\n Takes a tensor and outputs: min, max, avg, std, number of NaNs, number of\n INFs.\n\n :param tensor: torch tensor\n :param name: name of the tensor (only for logging)\n \"\"\"\n logging.info(name)\n tensor = tensor.detach().float().cpu().numpy()\n logging.info(f'MIN: {tensor.min()} MAX: {tensor.max()} '\n f'AVG: {tensor.mean()} STD: {tensor.std()} '\n f'NAN: {np.isnan(tensor).sum()} INF: {np.isinf(tensor).sum()}')\n\ndef l2_promote():\n # Check what's the device limit for current device, should be 64 by default\n pValue = ctypes.cast((ctypes.c_int*1)(), ctypes.POINTER(ctypes.c_int))\n result = torch.cuda.cudart().cudaDeviceGetLimit(pValue, ctypes.c_int(0x05))\n\n # Set device limit on the current device\n # cudaLimitMaxL2FetchGranularity = 0x05\n result = torch.cuda.cudart().cudaDeviceSetLimit(ctypes.c_int(0x05), ctypes.c_int(128))\n\n # Get the device limit again, should be 128\n result = torch.cuda.cudart().cudaDeviceGetLimit(pValue, ctypes.c_int(0x05))\n logging.info(f'L2 promotion: {pValue[0]}B')\n\n\nlib = ctypes.cdll.LoadLibrary(None)\nlib.THCudaHalfTensor_normall.argtypes=[ctypes.c_void_p, ctypes.c_void_p]\nlib.THCudaHalfTensor_normall.restype = ctypes.c_float\n\ndef fused_norm(input):\n if input.type() == 'torch.cuda.HalfTensor':\n # 16384 is half 2 if you stare at it long enough\n return lib.THCudaHalfTensor_normall(torch.cuda._state_cdata,\n input._cdata, 16384)\n else:\n return(input.norm())\n\n",
"# coding=utf-8\n# Copyright 2018 The Tensor2Tensor Authors.\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\"\"\"Timeseries generators tests.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport shutil\n\nfrom tensor2tensor.data_generators import timeseries\n\nimport tensorflow as tf\n\n\nclass TimeseriesTest(tf.test.TestCase):\n\n @classmethod\n def setUpClass(cls):\n cls.tmp_dir = tf.test.get_temp_dir()\n shutil.rmtree(cls.tmp_dir)\n os.mkdir(cls.tmp_dir)\n\n def testTimeseriesToyProblem(self):\n problem = timeseries.TimeseriesToyProblem()\n problem.generate_data(self.tmp_dir, self.tmp_dir)\n\n dataset = problem.dataset(tf.estimator.ModeKeys.TRAIN, self.tmp_dir)\n features = dataset.make_one_shot_iterator().get_next()\n\n examples = []\n exhausted = False\n with self.test_session() as sess:\n examples.append(sess.run(features))\n examples.append(sess.run(features))\n examples.append(sess.run(features))\n examples.append(sess.run(features))\n\n try:\n sess.run(features)\n except tf.errors.OutOfRangeError:\n exhausted = True\n\n self.assertTrue(exhausted)\n self.assertEqual(4, len(examples))\n\n self.assertNotEqual(\n list(examples[0][\"inputs\"][0, 0]), list(examples[1][\"inputs\"][0, 0]))\n\n def testTimeseriesSyntheticData10Series100kSamples(self):\n problem = timeseries.TimeseriesSyntheticDataSeries10Samples100k()\n self.assertEqual(10, problem.num_series)\n self.assertEqual(250, problem.num_input_timestamps)\n self.assertEqual(100, problem.num_target_timestamps)\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n",
"# Copyright 2017 Google Inc. 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\n\"\"\"Utility to handle vocabularies.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport codecs\nimport os\nimport tensorflow as tf\n\nfrom tensorflow.python.ops import lookup_ops\n\nfrom utils import misc_utils as utils\n\n# word level special token\nUNK = \"<unk>\"\nSOS = \"<s>\"\nEOS = \"</s>\"\nUNK_ID = 0\n\n# char ids 0-255 come from utf-8 encoding bytes\n# assign 256-300 to special chars\nBOS_CHAR_ID = 256 # <begin sentence>\nEOS_CHAR_ID = 257 # <end sentence>\nBOW_CHAR_ID = 258 # <begin word>\nEOW_CHAR_ID = 259 # <end word>\nPAD_CHAR_ID = 260 # <padding>\n\nDEFAULT_CHAR_MAXLEN = 50 # max number of chars for each word.\n\n\ndef _string_to_bytes(text, max_length):\n \"\"\"Given string and length, convert to byte seq of at most max_length.\n\n This process mimics docqa/elmo's preprocessing:\n https://github.com/allenai/document-qa/blob/master/docqa/elmo/data.py\n\n Note that we make use of BOS_CHAR_ID and EOS_CHAR_ID in iterator_utils.py &\n our usage differs from docqa/elmo.\n\n Args:\n text: tf.string tensor of shape []\n max_length: max number of chars for each word.\n\n Returns:\n A tf.int32 tensor of the byte encoded text.\n \"\"\"\n byte_ids = tf.to_int32(tf.decode_raw(text, tf.uint8))\n byte_ids = byte_ids[:max_length - 2]\n padding = tf.fill([max_length - tf.shape(byte_ids)[0] - 2], PAD_CHAR_ID)\n byte_ids = tf.concat(\n [[BOW_CHAR_ID], byte_ids, [EOW_CHAR_ID], padding], axis=0)\n tf.logging.info(byte_ids)\n\n byte_ids = tf.reshape(byte_ids, [max_length])\n tf.logging.info(byte_ids.get_shape().as_list())\n return byte_ids + 1\n\n\ndef tokens_to_bytes(tokens):\n \"\"\"Given a sequence of strings, map to sequence of bytes.\n\n Args:\n tokens: A tf.string tensor\n\n Returns:\n A tensor of shape words.shape + [bytes_per_word] containing byte versions\n of each word.\n \"\"\"\n bytes_per_word = DEFAULT_CHAR_MAXLEN\n with tf.device(\"/cpu:0\"):\n tf.assert_rank(tokens, 1)\n shape = tf.shape(tokens)\n tf.logging.info(tokens)\n tokens_flat = tf.reshape(tokens, [-1])\n as_bytes_flat = tf.map_fn(\n fn=lambda x: _string_to_bytes(x, max_length=bytes_per_word),\n elems=tokens_flat,\n dtype=tf.int32,\n back_prop=False)\n tf.logging.info(as_bytes_flat)\n as_bytes = tf.reshape(as_bytes_flat, [shape[0], bytes_per_word])\n return as_bytes\n\n\ndef load_vocab(vocab_file):\n vocab = []\n with codecs.getreader(\"utf-8\")(tf.gfile.GFile(vocab_file, \"rb\")) as f:\n vocab_size = 0\n for word in f:\n vocab_size += 1\n vocab.append(word.strip())\n return vocab, vocab_size\n\n\ndef check_vocab(vocab_file, out_dir, check_special_token=True, sos=None,\n eos=None, unk=None):\n \"\"\"Check if vocab_file doesn't exist, create from corpus_file.\"\"\"\n if tf.gfile.Exists(vocab_file):\n utils.print_out(\"# Vocab file %s exists\" % vocab_file)\n vocab, vocab_size = load_vocab(vocab_file)\n if check_special_token:\n # Verify if the vocab starts with unk, sos, eos\n # If not, prepend those tokens & generate a new vocab file\n if not unk: unk = UNK\n if not sos: sos = SOS\n if not eos: eos = EOS\n assert len(vocab) >= 3\n if vocab[0] != unk or vocab[1] != sos or vocab[2] != eos:\n utils.print_out(\"The first 3 vocab words [%s, %s, %s]\"\n \" are not [%s, %s, %s]\" %\n (vocab[0], vocab[1], vocab[2], unk, sos, eos))\n vocab = [unk, sos, eos] + vocab\n vocab_size += 3\n new_vocab_file = os.path.join(out_dir, os.path.basename(vocab_file))\n with codecs.getwriter(\"utf-8\")(\n tf.gfile.GFile(new_vocab_file, \"wb\")) as f:\n for word in vocab:\n f.write(\"%s\\n\" % word)\n vocab_file = new_vocab_file\n else:\n raise ValueError(\"vocab_file '%s' does not exist.\" % vocab_file)\n\n vocab_size = len(vocab)\n return vocab_size, vocab_file\n\n\ndef create_vocab_tables(src_vocab_file):\n \"\"\"Creates vocab tables for src_vocab_file and tgt_vocab_file.\"\"\"\n src_vocab_table = lookup_ops.index_table_from_file(\n src_vocab_file, default_value=UNK_ID)\n tgt_vocab_table = src_vocab_table\n return src_vocab_table, tgt_vocab_table\n\n\ndef load_embed_txt(embed_file):\n \"\"\"Load embed_file into a python dictionary.\n\n Note: the embed_file should be a Glove/word2vec formatted txt file. Assuming\n Here is an exampe assuming embed_size=5:\n\n the -0.071549 0.093459 0.023738 -0.090339 0.056123\n to 0.57346 0.5417 -0.23477 -0.3624 0.4037\n and 0.20327 0.47348 0.050877 0.002103 0.060547\n\n For word2vec format, the first line will be: <num_words> <emb_size>.\n\n Args:\n embed_file: file path to the embedding file.\n Returns:\n a dictionary that maps word to vector, and the size of embedding dimensions.\n \"\"\"\n emb_dict = dict()\n emb_size = None\n\n is_first_line = True\n with codecs.getreader(\"utf-8\")(tf.gfile.GFile(embed_file, \"rb\")) as f:\n for line in f:\n tokens = line.rstrip().split(\" \")\n if is_first_line:\n is_first_line = False\n if len(tokens) == 2: # header line\n emb_size = int(tokens[1])\n continue\n word = tokens[0]\n vec = list(map(float, tokens[1:]))\n emb_dict[word] = vec\n if emb_size:\n if emb_size != len(vec):\n utils.print_out(\n \"Ignoring %s since embeding size is inconsistent.\" % word)\n del emb_dict[word]\n else:\n emb_size = len(vec)\n return emb_dict, emb_size\n",
"# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not\n# use this file except in compliance with the License. A copy of the License\n# is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\n\"\"\"\nVisualize the checkpoints of the model: image, ground truth caption and\npredicted caption.\n\"\"\"\nimport argparse\nimport os\n\ntry: # Try to import pillow\n from PIL import Image # pylint: disable=import-error\nexcept ImportError as e:\n raise RuntimeError(\"Please install pillow.\")\n\ntry: # Try to import matplotlib\n import matplotlib # pylint: disable=import-error\nexcept ImportError as e:\n raise RuntimeError(\"Please install matplotlib.\")\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\n\ndef format_text_for_visualization(c, n):\n c = c.split(\" \")\n c[0] = c[0].title()\n out = \"\"\n for j in range(0, len(c)):\n out += c[j]\n if j == len(c)-1:\n out += \".\"\n else:\n if (j + 1) % n == 0:\n out += \"\\n\"\n else:\n out += \" \"\n return out\n\ndef main():\n params = argparse.ArgumentParser(\n description=\"CLI to visualize the captions along with images and \"\n \"ground truth.\"\n )\n params.add_argument(\"-d\", \"--image-root\",\n help=\"Absolute path of the dataset root where the \"\n \"images are stored.\")\n params.add_argument(\"-i\", \"--source\",\n help=\"File containing the images or features used to \"\n \"generate the captions.\")\n params.add_argument(\"-c\", \"--prediction\",\n help=\"File containing the captions. Each line \"\n \"corresponds to a line in the source.\")\n params.add_argument(\"-a\", \"--ground-truth\",\n default=None,\n help=\"File file containing the ground-truth captions \"\n \"(optional).\")\n params.add_argument(\"-s\", \"--save-to-folder\",\n default=None,\n help=\"Folder to save the visualizations.\")\n params.add_argument(\"-si\", \"--skip-images\",\n default=2,\n help=\"Number of images to skip for visualization.\")\n params.add_argument(\"-nc\", \"--number-of-columns\",\n default=4,\n help=\"Number of columns in the subplot (better if even \"\n \"number).\")\n args = params.parse_args()\n\n skip = args.skip_images\n N = M = args.number_of_columns\n\n # adjust this if visualization is not nice\n len_newline = 9\n fontsize = 10\n figsize = (30, 20)\n\n # Collect results in a better data structure (dict)\n # * Read predictions and image dir\n fs = open(args.source)\n fc = open(args.prediction)\n predictions = {}\n for s, c in zip(fs.readlines(), fc.readlines()):\n predictions[s] = c # just keep one sentence\n fs.close()\n fc.close()\n # * Read ground truth optionally\n ground_truth = {}\n if args.ground_truth is not None:\n fgt = open(args.ground_truth)\n fs = open(args.source)\n for s, gt in zip(fs.readlines(), fgt.readlines()):\n if s in ground_truth:\n ground_truth[s].append(gt)\n else:\n ground_truth[s] = [gt]\n fgt.close()\n fs.close()\n\n # Prepare output folder, if needed\n if args.save_to_folder is not None:\n fontsize = 15\n if not os.path.exists(args.save_to_folder):\n os.makedirs(args.save_to_folder)\n\n # Visualization\n plt.ioff()\n fig, axs = plt.subplots(N, M, figsize=figsize)\n fig.tight_layout()\n i = 0\n ii = 1\n for s in predictions.keys(): # Go over images (dict[image]=caption)\n if ii%skip==0: # maybe you do not want to display all images\n c = predictions[s]\n if len(ground_truth)>0:\n gts = ground_truth[s] # list\n s = s.split(\"\\n\")[0]\n c = c.split(\"\\n\")[0]\n # Display image\n image = Image.open(os.path.join(args.image_root, s))\n if 'RGB' not in image.mode:\n axs[i//N%M, i%N].imshow(image, cmap='gray')\n else:\n axs[i//N%M, i%N].imshow(image)\n # Display predicted caption\n axs[i//N%M, i%N].axis(\"off\")\n axs[(i+1)//N%M, (i+1)%N].text(0, 0.9,\n format_text_for_visualization(c, len_newline),\n fontsize=fontsize,\n bbox={'facecolor': 'white',\n 'alpha': 0.85,\n 'pad': 2})\n # Display ground-truth caption(s) optionally\n if len(ground_truth)>0:\n gt_vis = \"\"\n for j, gt in enumerate(gts):\n gt = gt.split(\"\\n\")[0]\n gt_vis += \\\n \"* \" + format_text_for_visualization(gt, len_newline) \\\n + \"\\n\"\n axs[(i+1)//N%M, (i+1)%N].text(0, 0, gt_vis,\n fontsize=fontsize,\n bbox={'facecolor': 'green',\n 'alpha': 0.3,\n 'pad': 2})\n axs[(i+1)//N%M, (i+1)%N].axis(\"off\")\n i += 2\n\n # Show or save to disk\n if i % (N * M) == 0:\n if args.save_to_folder is None:\n plt.show()\n else:\n plt.savefig(os.path.join(args.save_to_folder,\n str(ii).zfill(6) + '.png'),\n bbox_inches='tight')\n i = 0\n # Reset axes, clean up\n for k in range(N):\n for j in range(M):\n axs[k, j].cla()\n axs[k, j].axis(\"off\")\n ii += 1\n\n\nif __name__ == \"__main__\":\n main()\n\n\n",
"\"\"\"Test code for l2 normalization\"\"\"\nimport numpy as np\nimport tvm\nimport topi\nimport logging\nfrom topi.util import get_const_tuple\nimport topi.testing\n\ndef verify_l2_normalize(shape, eps, axis=None):\n '''Verify l2 normalization operator by comparing outputs from tvm and numpy implementation'''\n A = tvm.placeholder(shape, name='A')\n B = topi.cpp.nn.l2_normalize(A, eps, axis)\n dtype = A.dtype\n\n a_np = np.random.uniform(size=shape).astype(dtype)\n b_np = topi.testing.l2_normalize_python(a_np, eps, axis)\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 target = topi.cpp.TEST_create_target(device)\n if device == \"llvm\":\n s = topi.cpp.generic.default_schedule(target, [B], False)\n else:\n s = topi.cpp.cuda.schedule_l2_normalize(target, [B])\n ctx = tvm.context(device, 0)\n a = tvm.nd.array(a_np, ctx)\n b = tvm.nd.array(np.zeros(get_const_tuple(B.shape), dtype=B.dtype), ctx)\n func = tvm.build(s, [A, B], device, name=\"l2_normalize\")\n func(a, b)\n np.testing.assert_allclose(b.asnumpy(), b_np, rtol=1e-5)\n\n for device in ['cuda', 'opencl', 'metal', 'rocm', 'llvm']:\n check_device(device)\n\ndef test_l2_normalize():\n verify_l2_normalize((1, 3, 20, 20), 0.001)\n verify_l2_normalize((1, 3, 20, 20), 0.001, (1,))\n verify_l2_normalize((1, 3, 20, 20), 0.001, (1, 2))\n verify_l2_normalize((1, 3, 20, 20), 0.001, (2, 3))\n verify_l2_normalize((1, 3, 20, 20), 0.001, (0, 3))\n verify_l2_normalize((1, 3, 20, 20), 0.001, (0, 2, 3))\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.DEBUG)\n test_l2_normalize()\n",
"import numpy as np\nimport tvm\nfrom tvm.contrib import graph_runtime\nimport topi.testing\nimport nnvm.symbol as sym\nimport nnvm.compiler\nfrom nnvm.testing.config import ctx_list\nfrom nnvm.testing.check_computation import check_function\n\ndef test_check_function():\n # test the testing function\n\n x = sym.Variable(\"x\")\n y = sym.Variable(\"y\")\n\n # different styles of returning gradients from the backward function\n check_function(x + 2*y, lambda x, y: x + 2*y,\n lambda x, y, head_grads: [head_grads, 2*head_grads],\n shape={'x': (1, 2), y: (1, 2)}, dtype='float32')\n check_function(x + 2*y, lambda x, y: x + 2*y,\n lambda x, y, head_grads: (head_grads, 2*head_grads),\n shape={'x': (1, 2), y: (1, 2)}, dtype='float32')\n check_function(x + 2*y, lambda x, y: x + 2*y,\n lambda x, y, head_grads: {'x': head_grads, 'y': 2*head_grads},\n shape={'x': (1, 2), y: (1, 2)}, dtype='float32')\n check_function(x + 2*y, lambda x, y: x + 2*y,\n lambda x, y, head_grads: {'y': 2*head_grads},\n shape={'x': (1, 2), y: (1, 2)}, dtype='float32')\n check_function(x + 2*y, lambda x, y: x + 2*y,\n lambda x, y, head_grads: [2*head_grads],\n grad_input_vars=[y],\n shape={'x': (1, 2), y: (1, 2)}, dtype='float32')\n check_function(x + 2*y, lambda x, y: x + 2*y,\n lambda x, y, head_grads: 2*head_grads,\n grad_input_vars=[y],\n shape={'x': (1, 2), y: (1, 2)}, dtype='float32')\n check_function(x + 2*y, lambda x, y: x + 2*y,\n lambda x, y, head_grads: 2*head_grads,\n grad_input_vars=[y],\n shape={'x': (1, 2), y: (1, 2)}, dtype='float64')\n\n # test just numerical gradients\n # different styles of shape and dtype passing\n check_function(x + 2*y, shape={'x': (1, 2), y: (1, 2)},\n numerical_grads=True)\n check_function(x + 2*y, shape={'x': (1, 2), y: (1, 2)}, dtype='float32',\n numerical_grads=True)\n check_function(x + 2*y, shape={'x': (1, 2), y: (1, 2)}, dtype={x: 'float32', 'y': 'float32'},\n numerical_grads=True)\n check_function(x + 2*y, shape=(1, 2), dtype='float32',\n numerical_grads=True)\n\n # specifying variable attributes on variable creation\n # (in this case type codes must be used)\n x = sym.Variable(\"x\", dtype=0, shape=(1, 2))\n check_function(x + 2*y, shape={y: (1, 2)}, dtype={'y': 'float32'}, numerical_grads=True)\n y = sym.Variable(\"y\", dtype=0, shape=(1, 2))\n\n # shape overriding\n def _fwd1(x, y):\n assert x.shape == (1, 1)\n assert y.shape == (1, 2)\n return x + 2*y\n check_function(x + 2*y, _fwd1, shape={x: (1, 1)})\n\n # in_range\n def _fwd2(x, y):\n assert x.shape == (100,)\n assert (x <= 0.9).all()\n assert (x >= 0.8).all()\n return x + 2*y\n check_function(x + 2*y, _fwd2, shape=(100,), in_range=(0.8, 0.9), numerical_grads=False)\n check_function(x + 2*y, _fwd2, shape=(100,), in_range={'x': (0.8, 0.9)}, numerical_grads=False)\n check_function(x + 2*y, backward=lambda x, y, head_grads: [1.0, 2.0],\n in_range={'head_grads_0': (1.0, 1.0)})\n # explicit passing of values\n check_function(x + 2*y, backward=lambda x, y, head_grads: [1.0, 2.0],\n values={'head_grads_0': np.full((1, 2), 1.0)})\n\n # check that the function reports errors\n def _check_function_must_fail(*args, **kwargs):\n error = AssertionError\n if 'error' in kwargs:\n error = kwargs['error']\n del kwargs['error']\n try:\n check_function(*args, quiet=True, **kwargs)\n except error:\n pass\n else:\n raise AssertionError(\"check_function didn't raise an exception\")\n\n _check_function_must_fail(x + 2*y, error=ValueError)\n _check_function_must_fail(x + 2*y, lambda x, y: x + y)\n _check_function_must_fail(x + 2*y, backward=lambda x, y, head_grads: [1.0, 2.0])\n _check_function_must_fail(sym.block_grad(x + 2*y), numerical_grads=True)\n _check_function_must_fail(x*x, numerical_grads=True,\n numerical_grads_params={'atol': 0.0, 'rtol': 0.0})\n _check_function_must_fail(sym.log(-x*x), numerical_grads=True, error=ValueError)\n\n # different styles of returning results from the forward function\n check_function(x + 2*y, lambda x, y: [x + 2*y], numerical_grads=False)\n _check_function_must_fail(x + 2*y, lambda x, y: [x + 2*y, x], numerical_grads=False,\n error=ValueError)\n _check_function_must_fail(x + 2*y, lambda x, y: [], numerical_grads=False,\n error=ValueError)\n\n # multiple outputs\n z = sym.Group([2*x + y, x + 2*y])\n check_function(z, lambda x, y: [2*x + y, x + 2*y])\n check_function(z, lambda x, y: (2*x + y, x + 2*y))\n check_function(z, backward=lambda x, y, head_grads: [2*head_grads[0] + head_grads[1],\n head_grads[0] + 2*head_grads[1]])\n _check_function_must_fail(z, backward=lambda x, y, head_grads: [2*head_grads[0],\n 2*head_grads[1]])\n check_function(z, backward=lambda x, y, head_grads: [head_grads[1], 2*head_grads[1]],\n in_range={'head_grads_0': (0, 0)})\n check_function(z, numerical_grads=True)\n\n z = sym.Group([sym.block_grad(2*x + y), x + 2*y])\n check_function(z, lambda x, y: [2*x + y, x + 2*y], numerical_grads=False)\n _check_function_must_fail(z, lambda x, y: [2*x + y, x + 2*y])\n _check_function_must_fail(z, numerical_grads=True)\n\n z = sym.Group([2*x + y, sym.block_grad(x + 2*y)])\n _check_function_must_fail(z, numerical_grads=True)\n\n z = sym.Group([2*x + y, x + 2*y, x, y, sym.sum(x)])\n check_function(z, lambda x, y: [2*x + y, x + 2*y, x, y, np.sum(x)])\n\n # passing additional parameters to forward and backward\n def _fwd3(x, p):\n assert p == 'v'\n return x + 1\n def _bwd3(x, p, head_grads):\n assert p == 'v'\n return head_grads\n check_function(x + 1, _fwd3, _bwd3, additional_params={'p': 'v'})\n\n # implicitly created variables and shape/dtype inference for inputs\n x = sym.Variable(\"x\", shape=(2, 3), dtype=0)\n b = sym.Variable(\"b\")\n y = sym.dense(data=x, bias=b, units=4)\n # Don't check gradients on cuda because is doesn't yet support ewise after reduce\n check_function(y, exclude_targets={'cuda'}, numerical_grads=True)\n check_function(y, shape={'x': (3, 4)}, exclude_targets={'cuda'}, numerical_grads=True)\n check_function(y, dtype={'x': 'float64'}, exclude_targets={'cuda'}, numerical_grads=True)\n\n x = sym.Variable(\"x\")\n b = sym.Variable(\"b\")\n w = sym.Variable(\"w\")\n y = sym.dense(data=x, bias=b, weight=w, units=4)\n def _fwd_dense(x, w, b):\n return np.dot(x, w.T) + b\n check_function(y, _fwd_dense, shape={'x': (1,2)}, dtype={'x': 'float32'}, numerical_grads=False)\n check_function(y, _fwd_dense, shape={'x': (1,2)}, dtype={'w': 'float64'}, numerical_grads=False)\n _check_function_must_fail(y, _fwd_dense, shape={'x': (1,2)},\n dtype={'w': 'float64', 'b': 'float32'},\n numerical_grads=False,\n error=nnvm._base.NNVMError)\n # fails because no shape\n _check_function_must_fail(y, _fwd_dense, numerical_grads=False, error=ValueError)\n # ok because type is float32 by default\n check_function(y, _fwd_dense, shape={'x': (1,2)}, numerical_grads=False)\n\ndef test_relu():\n x = sym.Variable(\"x\")\n y = sym.relu(sym.leaky_relu(x, alpha=0.3) - 0.2)\n\n def forward(x):\n x = (x < 0) * x * 0.3 + (x > 0) * x - 0.2\n return (x > 0) * x\n\n def backward(head_grads, x):\n sub = (x < 0) * x * 0.3 + (x > 0) * x - 0.2\n return [(sub > 0).astype(\"float\") * \\\n ((x > 0).astype(\"float\") + 0.3 * (x < 0).astype(\"float\")) * head_grads]\n\n shape = {'x': (1, 3, 32, 32)}\n check_function(y, forward, backward, shape=shape)\n\ndef test_prelu_nchw():\n x = sym.Variable(\"x\")\n a = sym.Variable(\"a\")\n y = sym.prelu(data=x, alpha=a)\n\n def forward(x, a):\n return (x < 0) * (x * a.reshape(3, 1, 1)) + (x>=0) * x\n\n shape = {'x': (1, 3, 32, 32), 'a': (3,)}\n check_function(y, forward, shape=shape)\n\ndef test_prelu_nhwc():\n x = sym.Variable(\"x\")\n a = sym.Variable(\"a\")\n y = sym.prelu(data=x, alpha=a, axis=3)\n\n def forward(x, a):\n return (x < 0) * (x * a.reshape(1, 1, 3)) + (x>=0) * x\n\n shape = {'x': (1, 32, 32, 3), 'a': (3,)}\n check_function(y, forward, shape=shape)\n\ndef test_sym_scalar_pow():\n scalar = 3\n x = sym.Variable(\"x\")\n y = x**scalar\n\n def forward(x):\n return x**scalar\n\n def backward(head_grads, x):\n return [scalar * x**(scalar - 1) * head_grads]\n\n shape = {'x': (1, 3, 32, 32)}\n check_function(y, forward, backward, shape=shape)\n\n\ndef test_scalar_sym_pow():\n scalar = 3\n x = sym.Variable(\"x\")\n y = scalar**x\n\n def forward(x):\n return scalar**x\n\n def backward(head_grads, x):\n return [np.log(scalar) * scalar**x * head_grads]\n\n shape = {'x': (1, 3, 32, 32)}\n check_function(y, forward, backward, shape=shape)\n\n\ndef test_exp():\n x = sym.Variable(\"x\")\n y = sym.exp(x)\n\n def forward(x):\n return np.exp(x)\n\n def backward(head_grads, x):\n return [np.exp(x) * head_grads]\n\n shape = {'x': (1, 3, 32, 32)}\n check_function(y, forward, backward, shape=shape)\n\n\ndef test_log():\n x = sym.Variable(\"x\")\n y = sym.log(x)\n\n def forward(x):\n return np.log(x)\n\n def backward(head_grads, x):\n return [1. / x * head_grads]\n\n shape = {'x': (1, 3, 32, 32)}\n check_function(y, forward, backward, in_range=(0.002, 2.0), shape=shape)\n\n\ndef test_tanh():\n x = sym.Variable(\"x\")\n y = sym.tanh(x)\n\n def forward(x):\n return np.sinh(x) / np.cosh(x)\n\n def backward(head_grads, x):\n y_np = forward(x)\n return [(1 - y_np**2) * head_grads]\n\n shape = {'x': (1, 3, 32, 32)}\n check_function(y, forward, backward, shape=shape)\n\n\ndef test_sigmoid():\n x = sym.Variable(\"x\")\n y = sym.sigmoid(x)\n\n def forward(x):\n return 1.0 / (1.0 + np.exp(-x))\n\n def backward(head_grads, x):\n y_np = forward(x)\n return [y_np *(1 - y_np) * head_grads]\n\n shape = {'x': (1, 3, 32, 32)}\n check_function(y, forward, backward, shape=shape)\n\n\ndef test_softmax():\n x = sym.Variable(\"x\")\n y = sym.softmax(x)\n\n def forward(x):\n return topi.testing.softmax_python(x)\n\n def backward(head_grads, x):\n y = topi.testing.softmax_python(x)\n grad = y * (head_grads - np.sum(y * head_grads, axis=1, keepdims=True))\n return [grad]\n\n check_function(y, forward, backward,\n shape={'x': (10, 1000)}, numerical_grads=False)\n check_function(y, forward, backward,\n shape={'x': (2, 10)})\n\n\ndef test_log_softmax():\n x = sym.Variable(\"x\")\n y = sym.log_softmax(x)\n\n def forward(x):\n return topi.testing.log_softmax_python(x)\n\n def backward(head_grads, x):\n y = topi.testing.log_softmax_python(x)\n grad = head_grads - np.exp(y) * np.sum(head_grads, axis=1, keepdims=True)\n return [grad]\n\n check_function(y, forward, backward,\n shape={'x': (10, 1000)}, numerical_grads=False)\n check_function(y, forward, backward,\n shape={'x': (2, 10)})\n\n\ndef test_dense():\n x = sym.Variable(\"x\", shape=(10, 100))\n w = sym.Variable(\"dense_weight\", shape=(3, 100))\n b = sym.Variable(\"dense_bias\", shape=(3,))\n y = sym.dense(x, w, b, use_bias=True, units=3, name=\"dense\")\n y = sym.flatten(y)\n\n def forward(x, dense_weight, dense_bias):\n return np.dot(x, dense_weight.T) + dense_bias\n shape = {\n 'x': (10, 100),\n 'w': (3, 100),\n 'b': (3,)\n }\n # Don't check gradients on cuda because is doesn't yet support ewise after reduce\n check_function(y, forward, shape=shape,\n exclude_targets={'cuda'}, numerical_grads=True)\n check_function(y, forward, shape=shape,\n only_targets={'cuda'}, numerical_grads=False)\n\n\ndef test_batchnorm():\n x = sym.Variable(\"x\")\n beta = sym.Variable(\"beta\")\n gamma = sym.Variable(\"gamma\")\n moving_var = sym.Variable(\"moving_var\")\n moving_mean = sym.Variable(\"moving_mean\")\n eps = 1e-5\n y = sym.batch_norm(\n x, gamma, beta, moving_mean, moving_var, epsilon=eps)\n\n def forward(x, gamma, beta, moving_mean, moving_var):\n return (x - moving_mean) / np.sqrt(moving_var + eps) * gamma + beta\n\n shape = {\n 'x': (10, 20),\n 'gamma': (20,),\n 'beta': (20,),\n 'moving_mean': (20,),\n 'moving_var': (20,)\n }\n\n check_function(y, forward, in_range=(0.001, 1.0), shape=shape)\n\n\ndef verify_concatenate(ishape, axis):\n x = [sym.Variable(\"x%d\" % i, shape=ishape[i]) for i in range(len(ishape))]\n y = sym.concatenate(*x, axis=axis) + 1\n\n def forward(**kwargs):\n return np.concatenate(list(kwargs.values()), axis=axis) + 1\n\n check_function(y, forward)\n\n\ndef test_concatenate():\n verify_concatenate([(2, 3, 4), (1, 3, 4)], axis=0)\n verify_concatenate([(2, 4), (2, 7)], axis=1)\n\n\ndef verify_split(ishape, indices_or_sections, axis):\n x = sym.Variable(\"x\", shape=ishape)\n y = sym.split(x, indices_or_sections=indices_or_sections, axis=axis)\n\n def forward(x):\n return np.split(x, indices_or_sections, axis=axis)\n\n check_function(y, forward)\n\n\ndef test_split():\n verify_split((2, 3), 2, axis=0)\n verify_split((5, 3), [3], axis=0)\n verify_split((5, 9, 3), [3, 4], axis=1)\n\ndef verify_strided_slice(ishape, begin, end, strideinp=None):\n stride = strideinp if strideinp else [1, 1, 1]\n x = sym.Variable(\"x\", shape=ishape)\n if strideinp:\n y = sym.strided_slice(x, begin = begin, end = end, stride = stride) + 1\n else:\n y = sym.strided_slice(x, begin = begin, end = end) + 1\n\n for i in range(len(begin), 3):\n begin.append(0)\n for i in range(len(end), 3):\n end.append(ishape[i])\n\n def test_forward(x):\n return x[begin[0]:end[0]:stride[0],\n begin[1]:end[1]:stride[1], begin[2]:end[2]:stride[2]] + 1\n\n check_function(y, test_forward)\n\ndef test_strided_slice():\n verify_strided_slice((3, 4, 3), [0, 0, 0], [4, -5, 4], [1, -1, 2])\n verify_strided_slice((3, 4, 3), [1, 1, 0], [4, 4, 3], [2, 1, 1])\n verify_strided_slice((3, 4, 3), [1, -1, 0], [4, -5, 3], [2, -1, 1])\n verify_strided_slice((3, 4, 3), [1, 0, 0], [2, 2, 3], [1, 1, 2])\n verify_strided_slice((3, 4, 3), [1, -1, 0], [2, -3, 3], [1, -1, 1])\n verify_strided_slice((3, 4, 3), [1, 1, 0], [4, 4, 3])\n verify_strided_slice((3, 4, 3), [1, 1, 0], [4, 1000, 3])\n verify_strided_slice((3, 4, 3), [1, 1, 0], [4, 4])\n verify_strided_slice((3, 4, 3), [1, 1], [4, 4, 3])\n\ndef verify_take(src_shape, indices_src, axis=None):\n src_dtype = \"float32\"\n indices_dtype = \"int32\"\n indices_src = np.array(indices_src, dtype=indices_dtype)\n a = sym.Variable(\"a\", shape=src_shape)\n indices = sym.Variable(\"indices\", shape=indices_src.shape)\n y = sym.take(a, indices, axis=axis)\n\n def forward(a, indices):\n return np.take(a, indices=indices, axis=axis)\n\n a_src = np.arange(np.prod(src_shape), dtype=src_dtype).reshape(src_shape)\n\n check_function(y, forward,\n dtype={'a': src_dtype, 'indices': indices_dtype},\n values={'a': a_src, 'indices': indices_src})\n\ndef test_take():\n verify_take((4,), [1])\n verify_take((4,), [[0,1,2,3]])\n verify_take((3,3,3), [[11,25]])\n verify_take((4,), [[0,1],[2,3]])\n verify_take((4,), [1], 0)\n verify_take((2,2), [[[1,0],[0,1]]], 0)\n verify_take((2,2), [[[1,0],[0,1]]], 1)\n verify_take((4,3,5,6), [[2,1,0,0]], -2)\n\n\ndef verify_squeeze(shape, axis):\n x = sym.Variable(\"x\")\n if axis is not None:\n y = sym.squeeze(x, axis=axis)\n else:\n y = sym.squeeze(x)\n y = y + 1\n\n def forward(x):\n return np.squeeze(x, axis=axis) + 1\n\n def backward(head_grads, x):\n return [np.reshape(head_grads, x.shape)]\n\n check_function(y, forward, backward, shape=shape)\n\n\ndef test_squeeze():\n verify_squeeze((1, 3, 2, 5), None)\n verify_squeeze((1, 3, 1), axis=0)\n verify_squeeze((1, 3, 2, 5, 1), axis=-1)\n\n\ndef test_pad():\n x = sym.Variable(\"x\")\n y = sym.pad(x, pad_width=((0, 0), (0, 0), (0, 1), (2, 3)), pad_value=1.)\n\n def forward(x):\n return np.pad(x,\n pad_width=((0, 0), (0, 0), (0, 1), (2, 3)),\n mode='constant', constant_values=1.)\n\n shape = {'x': (1, 3, 28, 28)}\n check_function(y, forward, shape=shape)\n\ndef verify_lrn(ishape, size, axis, bias, alpha, beta):\n x = sym.Variable(\"x\", shape=ishape)\n y = sym.lrn(x, size=size, axis=axis, bias=bias, alpha=alpha, beta=beta)\n\n def forward1(x):\n return topi.testing.lrn_python(x, size, axis, bias, alpha, beta)\n\n check_function(y, forward1)\n\n def forward2(x):\n y = forward1(x)\n return (y > 0)*y\n\n #Checking LRN op followed by elementwise op relu\n check_function(sym.relu(y), forward2, in_range={'x': (-10.0, 10.0)})\n\ndef verify_l2_normalize(ishape, eps, axis):\n x = sym.Variable(\"x\", shape=ishape)\n y = sym.l2_normalize(x, eps=eps, axis=axis)\n\n def forward1(x):\n return topi.testing.l2_normalize_python(x, eps, axis)\n\n check_function(y, forward1)\n\n def forward2(x):\n y = forward1(x)\n return (y > 0)*y\n\n #Checking L2 normalization op followed by elementwise op relu\n check_function(sym.relu(y), forward2, in_range={'x': (-10.0, 10.0)})\n\ndef test_lrn():\n verify_lrn((1, 3, 20, 20), 3, 1, 1.0, 1.0, 0.5)\n verify_lrn((1, 3, 20, 20), 3, 1, 2.0, 1.0, 0.75)\n\ndef test_l2_normalize():\n verify_l2_normalize((1, 3, 20, 20), 0.001, (1,))\n verify_l2_normalize((1, 3, 20, 20), 0.001, (1, 2))\n\nif __name__ == \"__main__\":\n test_check_function()\n test_split()\n test_concatenate()\n test_log_softmax()\n test_batchnorm()\n test_dense()\n test_relu()\n test_prelu_nchw()\n test_prelu_nhwc()\n test_sym_scalar_pow()\n test_scalar_sym_pow()\n test_exp()\n test_log()\n test_tanh()\n test_sigmoid()\n test_softmax()\n test_squeeze()\n test_pad()\n test_take()\n test_lrn()\n test_l2_normalize()\n test_strided_slice()\n",
"\"\"\"\nCompile CoreML Models\n=====================\n**Author**: `Joshua Z. Zhang <https://zhreshold.github.io/>`_\n\nThis article is an introductory tutorial to deploy CoreML models with NNVM.\n\nFor us to begin with, coremltools module is required to be installed.\n\nA quick solution is to install via pip\n\n.. code-block:: bash\n\n pip install -U coremltools --user\n\nor please refer to official site\nhttps://github.com/apple/coremltools\n\"\"\"\nimport nnvm\nimport tvm\nimport coremltools as cm\nimport numpy as np\nfrom PIL import Image\n\ndef download(url, path, overwrite=False):\n import os\n if os.path.isfile(path) and not overwrite:\n print('File {} existed, skip.'.format(path))\n return\n print('Downloading from url {} to {}'.format(url, path))\n try:\n import urllib.request\n urllib.request.urlretrieve(url, path)\n except:\n import urllib\n urllib.urlretrieve(url, path)\n\n######################################################################\n# Load pretrained CoreML model\n# ----------------------------\n# We will download and load a pretrained mobilenet classification network\n# provided by apple in this example\nmodel_url = 'https://docs-assets.developer.apple.com/coreml/models/MobileNet.mlmodel'\nmodel_file = 'mobilenet.mlmodel'\ndownload(model_url, model_file)\n# now you mobilenet.mlmodel on disk\nmlmodel = cm.models.MLModel(model_file)\n# we can load the graph as NNVM compatible model\nsym, params = nnvm.frontend.from_coreml(mlmodel)\n\n######################################################################\n# Load a test image\n# ------------------\n# A single cat dominates the examples!\nfrom PIL import Image\nimg_url = 'https://github.com/dmlc/mxnet.js/blob/master/data/cat.png?raw=true'\ndownload(img_url, 'cat.png')\nimg = Image.open('cat.png').resize((224, 224))\n#x = np.transpose(img, (2, 0, 1))[np.newaxis, :]\nimage = np.asarray(img)\nimage = image.transpose((2, 0, 1))\nx = image[np.newaxis, :]\n######################################################################\n# Compile the model on NNVM\n# ---------------------------\n# We should be familiar with the process right now.\nimport nnvm.compiler\ntarget = 'cuda'\nshape_dict = {'image': x.shape}\nwith nnvm.compiler.build_config(opt_level=2, add_pass=['AlterOpLayout']):\n graph, lib, params = nnvm.compiler.build(sym, target, shape_dict, params=params)\n\n######################################################################\n# Execute on TVM\n# -------------------\n# The process is no different from other example\nfrom tvm.contrib import graph_runtime\nctx = tvm.gpu(0)\ndtype = 'float32'\nm = graph_runtime.create(graph, lib, ctx)\n# set inputs\nm.set_input('image', tvm.nd.array(x.astype(dtype)))\nm.set_input(**params)\n# execute\nm.run()\n# get outputs\ntvm_output = m.get_output(0)\ntop1 = np.argmax(tvm_output.asnumpy()[0])\n\n#####################################################################\n# Look up synset name\n# -------------------\n# Look up prediction top 1 index in 1000 class synset.\nsynset_url = ''.join(['https://gist.githubusercontent.com/zhreshold/',\n '4d0b62f3d01426887599d4f7ede23ee5/raw/',\n '596b27d23537e5a1b5751d2b0481ef172f58b539/',\n 'imagenet1000_clsid_to_human.txt'])\nsynset_name = 'synset.txt'\ndownload(synset_url, synset_name)\nwith open(synset_name) as f:\n synset = eval(f.read())\nprint('Top-1 id', top1, 'class name', synset[top1])\n",
"# Copyright 2018 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\"\"\"Model defination for the Mask-RCNN Model.\n\nDefines model_fn of Mask-RCNN for TF Estimator. The model_fn includes Mask-RCNN\nmodel architecture, loss function, learning rate schedule, and evaluation\nprocedure.\n\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\n\ndef learning_rate_schedule(peak_learning_rate, lr_warmup_init,\n lr_warmup_step, first_lr_drop_step,\n second_lr_drop_step, global_step):\n \"\"\"Handles linear scaling rule, gradual warmup, and LR decay.\"\"\"\n # lr_warmup_init is the starting learning rate; the learning rate is linearly\n # scaled up to the full learning rate after `lr_warmup_step` before decaying.\n linear_warmup = (lr_warmup_init +\n (tf.cast(global_step, dtype=tf.float32) / lr_warmup_step *\n (peak_learning_rate - lr_warmup_init)))\n learning_rate = tf.where(global_step < lr_warmup_step,\n linear_warmup, peak_learning_rate)\n lr_schedule = [[1.0, lr_warmup_step],\n [0.1, first_lr_drop_step],\n [0.01, second_lr_drop_step]]\n for mult, start_global_step in lr_schedule:\n learning_rate = tf.where(global_step < start_global_step, learning_rate,\n peak_learning_rate * mult)\n return learning_rate\n"
] | [
[
"tensorflow.python.framework.load_library.load_op_library",
"tensorflow.sysconfig.get_link_flags",
"torch.utils.ffi.create_extension",
"tensorflow.sysconfig.get_lib",
"tensorflow.sysconfig.get_include",
"tensorflow.sysconfig.get_compile_flags"
],
[
"numpy.nonzero",
"numpy.apply_along_axis",
"numpy.random.uniform",
"numpy.array",
"numpy.zeros"
],
[
"torch.nn.init.ones_",
"torch.Size",
"torch.Tensor",
"torch.nn.init.zeros_"
],
[
"numpy.int",
"numpy.zeros",
"scipy.signal.convolve2d",
"numpy.random.uniform"
],
[
"numpy.exp",
"torch.cuda.is_available"
],
[
"tensorflow.constant",
"tensorflow.control_dependencies",
"tensorflow.less"
],
[
"tensorflow.logging.info",
"tensorflow.gfile.Exists",
"tensorflow.gfile.Glob",
"tensorflow.gfile.Open"
],
[
"tensorflow.contrib.tpu.RunConfig",
"tensorflow.logging.info",
"tensorflow.logging.set_verbosity",
"numpy.prod",
"tensorflow.contrib.tpu.TPUConfig",
"tensorflow.contrib.training.checkpoints_iterator",
"tensorflow.Session.reset"
],
[
"torch.nn.init.uniform_",
"torch.distributed.broadcast",
"torch.utils.collect_env.get_pretty_env_info",
"torch.FloatTensor",
"torch.device",
"torch.distributed.get_rank",
"torch.cuda.cudart",
"torch.cuda.synchronize",
"torch.distributed.init_process_group",
"torch.LongTensor",
"numpy.isnan",
"torch.distributed.is_initialized",
"torch.cuda.FloatTensor",
"torch.distributed.is_available",
"torch.nn.init.zeros_",
"torch.distributed.get_world_size",
"torch.distributed.get_backend",
"torch.cuda.set_device",
"torch.distributed.all_reduce",
"numpy.isinf"
],
[
"tensorflow.test.main",
"tensorflow.test.get_temp_dir"
],
[
"tensorflow.device",
"tensorflow.python.ops.lookup_ops.index_table_from_file",
"tensorflow.concat",
"tensorflow.shape",
"tensorflow.gfile.Exists",
"tensorflow.assert_rank",
"tensorflow.decode_raw",
"tensorflow.reshape",
"tensorflow.gfile.GFile",
"tensorflow.logging.info"
],
[
"matplotlib.use",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ioff",
"matplotlib.pyplot.subplots"
],
[
"numpy.random.uniform"
],
[
"numpy.dot",
"numpy.log",
"numpy.split",
"numpy.take",
"numpy.pad",
"numpy.cosh",
"numpy.reshape",
"numpy.sqrt",
"numpy.squeeze",
"numpy.sinh",
"numpy.full",
"numpy.prod",
"numpy.array",
"numpy.exp",
"numpy.sum"
],
[
"numpy.asarray"
],
[
"tensorflow.cast",
"tensorflow.where"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [
"1.7",
"1.0",
"0.10",
"1.2",
"0.14",
"0.19",
"1.5",
"0.12",
"0.17",
"0.13",
"1.6",
"1.4",
"1.9",
"1.3",
"1.10",
"0.15",
"0.18",
"0.16",
"1.8"
],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"2.7",
"1.12",
"2.6",
"1.4",
"2.2",
"2.3",
"2.4",
"2.9",
"1.5",
"1.7",
"2.5",
"0.12",
"1.0",
"2.8",
"1.2",
"2.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10"
]
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": [
"1.10",
"1.12",
"1.4",
"1.13",
"1.5",
"1.7",
"0.12",
"1.0",
"1.2"
]
}
] |
bellash13/SmartAcademyPython | [
"44d0f6db0fcdcbbf1449a45b073a2b3182a19714"
] | [
"Jour 3/myNumpy.py"
] | [
"import numpy as np\na = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])\nprint(len(a))"
] | [
[
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
benelot/sea-thru | [
"e143b75eca7dcb6887a4ecc98691816e6b9d3b69"
] | [
"seathru_mono_e2e.py"
] | [
"from __future__ import absolute_import, division, print_function\n\nimport os\nimport argparse\n\nimport PIL.Image as pil\nimport rawpy\nimport torch\nfrom torchvision import transforms\nimport numpy as np\n\nimport deps.monodepth2.networks as networks\nfrom deps.monodepth2.utils import download_model_if_doesnt_exist\nfrom seathru import preprocess_monodepth_depth_map, run_pipeline, estimate_sigma, denoise_tv_chambolle\n\n\ndef run(args):\n \"\"\"Function to predict for a single image or folder of images\n \"\"\"\n assert args.model_name is not None, \"You must specify the --model_name parameter; see README.md for an example\"\n\n if torch.cuda.is_available() and not args.no_cuda:\n device = torch.device(\"cuda\")\n else:\n device = torch.device(\"cpu\")\n\n download_model_if_doesnt_exist(args.model_name)\n model_path = os.path.join(\"models\", args.model_name)\n print(\"-> Loading model from \", model_path)\n encoder_path = os.path.join(model_path, \"encoder.pth\")\n depth_decoder_path = os.path.join(model_path, \"depth.pth\")\n\n # LOADING PRETRAINED MODEL\n print(\" Loading pretrained encoder\")\n encoder = networks.ResnetEncoder(18, False)\n loaded_dict_enc = torch.load(encoder_path, map_location=device)\n\n # extract the height and width of image that this model was trained with\n feed_height = loaded_dict_enc['height']\n feed_width = loaded_dict_enc['width']\n filtered_dict_enc = {k: v for k, v in loaded_dict_enc.items() if k in encoder.state_dict()}\n encoder.load_state_dict(filtered_dict_enc)\n encoder.to(device)\n encoder.eval()\n\n print(\" Loading pretrained decoder\")\n depth_decoder = networks.DepthDecoder(\n num_ch_enc=encoder.num_ch_enc, scales=range(4))\n\n loaded_dict = torch.load(depth_decoder_path, map_location=device)\n depth_decoder.load_state_dict(loaded_dict)\n\n depth_decoder.to(device)\n depth_decoder.eval()\n\n # Load image and preprocess\n img = pil.fromarray(rawpy.imread(args.image).postprocess()) if args.raw else pil.open(args.image).convert('RGB')\n img.thumbnail((args.size, args.size), pil.ANTIALIAS)\n original_width, original_height = img.size\n # img = exposure.equalize_adapthist(np.array(img), clip_limit=0.03)\n # img = pil.fromarray((np.round(img * 255.0)).astype(np.uint8))\n input_image = img.resize((feed_width, feed_height), pil.LANCZOS)\n input_image = transforms.ToTensor()(input_image).unsqueeze(0)\n print('Preprocessed image', flush=True)\n\n # PREDICTION\n input_image = input_image.to(device)\n features = encoder(input_image)\n outputs = depth_decoder(features)\n\n disp = outputs[(\"disp\", 0)]\n disp_resized = torch.nn.functional.interpolate(\n disp, (original_height, original_width), mode=\"bilinear\", align_corners=False)\n\n # Saving colormapped depth image\n disp_resized_np = disp_resized.squeeze().cpu().detach().numpy()\n mapped_im_depths = ((disp_resized_np - np.min(disp_resized_np)) / (\n np.max(disp_resized_np) - np.min(disp_resized_np))).astype(np.float32)\n print(\"Processed image\", flush=True)\n print('Loading image...', flush=True)\n depths = preprocess_monodepth_depth_map(mapped_im_depths, args.monodepth_add_depth,\n args.monodepth_multiply_depth)\n recovered = run_pipeline(np.array(img) / 255.0, depths, args)\n # recovered = exposure.equalize_adapthist(scale(np.array(recovered)), clip_limit=0.03)\n sigma_est = estimate_sigma(recovered, multichannel=True, average_sigmas=True) / 10.0\n recovered = denoise_tv_chambolle(recovered, sigma_est, multichannel=True)\n im = pil.fromarray((np.round(recovered * 255.0)).astype(np.uint8))\n\n from pathlib import Path\n p = Path(args.image)\n\n im.save(args.output.format(p.stem), format='png')\n print('Done.')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--image', required=True, help='Input image')\n parser.add_argument('--output', default='outputs/{0}.png', help='Output filename')\n parser.add_argument('--f', type=float, default=2.0, help='f value (controls brightness)')\n parser.add_argument('--l', type=float, default=0.5, help='l value (controls balance of attenuation constants)')\n parser.add_argument('--p', type=float, default=0.01, help='p value (controls locality of illuminant map)')\n parser.add_argument('--min-depth', type=float, default=0.0,\n help='Minimum depth value to use in estimations (range 0-1)')\n parser.add_argument('--max-depth', type=float, default=1.0,\n help='Replacement depth percentile value for invalid depths (range 0-1)')\n parser.add_argument('--spread-data-fraction', type=float, default=0.05,\n help='Require data to be this fraction of depth range away from each other in attenuation estimations')\n parser.add_argument('--size', type=int, default=320, help='Size to output')\n parser.add_argument('--monodepth-add-depth', type=float, default=2.0, help='Additive value for monodepth map')\n parser.add_argument('--monodepth-multiply-depth', type=float, default=10.0,\n help='Multiplicative value for monodepth map')\n parser.add_argument('--model-name', type=str, default=\"mono_1024x320\",\n help='monodepth model name')\n parser.add_argument('--output-graphs', action='store_true', help='Output graphs')\n parser.add_argument('--result-graphs', action='store_true', help='Result graphs')\n parser.add_argument('--raw', action='store_true', help='RAW image')\n args = parser.parse_args()\n run(args)\n"
] | [
[
"torch.load",
"numpy.min",
"numpy.round",
"numpy.max",
"torch.cuda.is_available",
"torch.nn.functional.interpolate",
"torch.device",
"numpy.array"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Yuansurex/deep_learning | [
"b3597b414fb6fed2fbb7af8c8ac0b329c9e77417"
] | [
"ch04/gradient_2d.py"
] | [
"# coding: utf-8\n# cf.http://d.hatena.ne.jp/white_wheels/20100327/p3\nimport numpy as np\nimport matplotlib.pylab as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\ndef _numerical_gradient_no_batch(f, x):\n h = 1e-4 # 0.0001\n grad = np.zeros_like(x)\n\n for idx in range(x.size):\n tmp_val = x[idx]\n x[idx] = float(tmp_val) + h\n fxh1 = f(x) # f(x+h)\n \n x[idx] = tmp_val - h \n fxh2 = f(x) # f(x-h)\n grad[idx] = (fxh1 - fxh2) / (2*h)\n \n x[idx] = tmp_val # 还原值\n \n return grad\n\n\ndef numerical_gradient(f, X):\n if X.ndim == 1:\n return _numerical_gradient_no_batch(f, X)\n else:\n grad = np.zeros_like(X)\n \n for idx, x in enumerate(X): # (0, seq[0]), (1, seq[1]), (2, seq[2]), ...\n grad[idx] = _numerical_gradient_no_batch(f, x)\n \n return grad\n\n\ndef function_2(x):\n if x.ndim == 1:\n return np.sum(x**2)\n else:\n return np.sum(x**2, axis=1)\n\n\ndef tangent_line(f, x):\n d = numerical_gradient(f, x)\n print(d)\n y = f(x) - d*x\n return lambda t: d*t + y\n \nif __name__ == '__main__':\n x0 = np.arange(-2, 2.5, 0.25)\n x1 = np.arange(-2, 2.5, 0.25)\n\n X, Y = np.meshgrid(x0, x1) # 构建平面方格18*18=324\n X = X.flatten() # (324,1)\n Y = Y.flatten()\n\n grad = numerical_gradient(function_2, np.array([X, Y])) # 拼成一个数组\n plt.figure()\n plt.quiver(X, Y, -grad[0], -grad[1], angles=\"xy\",color=\"#666666\") # headwidth=10,scale=40,color=\"#444444\") 绘制二维矢量场图\n plt.xlim([-2, 2])\n plt.ylim([-2, 2])\n plt.xlabel('x0')\n plt.ylabel('x1')\n plt.grid()\n plt.legend()\n plt.draw()\n plt.show()"
] | [
[
"matplotlib.pylab.show",
"matplotlib.pylab.grid",
"matplotlib.pylab.xlim",
"numpy.arange",
"matplotlib.pylab.legend",
"matplotlib.pylab.draw",
"matplotlib.pylab.xlabel",
"matplotlib.pylab.figure",
"numpy.zeros_like",
"matplotlib.pylab.ylabel",
"matplotlib.pylab.ylim",
"matplotlib.pylab.quiver",
"numpy.array",
"numpy.meshgrid",
"numpy.sum"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
syagev/kaggle_dsb | [
"4927f9dee59092f513cbdc02cfc5954c4fb5e7eb"
] | [
"luna16/src/candidates.py"
] | [
"from __future__ import division\nimport numpy as np\nfrom scipy.spatial.distance import pdist, squareform\nfrom scipy.sparse.csgraph import connected_components\nimport pandas as pd\nfrom tqdm import tqdm\nimport blob\nimport pickle\nimport glob\nimport os\nimport sys\nimport scipy.misc\nfrom skimage.io import imread\nfrom skimage import morphology\nfrom scipy import ndimage\nimport cv2\nimport pickle\nimport matplotlib.pyplot as plt\nfrom scipy.ndimage.measurements import center_of_mass\n\nimport subprocess\n\n# import ptvsd\n\nfrom image_read_write import load_itk_image\n\nCANDIDATES_COLUMNS = ['seriesuid','coordX','coordY','coordZ','label']\nTHRESHOLD = 225\n\n\n\ndef unet_candidates():\n cands = glob.glob('%s/*.png' % sys.argv[1]) #\"/razberry/workspace/dsb_nodule_detection.109fd54/*.png\n #df = pd.DataFrame(columns=['seriesuid','coordX','coordY','coordZ','class'])\n data = []\n imname = \"\"\n origin = []\n spacing = []\n nrimages = 0\n for name in tqdm(cands):\n\n #image = imread(name)\n image_t = imread(name)\n image_t = image_t.transpose()\n #Thresholding\n image_t[image_t<THRESHOLD] = 0\n image_t[image_t>0] = 1\n #erosion\n selem = morphology.disk(1)\n image_eroded = image_t\n image_eroded = morphology.binary_erosion(image_t,selem=selem)\n\n label_im, nb_labels = ndimage.label(image_eroded)\n imname3 = os.path.split(name)[1].replace('.png','')\n\n splitted = imname3.split(\"_\")\n slice = splitted[1]\n imname2 = splitted[0][:-1]\n centers = []\n for i in xrange(1,nb_labels+1):\n blob_i = np.where(label_im==i,1,0)\n mass = center_of_mass(blob_i)\n centers.append([mass[1],mass[0]])\n\n\n if imname2 != imname:\n if os.path.isfile(\"../data/1_1_1mm_512_x_512_annotation_masks/spacings/{0}.pickle\".format(imname2)):\n with open(\"../data/1_1_1mm_512_x_512_annotation_masks/spacings/{0}.pickle\".format(imname2), 'rb') as handle:\n dic = pickle.load(handle)\n origin = dic[\"origin\"]\n spacing = dic[\"spacing\"]\n\n imname = imname2\n nrimages +=1\n\n for center in centers:\n # coords = voxel_2_world([int(slice),center[1]+(512-324)*0.5,center[0]+(512-324)*0.5],origin,spacing)\n coords = [int(slice),center[1],center[0]]\n data.append([imname2,coords[2],coords[1],coords[0],'?'])\n\n #if nrimages == 5:\n # break\n\n df = pd.DataFrame(data,columns=CANDIDATES_COLUMNS)\n \n save_candidates('%s/candidates.csv' % work_dir, df)\n \n\ndef candidates_to_image(cands,radius):\n image_names = []\n for subset in xrange(0,10):\n subset_names = glob.glob(\"../data/subset{0}/*.mhd\".format(subset))\n names = [os.path.split(x)[1].replace('.mhd','') for x in subset_names]\n image_names.append(names)\n previous_candidate = \"\"\n images = []\n image = []\n origin = []\n spacing = []\n number = 0\n for candidate in tqdm(cands.values):\n if candidate[0] != previous_candidate:\n number = 0\n previous_candidate = candidate[0]\n for image_subset in xrange(0,10):\n if candidate[0] in image_names[image_subset]:\n image,origin,spacing = load_itk_image(\"../data/subset{0}/{1}.mhd\".format(image_subset,candidate[0]))\n break\n coords = world_2_voxel([candidate[3],candidate[2],candidate[1]],origin,spacing)\n im = image_part_from_candidate(image,coords,radius)\n #images.append(im)\n if candidate[4]:\n label = \"true\"\n else:\n label = \"false\"\n scipy.misc.imsave('../data/samples/{0}_{1}_{2}.jpg'.format(candidate[0],number,label), im)\n number += 1\n return images\n\ndef image_part_from_candidate(image,coords,radius):\n im = np.zeros((radius*2,radius*2))\n for x in xrange(-radius,radius):\n for y in xrange(-radius,radius):\n try:\n im[x+radius,y+radius]=image[coords[0],coords[1]+x,coords[2]+y]\n except:\n im[x+radius,y+radius]=-1000\n return im\n\n\n#Merge candidates of a single scan\ndef merge_candidates_scan(candidates, seriesuid, distance=5.):\n distances = pdist(candidates, metric='euclidean')\n adjacency_matrix = squareform(distances)\n\n # Determine nodes within distance, replace by 1 (=adjacency matrix)\n adjacency_matrix = np.where(adjacency_matrix<=distance,1,0)\n\n # Determine all connected components in the graph\n n, labels = connected_components(adjacency_matrix)\n new_candidates = np.zeros((n,3))\n\n # Take the mean for these connected components\n for cluster_i in range(n):\n points = candidates[np.where(labels==cluster_i)]\n center = np.mean(points,axis=0)\n new_candidates[cluster_i,:] = center\n\n x = new_candidates[:,0]\n y = new_candidates[:,1]\n z = new_candidates[:,2]\n labels = [seriesuid]*len(x)\n class_name = [0]*len(x)\n\n data= zip(labels,x,y,z,class_name)\n\n new_candidates = pd.DataFrame(data,columns=CANDIDATES_COLUMNS)\n\n return new_candidates\n\ndef merge_candidates(df_candidates, distance=5.):\n new_candidates = pd.DataFrame()\n for scan_name in tqdm(df_candidates['seriesuid'].unique()):\n #print \"Merging scan\", scan_name\n df = df_candidates[df_candidates['seriesuid']==scan_name]\n x = df['coordX']\n y = df['coordY']\n z = df['coordZ']\n shape = (len(x),3)\n candidates = np.zeros(shape)\n candidates[:,0]=x\n candidates[:,1]=y\n candidates[:,2]=z\n\n new = merge_candidates_scan(candidates,seriesuid=scan_name,distance=distance)\n new_candidates = new_candidates.append(new)\n\n\n #print new_candidates\n return new_candidates\n\n\ndef world_2_voxel(worldCoord, origin, spacing):\n stretchedVoxelCoord = np.absolute(worldCoord - origin)\n voxelCoord = stretchedVoxelCoord / spacing\n return voxelCoord\n\ndef voxel_2_world(voxelCoord, origin, spacing):\n stretchedVoxelCoord = voxelCoord * spacing\n worldCoord = stretchedVoxelCoord + origin\n return worldCoord\n\ndef load_candidates(filename, as_coords=False):\n candidates = pd.read_csv(filename)\n return candidates\n\n# Save candidates given filename and pandas dataframe\n# Dataframe with columns:\n# seriesuid, coordX, coordY, coordZ, class\n# class seems to be 0 always\ndef save_candidates(filename, df_candidates):\n df_candidates.to_csv(filename, index=False)\n\ndef coords_to_candidates(coords, seriesuid):\n x = coords[:,0]\n y = coords[:,1]\n z = coords[:,2]\n names = [seriesuid]*len(x)\n class_name = [0]*len(x)\n\n data = zip(names,x,y,z,class_name)\n candidates = pd.DataFrame(data,columns=CANDIDATES_COLUMNS)\n return candidates\n\nif __name__ == \"__main__\":\n\n # ptvsd.enable_attach(None, address = ('0.0.0.0', 3001))\n # ptvsd.wait_for_attach()\n\n work_dir = sys.argv[2]\n if not os.path.exists(work_dir):\n os.makedirs(work_dir)\n\n unet_candidates()\n # quit()\n df = load_candidates('%s/candidates.csv' % work_dir)\n # images = candidates_to_image(df,15)\n new_candidates = merge_candidates(df)\n save_candidates('%s/candidates_merged.csv' % work_dir, new_candidates)\n\n\n # #coords = blob.blob_image('../data/hoi.mhd')\n # #with open('../data/hoi_coords.pkl','w') as f:\n # # pickle.dump(coords, f)\n # with open('../data/hoi_coords.pkl','r') as f:\n # candidates = pickle.load(f)\n\n # coords = []\n # #coords = [y for y in [x for x in candidates]]\n\n # #slice, blob, xyz\n\n # for slice in candidates:\n # #print slice\n # for blob in slice:\n # coords.append(blob)\n # #print coords\n\n # image, origin, spacing = load_itk_image('../data/hoi.mhd')\n\n # world_coords = np.array([voxel_2_world(y,origin,spacing) for y in coords])\n\n # #print world_coords\n\n\n # candidates = coords_to_candidates(world_coords, '1.3.6.1.4.1.14519.5.2.1.6279.6001.105756658031515062000744821260')\n # print len(candidates)\n # candidates = merge_candidates(candidates)\n # print len(candidates)\n\n # save_candidates('../data/hoi_candidates.csv', candidates)\n"
] | [
[
"numpy.absolute",
"pandas.read_csv",
"pandas.DataFrame",
"scipy.ndimage.measurements.center_of_mass",
"scipy.ndimage.label",
"scipy.spatial.distance.pdist",
"numpy.mean",
"scipy.spatial.distance.squareform",
"numpy.zeros",
"numpy.where",
"scipy.sparse.csgraph.connected_components"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [
"2.0",
"1.4",
"1.3",
"1.1",
"1.5",
"1.2"
],
"scipy": [],
"tensorflow": []
}
] |
GrimRanger/GeneticAlgorithm | [
"93fa476e82d610f8622276526baa269303a058e0",
"93fa476e82d610f8622276526baa269303a058e0"
] | [
"helps/deap/deap-master/examples/ga/xkcd.py",
"helps/deap/deap-master/examples/es/cma_1+l_minfct.py"
] | [
"# This file is part of DEAP.\n#\n# DEAP is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as\n# published by the Free Software Foundation, either version 3 of\n# the License, or (at your option) any later version.\n#\n# DEAP is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with DEAP. If not, see <http://www.gnu.org/licenses/>.\n\"\"\"This example shows a possible answer to a problem that can be found in this\nxkcd comics: http://xkcd.com/287/. In the comic, the characters want to get\nexactly 15.05$ worth of appetizers, as fast as possible.\"\"\"\nimport random\nfrom operator import attrgetter\nfrom collections import Counter\n\n# We delete the reduction function of the Counter because it doesn't copy added\n# attributes. Because we create a class that inherit from the Counter, the\n# fitness attribute was not copied by the deepcopy.\ndel Counter.__reduce__\n\nimport numpy\n\nfrom deap import algorithms\nfrom deap import base\nfrom deap import creator\nfrom deap import tools\n\nIND_INIT_SIZE = 3\n\n# Create the item dictionary: item id is an integer, and value is \n# a (name, weight, value) 3-uple. Since the comic didn't specified a time for\n# each menu item, random was called to generate a time.\nITEMS_NAME = \"Mixed Fruit\", \"French Fries\", \"Side Salad\", \"Hot Wings\", \"Mozzarella Sticks\", \"Sampler Plate\"\nITEMS_PRICE = 2.15, 2.75, 3.35, 3.55, 4.2, 5.8\nITEMS = dict((name, (price, random.uniform(1, 5))) for name, price in zip(ITEMS_NAME, ITEMS_PRICE))\n\ncreator.create(\"Fitness\", base.Fitness, weights=(-1.0, -1.0))\ncreator.create(\"Individual\", Counter, fitness=creator.Fitness)\n\ntoolbox = base.Toolbox()\ntoolbox.register(\"attr_item\", random.choice, ITEMS_NAME)\ntoolbox.register(\"individual\", tools.initRepeat, creator.Individual, toolbox.attr_item, IND_INIT_SIZE)\ntoolbox.register(\"population\", tools.initRepeat, list, toolbox.individual)\n\ndef evalXKCD(individual, target_price):\n \"\"\"Evaluates the fitness and return the error on the price and the time\n taken by the order if the chef can cook everything in parallel.\"\"\"\n price = 0.0\n times = list()\n for item, number in individual.items():\n price += ITEMS[item][0] * number\n times.append(ITEMS[item][1])\n return abs(price - target_price), max(times)\n\ndef cxCounter(ind1, ind2, indpb):\n \"\"\"Swaps the number of perticular items between two individuals\"\"\"\n for key in ITEMS.keys():\n if random.random() < indpb:\n ind1[key], ind2[key] = ind2[key], ind1[key]\n return ind1, ind2\n\ndef mutCounter(individual):\n \"\"\"Adds or remove an item from an individual\"\"\"\n if random.random() > 0.5:\n individual.update([random.choice(ITEMS_NAME)])\n else:\n val = random.choice(ITEMS_NAME)\n individual.subtract([val])\n if individual[val] < 0:\n del individual[val]\n return individual,\n\ntoolbox.register(\"evaluate\", evalXKCD, target_price=15.05)\ntoolbox.register(\"mate\", cxCounter, indpb=0.5)\ntoolbox.register(\"mutate\", mutCounter)\ntoolbox.register(\"select\", tools.selNSGA2)\n\ndef main():\n NGEN = 40\n MU = 100\n LAMBDA = 200\n CXPB = 0.3\n MUTPB = 0.6\n\n pop = toolbox.population(n=MU)\n hof = tools.ParetoFront()\n \n price_stats = tools.Statistics(key=lambda ind: ind.fitness.values[0])\n time_stats = tools.Statistics(key=lambda ind: ind.fitness.values[1])\n stats = tools.MultiStatistics(price=price_stats, time=time_stats)\n stats.register(\"avg\", numpy.mean, axis=0)\n stats.register(\"std\", numpy.std, axis=0)\n stats.register(\"min\", numpy.min, axis=0)\n\n algorithms.eaMuPlusLambda(pop, toolbox, MU, LAMBDA, CXPB, MUTPB, NGEN,\n stats, halloffame=hof)\n\n return pop, stats, hof\n\nif __name__ == \"__main__\":\n _, _, hof = main()\n from matplotlib import pyplot as plt\n error_price = [i.fitness.values[0] for i in hof]\n time = [i.fitness.values[1] for i in hof]\n plt.plot(error_price, time, 'bo')\n plt.xlabel(\"Price difference\")\n plt.ylabel(\"Total time\")\n plt.show()\n",
"# This file is part of DEAP.\n#\n# DEAP is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License as\n# published by the Free Software Foundation, either version 3 of\n# the License, or (at your option) any later version.\n#\n# DEAP is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with DEAP. If not, see <http://www.gnu.org/licenses/>.\n\nimport array\n\nimport numpy\n\nfrom deap import algorithms\nfrom deap import base\nfrom deap import benchmarks\nfrom deap import cma\nfrom deap import creator\nfrom deap import tools\n\nN=5\ncreator.create(\"FitnessMin\", base.Fitness, weights=(-1.0,))\ncreator.create(\"Individual\", array.array, typecode='d', fitness=creator.FitnessMin)\n\n# See http://www.lri.fr/~hansen/cmaes_inmatlab.html for more details about\n# the rastrigin and other tests for CMA-ES\ntoolbox = base.Toolbox()\ntoolbox.register(\"evaluate\", benchmarks.sphere)\n\ndef main():\n numpy.random.seed()\n\n # The CMA-ES One Plus Lambda algorithm takes a initialized parent as argument\n parent = creator.Individual((numpy.random.rand() * 5) - 1 for _ in range(N))\n parent.fitness.values = toolbox.evaluate(parent)\n \n strategy = cma.StrategyOnePlusLambda(parent, sigma=5.0, lambda_=10)\n toolbox.register(\"generate\", strategy.generate, ind_init=creator.Individual)\n toolbox.register(\"update\", strategy.update)\n\n hof = tools.HallOfFame(1) \n stats = tools.Statistics(lambda ind: ind.fitness.values)\n stats.register(\"avg\", numpy.mean)\n stats.register(\"std\", numpy.std)\n stats.register(\"min\", numpy.min)\n stats.register(\"max\", numpy.max)\n \n algorithms.eaGenerateUpdate(toolbox, ngen=200, halloffame=hof, stats=stats)\n\nif __name__ == \"__main__\":\n main()\n"
] | [
[
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
],
[
"numpy.random.rand",
"numpy.random.seed"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
BioGeek/model-analysis | [
"03db02c21e21b092bc409c8bf263174b90c4e2ae",
"03db02c21e21b092bc409c8bf263174b90c4e2ae"
] | [
"tensorflow_model_analysis/evaluators/aggregate.py",
"tensorflow_model_analysis/model_util.py"
] | [
"# Lint as: python3\n# Copyright 2018 Google LLC\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# https://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\"\"\"Public API for performing evaluations using the EvalMetricsGraph.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\n# Standard __future__ imports\nfrom __future__ import print_function\n\nfrom typing import Any, Dict, Generator, Iterable, List, Optional, Text, Tuple, Union\n\nimport apache_beam as beam\nimport numpy as np\n\nfrom tensorflow_model_analysis import constants\nfrom tensorflow_model_analysis import model_util\nfrom tensorflow_model_analysis import types\nfrom tensorflow_model_analysis.eval_metrics_graph import eval_metrics_graph\nfrom tensorflow_model_analysis.slicer import slicer_lib as slicer\n\n\[email protected]_fn\[email protected]_input_types(Tuple[slicer.SliceKeyType, types.Extracts])\[email protected]_output_types(Tuple[slicer.SliceKeyType, Dict[Text, Any]])\ndef ComputePerSliceMetrics( # pylint: disable=invalid-name\n slice_result: beam.pvalue.PCollection,\n eval_shared_model: types.EvalSharedModel,\n desired_batch_size: Optional[int] = None,\n compute_with_sampling: Optional[bool] = False,\n random_seed_for_testing: Optional[int] = None) -> beam.pvalue.PCollection:\n \"\"\"PTransform for computing, aggregating and combining metrics.\n\n Args:\n slice_result: Incoming PCollection consisting of slice key and extracts.\n eval_shared_model: Shared model parameters for EvalSavedModel.\n desired_batch_size: Optional batch size for batching in Aggregate.\n compute_with_sampling: True to compute with sampling.\n random_seed_for_testing: Seed to use for unit testing.\n\n Returns:\n PCollection of (slice key, dict of metrics).\n \"\"\"\n # TODO(b/123516222): Remove this workaround per discussions in CL/227944001\n slice_result.element_type = beam.typehints.Any\n\n return (\n slice_result\n # _ModelLoadingIdentityFn loads the EvalSavedModel into memory\n # under a shared handle that can be used by subsequent steps.\n # Combiner lifting and producer-consumer fusion should ensure\n # that these steps run in the same process and memory space.\n # TODO(b/69566045): Remove _ModelLoadingIdentityFn and move model\n # loading to CombineFn.setup after it is available in Beam.\n | 'LoadModel' >> beam.ParDo(\n _ModelLoadingIdentityFn(eval_shared_model=eval_shared_model))\n | 'CombinePerSlice' >> beam.CombinePerKey(\n _AggregateCombineFn(\n eval_shared_model=eval_shared_model,\n desired_batch_size=desired_batch_size,\n compute_with_sampling=compute_with_sampling,\n seed_for_testing=random_seed_for_testing))\n | 'InterpretOutput' >> beam.ParDo(\n _ExtractOutputDoFn(eval_shared_model=eval_shared_model)))\n\n\ndef _add_metric_variables( # pylint: disable=invalid-name\n left: types.MetricVariablesType,\n right: types.MetricVariablesType) -> types.MetricVariablesType:\n \"\"\"Returns left and right metric variables combined.\"\"\"\n if left is not None and right is not None:\n if len(left) != len(right):\n raise ValueError('metric variables lengths should match, but got '\n '%d and %d' % (len(left), len(right)))\n return [x + y for x, y in zip(left, right)]\n elif left is not None:\n return left\n else:\n return right\n\n\nclass _AggState(object):\n \"\"\"Combine state for AggregateCombineFn.\n\n There are two parts to the state: the metric variables (the actual state),\n and a list of FeaturesPredictionsLabels or other inputs. See\n _AggregateCombineFn for why we need this.\n \"\"\"\n\n __slots__ = ['metric_variables', 'inputs']\n\n def __init__(self):\n self.metric_variables = None # type: Optional[types.MetricVariablesType]\n self.inputs = [\n ] # type: List[Union[bytes, types.FeaturesPredictionsLabels]]\n\n def copy_from( # pylint: disable=invalid-name\n self, other: '_AggState') -> None:\n if other.metric_variables:\n self.metric_variables = other.metric_variables\n self.inputs = other.inputs\n\n def __iadd__(self, other: '_AggState') -> '_AggState':\n self.metric_variables = _add_metric_variables(self.metric_variables,\n other.metric_variables)\n self.inputs.extend(other.inputs)\n return self\n\n def add_input(self, new_input) -> None:\n self.inputs.append(new_input)\n\n def add_metrics_variables( # pylint: disable=invalid-name\n self, metric_variables: types.MetricVariablesType) -> None:\n self.metric_variables = _add_metric_variables(self.metric_variables,\n metric_variables)\n\n\[email protected]_input_types(types.Extracts)\[email protected]_output_types(Optional[List[Any]])\nclass _AggregateCombineFn(model_util.CombineFnWithModels):\n \"\"\"Aggregate combine function.\n\n This function really does three things:\n 1. Batching of FeaturesPredictionsLabels.\n 3. \"Partial reduction\" of these batches by sending this through the\n \"intro metrics\" step.\n 3. The \"normal\" combining of MetricVariables.\n\n What we really want to do is conceptually the following:\n Predictions | GroupByKey() | KeyAwareBatchElements()\n | ParDo(IntroMetrics()) | CombineValues(CombineMetricVariables()).\n\n but there's no way to KeyAwareBatchElements in Beam, and no way to do partial\n reductions either. Hence, this CombineFn has to do the work of batching,\n partial reduction (intro metrics), and actual combining, all in one.\n\n We do this by accumulating FeaturesPredictionsLabels in the combine state\n until we accumulate a large enough batch, at which point we send them\n through the \"intro metrics\" step. When merging, we merge the metric variables\n and accumulate FeaturesPredictionsLabels accordingly. We do one final\n \"intro metrics\" and merge step before producing the final output value.\n\n See also:\n BEAM-3737: Key-aware batching function\n (https://issues.apache.org/jira/browse/BEAM-3737).\n \"\"\"\n\n # This needs to be large enough to allow for efficient TF invocations during\n # batch flushing, but shouldn't be too large as it also acts as cap on the\n # maximum memory usage of the computation.\n _DEFAULT_DESIRED_BATCH_SIZE = 1000\n\n def __init__(self,\n eval_shared_model: types.EvalSharedModel,\n desired_batch_size: Optional[int] = None,\n compute_with_sampling: Optional[bool] = False,\n seed_for_testing: Optional[int] = None) -> None:\n super(_AggregateCombineFn,\n self).__init__({'': eval_shared_model.model_loader})\n self._seed_for_testing = seed_for_testing\n self._eval_metrics_graph = None # type: eval_metrics_graph.EvalMetricsGraph\n # We really want the batch size to be adaptive like it is in\n # beam.BatchElements(), but there isn't an easy way to make it so.\n # TODO(b/73789023): Figure out how to make this batch size dynamic.\n if desired_batch_size and desired_batch_size > 0:\n self._desired_batch_size = desired_batch_size\n else:\n self._desired_batch_size = self._DEFAULT_DESIRED_BATCH_SIZE\n\n self._compute_with_sampling = compute_with_sampling\n self._random_state = np.random.RandomState(seed_for_testing)\n\n # Metrics.\n self._combine_batch_size = beam.metrics.Metrics.distribution(\n constants.METRICS_NAMESPACE, 'combine_batch_size')\n self._num_compacts = beam.metrics.Metrics.counter(\n constants.METRICS_NAMESPACE, 'num_compacts')\n\n def _poissonify(self, accumulator: _AggState) -> List[bytes]:\n # pylint: disable=line-too-long\n \"\"\"Creates a bootstrap resample of the data in an accumulator.\n\n Given a set of data, it will be represented in the resample set a number of\n times, that number of times is drawn from Poisson(1).\n See\n http://www.unofficialgoogledatascience.com/2015/08/an-introduction-to-poisson-bootstrap26.html\n for a detailed explanation of the technique. This will work technically with\n small or empty batches but as the technique is an approximation, the\n approximation gets better as the number of examples gets larger. If the\n results themselves are empty TFMA will reject the sample. For any samples of\n a reasonable size, the chances of this are exponentially tiny. See \"The\n mathematical fine print\" section of the blog post linked above.\n\n Args:\n accumulator: Accumulator containing FPLs from a sample\n\n Returns:\n A list of FPLs representing a bootstrap resample of the accumulator items.\n \"\"\"\n result = []\n if accumulator.inputs:\n poisson_counts = self._random_state.poisson(1, len(accumulator.inputs))\n for i, input_item in enumerate(accumulator.inputs):\n result.extend([input_item] * poisson_counts[i])\n return result\n\n def _maybe_do_batch(self,\n accumulator: _AggState,\n force: bool = False) -> None:\n \"\"\"Maybe intro metrics and update accumulator in place.\n\n Checks if accumulator has enough FPLs for a batch, and if so, does the\n intro metrics for the batch and updates accumulator in place.\n\n Args:\n accumulator: Accumulator. Will be updated in place.\n force: Force intro metrics even if accumulator has less FPLs than the\n batch size.\n \"\"\"\n\n if self._eval_metrics_graph is None:\n self._setup_if_needed()\n self._eval_metrics_graph = self._loaded_models['']\n batch_size = len(accumulator.inputs)\n if force or batch_size >= self._desired_batch_size:\n if accumulator.inputs:\n self._combine_batch_size.update(batch_size)\n inputs_for_metrics = accumulator.inputs\n if self._compute_with_sampling:\n # If we are computing with multiple bootstrap replicates, use fpls\n # generated by the Poisson bootstrapping technique.\n inputs_for_metrics = self._poissonify(accumulator)\n if inputs_for_metrics:\n accumulator.add_metrics_variables(\n self._eval_metrics_graph.metrics_reset_update_get_list(\n inputs_for_metrics))\n else:\n # Call to metrics_reset_update_get_list does a reset prior to the\n # metrics update, but does not handle empty updates. Explicitly\n # calling just reset here, to make the flow clear.\n self._eval_metrics_graph.reset_metric_variables()\n del accumulator.inputs[:]\n\n def create_accumulator(self) -> _AggState:\n return _AggState()\n\n def add_input(self, accumulator: _AggState,\n elem: types.Extracts) -> _AggState:\n accumulator.add_input(elem[constants.INPUT_KEY])\n self._maybe_do_batch(accumulator)\n return accumulator\n\n def merge_accumulators(self, accumulators: Iterable[_AggState]) -> _AggState:\n result = self.create_accumulator()\n for acc in accumulators:\n result += acc\n # Compact within the loop to avoid accumulating too much data.\n #\n # During the \"map\" side of combining merging happens with memory limits\n # but on the \"reduce\" side it's across all bundles (for a given key).\n #\n # So we could potentially accumulate get num_bundles * batch_size\n # elements if we don't process the batches within the loop, which\n # could cause OOM errors (b/77293756).\n self._maybe_do_batch(result)\n return result\n\n def compact(self, accumulator: _AggState) -> _AggState:\n self._maybe_do_batch(accumulator, force=True) # Guaranteed compaction.\n self._num_compacts.inc(1)\n return accumulator\n\n def extract_output(\n self, accumulator: _AggState) -> Optional[types.MetricVariablesType]:\n # It's possible that the accumulator has not been fully flushed, if it was\n # not produced by a call to compact (which is not guaranteed across all Beam\n # Runners), so we defensively flush it here again, before we extract data\n # from it, to ensure correctness.\n self._maybe_do_batch(accumulator, force=True)\n return accumulator.metric_variables\n\n\[email protected]_input_types(Tuple[slicer.SliceKeyType,\n Optional[List[Any]]])\n# TODO(b/123516222): Add output typehints. Similarly elsewhere that it applies.\nclass _ExtractOutputDoFn(model_util.DoFnWithModels):\n \"\"\"A DoFn that extracts the metrics output.\"\"\"\n\n def __init__(self, eval_shared_model: types.EvalSharedModel) -> None:\n super(_ExtractOutputDoFn,\n self).__init__({'': eval_shared_model.model_loader})\n\n # This keeps track of the number of times the poisson bootstrap encounters\n # an empty set of elements for a slice sample. Should be extremely rare in\n # practice, keeping this counter will help us understand if something is\n # misbehaving.\n self._num_bootstrap_empties = beam.metrics.Metrics.counter(\n constants.METRICS_NAMESPACE, 'num_bootstrap_empties')\n\n def process(\n self, element: Tuple[slicer.SliceKeyType, types.MetricVariablesType]\n ) -> Generator[Tuple[slicer.SliceKeyType, Dict[Text, Any]], None, None]:\n (slice_key, metric_variables) = element\n if metric_variables:\n eval_saved_model = self._loaded_models['']\n result = eval_saved_model.metrics_set_variables_and_get_values(\n metric_variables)\n yield (slice_key, result)\n else:\n # Increase a counter for empty bootstrap samples. When sampling is not\n # enabled, this should never be exected. This should only occur when the\n # slice sizes are incredibly small, and seeing large values of this\n # counter is a sign that something has gone wrong.\n self._num_bootstrap_empties.inc(1)\n\n\[email protected]_input_types(Tuple[slicer.SliceKeyType, types.Extracts])\[email protected]_output_types(Tuple[slicer.SliceKeyType, types.Extracts])\nclass _ModelLoadingIdentityFn(model_util.DoFnWithModels):\n \"\"\"A DoFn that loads the EvalSavedModel and returns the input unchanged.\"\"\"\n\n def __init__(self, eval_shared_model: types.EvalSharedModel) -> None:\n super(_ModelLoadingIdentityFn,\n self).__init__({'': eval_shared_model.model_loader})\n\n def process(\n self, element: Tuple[slicer.SliceKeyType, types.Extracts]\n ) -> List[Tuple[slicer.SliceKeyType, types.Extracts]]:\n return [element]\n",
"# Lint as: python3\n# Copyright 2018 Google LLC\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# https://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\"\"\"Utils for working with models.\"\"\"\n\n# Standard __future__ imports\n\nimport collections\nimport datetime\n\nfrom typing import Any, Callable, Dict, List, Optional, Sequence, Set, Text\n\nfrom absl import logging\nimport apache_beam as beam\nimport tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import\nfrom tensorflow_model_analysis import config\nfrom tensorflow_model_analysis import constants\nfrom tensorflow_model_analysis import types\nfrom tensorflow_model_analysis.eval_saved_model import constants as eval_constants\nfrom tensorflow_model_analysis.eval_saved_model import load\n\nKERAS_INPUT_SUFFIX = '_input'\n\n\ndef get_baseline_model_spec(\n eval_config: config.EvalConfig) -> Optional[config.ModelSpec]:\n \"\"\"Returns baseline model spec.\"\"\"\n for spec in eval_config.model_specs:\n if spec.is_baseline:\n return spec\n return None\n\n\ndef get_model_spec(eval_config: config.EvalConfig,\n model_name: Text) -> Optional[config.ModelSpec]:\n \"\"\"Returns model spec with given model name.\"\"\"\n if len(eval_config.model_specs) == 1 and not model_name:\n return eval_config.model_specs[0]\n for spec in eval_config.model_specs:\n if spec.name == model_name:\n return spec\n return None\n\n\ndef get_model_type(model_spec: config.ModelSpec,\n model_path: Optional[Text] = '',\n tags: Optional[List[Text]] = None) -> Text:\n \"\"\"Returns model type for given model spec taking into account defaults.\n\n The defaults are chosen such that if a model_path is provided and the model\n can be loaded as a keras model then TF_KERAS is assumed. Next, if tags\n are provided and the tags contains 'eval' then TF_ESTIMATOR is assumed.\n Lastly, if the model spec contains an 'eval' signature TF_ESTIMATOR is assumed\n otherwise TF_GENERIC is assumed.\n\n Args:\n model_spec: Model spec.\n model_path: Optional model path to verify if keras model.\n tags: Options tags to verify if eval is used.\n \"\"\"\n if model_spec and model_spec.model_type:\n return model_spec.model_type\n\n if model_path:\n try:\n keras_model = tf.keras.models.load_model(model_path)\n # In some cases, tf.keras.models.load_model can successfully load a\n # saved_model but it won't actually be a keras model.\n if isinstance(keras_model, tf.keras.models.Model):\n return constants.TF_KERAS\n except Exception: # pylint: disable=broad-except\n pass\n\n if tags:\n if tags and eval_constants.EVAL_TAG in tags:\n return constants.TF_ESTIMATOR\n else:\n return constants.TF_GENERIC\n\n signature_names = []\n if model_spec:\n if model_spec.signature_name:\n signature_names.append(model_spec.signature_name)\n elif model_spec.signature_names:\n for signature_name in model_spec.signature_names:\n signature_names.append(signature_name)\n else:\n signature_names.append(tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY)\n\n # Default to serving unless estimator is used and eval signature is used.\n if eval_constants.EVAL_TAG in signature_names:\n return constants.TF_ESTIMATOR\n else:\n return constants.TF_GENERIC\n\n\ndef verify_and_update_eval_shared_models(\n eval_shared_model: Optional[types.MaybeMultipleEvalSharedModels]\n) -> Optional[List[types.EvalSharedModel]]:\n \"\"\"Verifies eval shared models and normnalizes to produce a single list.\n\n The output is normalized such that if a list or dict contains a single entry,\n the model name will always be empty.\n\n Args:\n eval_shared_model: None, a single model, a list of models, or a dict of\n models keyed by model name.\n\n Returns:\n A list of models.\n\n Raises:\n ValueError if dict is passed and keys don't match model names or a\n multi-item list is passed without model names.\n \"\"\"\n if not eval_shared_model:\n return None\n eval_shared_models = []\n if isinstance(eval_shared_model, dict):\n for k, v in eval_shared_model.items():\n if v.model_name and k and k != v.model_name:\n raise ValueError('keys for EvalSharedModel dict do not match '\n 'model_names: dict={}'.format(eval_shared_model))\n if not v.model_name and k:\n v = v._replace(model_name=k)\n eval_shared_models.append(v)\n elif isinstance(eval_shared_model, list):\n eval_shared_models = eval_shared_model\n else:\n eval_shared_models = [eval_shared_model]\n if len(eval_shared_models) > 1:\n for v in eval_shared_models:\n if not v.model_name:\n raise ValueError(\n 'model_name is required when passing multiple EvalSharedModels: '\n 'eval_shared_models={}'.format(eval_shared_models))\n # To maintain consistency between settings where single models are used,\n # always use '' as the model name regardless of whether a name is passed.\n elif len(eval_shared_models) == 1 and eval_shared_models[0].model_name:\n eval_shared_models[0] = eval_shared_models[0]._replace(model_name='')\n return eval_shared_models\n\n\ndef rebatch_by_input_names(\n batch_of_extracts: List[types.Extracts],\n input_names: List[Text],\n input_specs: Optional[Dict[Text, tf.TypeSpec]] = None) -> Dict[Text, Any]:\n \"\"\"Converts a batch of extracts into multiple batches keyed by input names.\n\n Args:\n batch_of_extracts: Batch of extracts (one per example).\n input_names: List of input names to search for features under.\n input_specs: Optional list of type specs associated with inputs.\n\n Returns:\n Dict of batch aligned features keyed by input (feature) name.\n \"\"\"\n # TODO(b/138474171): Make this code more efficient.\n if input_specs is None:\n input_specs = {}\n inputs = collections.defaultdict(list)\n found = {}\n for name in input_names:\n for extract in batch_of_extracts:\n # If features key exist, use that for features, else use input_key\n if constants.FEATURES_KEY in extract:\n input_features = extract[constants.FEATURES_KEY]\n else:\n input_features = extract[constants.INPUT_KEY]\n if isinstance(input_features, dict):\n value = None\n if name in input_features:\n found[name] = True\n value = input_features[name]\n # Some keras models prepend '_input' to the names of the inputs\n # so try under '<name>_input' as well.\n elif (name.endswith(KERAS_INPUT_SUFFIX) and\n name[:-len(KERAS_INPUT_SUFFIX)] in input_features):\n found[name] = True\n value = input_features[name[:-len(KERAS_INPUT_SUFFIX)]]\n if value is not None:\n # If the expected input shape contains only the batch dimension\n # then we need to flatten the np.array. This it to handle tf_hub\n # cases where the inputs can have a single dimension.\n if name in input_specs and len(input_specs[name].shape) == 1:\n if value.size != 1:\n raise ValueError(\n 'model expects inputs with shape (?,), but shape is '\n '{}: input_names={} input_specs={}, extract={}'.format(\n value.shape, input_names, input_specs, extract))\n inputs[name].append(value.item())\n else:\n inputs[name].append(value)\n else:\n # Check that we have not previously added inputs before.\n if inputs:\n raise ValueError(\n 'only a single input was passed, but model expects multiple: '\n 'input_names = {}, extract={}'.format(input_names, extract))\n found[name] = True\n inputs[name].append(input_features)\n if len(found) != len(input_names):\n logging.log_first_n(\n logging.WARNING,\n 'inputs do not match those expected by the model: input_names=%s, '\n 'found in extracts=%s', 1, input_names, found)\n return inputs\n\n\ndef find_input_name_in_features(features: Set[Text],\n input_name: Text) -> Optional[Text]:\n \"\"\"Maps input name to an entry in features. Returns None if not found.\"\"\"\n if input_name in features:\n return input_name\n # Some keras models prepend '_input' to the names of the inputs\n # so try under '<name>_input' as well.\n elif (input_name.endswith(KERAS_INPUT_SUFFIX) and\n input_name[:-len(KERAS_INPUT_SUFFIX)] in features):\n return input_name[:-len(KERAS_INPUT_SUFFIX)]\n return None\n\n\ndef filter_tensors_by_input_names(\n tensors: Dict[Text,\n Any], input_names: List[Text]) -> Optional[Dict[Text, Any]]:\n \"\"\"Filter tensors by input names.\n\n In case we don't find the specified input name in the tensors and there\n exists only one input name, we assume we are feeding serialized examples to\n the model and return None.\n\n Args:\n tensors: Dict of tensors.\n input_names: List of input names.\n\n Returns:\n Filtered tensors.\n\n Raises:\n RuntimeError: When the specified input tensor cannot be found.\n \"\"\"\n if not input_names:\n return None\n result = {}\n tensor_keys = set(tensors.keys())\n for name in input_names:\n tensor_name = find_input_name_in_features(tensor_keys, name)\n if tensor_name is None:\n # This should happen only in the case where the model takes serialized\n # examples as input. Else raise an exception.\n if len(input_names) == 1:\n return None\n raise RuntimeError(\n 'Input tensor not found: {}. Existing keys: {}.'.format(\n name, ','.join(tensors.keys())))\n result[name] = tensors[tensor_name]\n return result\n\n\ndef model_construct_fn( # pylint: disable=invalid-name\n eval_saved_model_path: Optional[Text] = None,\n add_metrics_callbacks: Optional[List[types.AddMetricsCallbackType]] = None,\n include_default_metrics: Optional[bool] = None,\n additional_fetches: Optional[List[Text]] = None,\n blacklist_feature_fetches: Optional[List[Text]] = None,\n tags: Optional[List[Text]] = None,\n model_type: Optional[Text] = constants.TF_ESTIMATOR):\n \"\"\"Returns function for constructing shared models.\"\"\"\n if tags is None:\n tags = [eval_constants.EVAL_TAG]\n\n def construct_fn(model_load_seconds_callback: Callable[[int], None]):\n \"\"\"Thin wrapper for the actual construct to allow for load time metrics.\"\"\"\n\n def construct(): # pylint: disable=invalid-name\n \"\"\"Function for constructing shared models.\"\"\"\n start_time = datetime.datetime.now()\n # If we are evaluating on TPU, initialize the TPU.\n # TODO(b/143484017): Add model warmup for TPU.\n if tf.saved_model.TPU in tags:\n tf.tpu.experimental.initialize_tpu_system()\n if (model_type == constants.TF_ESTIMATOR and\n eval_constants.EVAL_TAG in tags):\n model = load.EvalSavedModel(\n eval_saved_model_path,\n include_default_metrics,\n additional_fetches=additional_fetches,\n blacklist_feature_fetches=blacklist_feature_fetches,\n tags=tags)\n if add_metrics_callbacks:\n model.register_add_metric_callbacks(add_metrics_callbacks)\n model.graph_finalize()\n elif model_type == constants.TF_KERAS:\n # TODO(b/141524386, b/141566408): TPU Inference is not supported\n # for Keras saved_model yet.\n model = tf.keras.models.load_model(eval_saved_model_path)\n else:\n model = tf.compat.v1.saved_model.load_v2(\n eval_saved_model_path, tags=tags)\n end_time = datetime.datetime.now()\n model_load_seconds_callback(int((end_time - start_time).total_seconds()))\n return model\n\n return construct\n\n return construct_fn\n\n\nclass DoFnWithModels(beam.DoFn):\n \"\"\"Abstract class for DoFns that need the shared models.\"\"\"\n\n def __init__(self, model_loaders: Dict[Text, types.ModelLoader]):\n \"\"\"Initializes DoFn using dict of model loaders keyed by model location.\"\"\"\n self._model_loaders = model_loaders\n self._loaded_models = None\n self._model_load_seconds = None\n self._model_load_seconds_distribution = beam.metrics.Metrics.distribution(\n constants.METRICS_NAMESPACE, 'model_load_seconds')\n\n def _set_model_load_seconds(self, model_load_seconds):\n self._model_load_seconds = model_load_seconds\n\n def setup(self):\n self._loaded_models = {}\n for model_name, model_loader in self._model_loaders.items():\n self._loaded_models[model_name] = model_loader.shared_handle.acquire(\n model_loader.construct_fn(self._set_model_load_seconds))\n\n def process(self, elem):\n raise NotImplementedError('Subclasses are expected to override this.')\n\n def finish_bundle(self):\n # Must update distribution in finish_bundle instead of setup\n # because Beam metrics are not supported in setup.\n if self._model_load_seconds is not None:\n self._model_load_seconds_distribution.update(self._model_load_seconds)\n self._model_load_seconds = None\n\n\n# TODO(pachristopher): Define a new base class for Arrow based batched DoFn\n# and inherit from this class. This would allow new Arrow based batched predict\n# predict extractors to share code.\[email protected]_input_types(beam.typehints.List[types.Extracts])\[email protected]_output_types(types.Extracts)\nclass BatchReducibleDoFnWithModels(DoFnWithModels):\n \"\"\"Abstract class for DoFns that need the shared models.\n\n This DoFn will try to use large batch size at first. If a functional failure\n is caught, an attempt will be made to process the elements serially\n at batch size 1.\n \"\"\"\n\n def __init__(self, model_loaders: Dict[Text, types.ModelLoader]):\n super(BatchReducibleDoFnWithModels, self).__init__(model_loaders)\n self._batch_size = (\n beam.metrics.Metrics.distribution(constants.METRICS_NAMESPACE,\n 'batch_size'))\n self._batch_size_failed = (\n beam.metrics.Metrics.distribution(constants.METRICS_NAMESPACE,\n 'batch_size_failed'))\n self._num_instances = beam.metrics.Metrics.counter(\n constants.METRICS_NAMESPACE, 'num_instances')\n\n def _batch_reducible_process(\n self, elements: List[types.Extracts]) -> Sequence[types.Extracts]:\n raise NotImplementedError('Subclasses are expected to override this.')\n\n def process(self, elements: List[types.Extracts]) -> Sequence[types.Extracts]:\n batch_size = len(elements)\n try:\n result = self._batch_reducible_process(elements)\n self._batch_size.update(batch_size)\n self._num_instances.inc(batch_size)\n return result\n except (ValueError, tf.errors.InvalidArgumentError) as e:\n tf.compat.v1.logging.warning(\n 'Large batch_size %s failed with error %s. '\n 'Attempting to run batch through serially.', batch_size, e)\n self._batch_size_failed.update(batch_size)\n result = []\n for element in elements:\n self._batch_size.update(1)\n result.extend(self._batch_reducible_process([element]))\n self._num_instances.inc(len(result))\n return result\n\n\nclass CombineFnWithModels(beam.CombineFn):\n \"\"\"Abstract class for CombineFns that need the shared models.\n\n Until BEAM-3736 (Add SetUp() and TearDown() for CombineFns) is implemented\n users of this class are responsible for calling _setup_if_needed manually.\n \"\"\"\n\n def __init__(self, model_loaders: Dict[Text, types.ModelLoader]):\n \"\"\"Initializes CombineFn using dict of loaders keyed by model location.\"\"\"\n self._model_loaders = model_loaders\n self._loaded_models = None\n self._model_load_seconds = None\n self._model_load_seconds_distribution = beam.metrics.Metrics.distribution(\n constants.METRICS_NAMESPACE, 'model_load_seconds')\n\n def _set_model_load_seconds(self, model_load_seconds):\n self._model_load_seconds = model_load_seconds\n\n # TODO(yifanmai): Merge _setup_if_needed into setup\n # There's no initialisation method for CombineFns.\n # See BEAM-3736: Add SetUp() and TearDown() for CombineFns.\n def _setup_if_needed(self) -> None:\n if self._loaded_models is None:\n self._loaded_models = {}\n for model_name, model_loader in self._model_loaders.items():\n self._loaded_models[model_name] = model_loader.shared_handle.acquire(\n model_loader.construct_fn(self._set_model_load_seconds))\n if self._model_load_seconds is not None:\n self._model_load_seconds_distribution.update(self._model_load_seconds)\n self._model_load_seconds = None\n"
] | [
[
"numpy.random.RandomState"
],
[
"tensorflow.compat.v1.logging.warning",
"tensorflow.keras.models.load_model",
"tensorflow.tpu.experimental.initialize_tpu_system",
"tensorflow.compat.v1.saved_model.load_v2"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Ottovonxu/islide | [
"5ee9954e378f0b5a0722292351cb3cc74b95c1b3",
"5ee9954e378f0b5a0722292351cb3cc74b95c1b3",
"5ee9954e378f0b5a0722292351cb3cc74b95c1b3"
] | [
"ctr/model.py",
"inferenceLSH/classifier.py",
"inferenceLSH/utils.py"
] | [
"import torch\nfrom torch import nn\n\nclass FCN(nn.Module):\n def __init__(self, dimension, num_layers=3, num_class=2):\n super(FCN, self).__init__()\n \n self.first_layer = nn.Linear(dimension, 1000)\n self.first_layer_relu = nn.ReLU()\n mid_layers = []\n for i in range(num_layers - 2):\n mid_layers.append(nn.Linear(1000, 1000))\n mid_layers.append(nn.ReLU())\n self.mid_layers = nn.Sequential(*mid_layers)\n\n self.last_layer = nn.Linear(1000, num_class)\n self.softmax = nn.Softmax(dim=1)\n\n def forward(self, x):\n x = self.first_layer(x)\n x = self.first_layer_relu(x)\n for layer in self.mid_layers:\n x = layer(x)\n x = self.last_layer(x)\n x = self.softmax(x)\n return x\n\nclass LR(nn.Module):\n def __init__(self, dimension, num_class=2):\n super(LR, self).__init__()\n\n self.last_layer = nn.Linear(dimension, num_class)\n self.softmax = nn.Softmax(dim=1)\n\n def forward(self, x):\n x = self.last_layer(x)\n x = self.softmax(x)\n return x\n\n\nclass LRSG(nn.Module):\n def __init__(self, dimension, num_class=1):\n super(LRSG, self).__init__()\n\n self.last_layer = nn.Linear(dimension, num_class)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n x = self.last_layer(x)\n x = self.sigmoid(x)\n return x\n\nclass FCNSG(nn.Module):\n def __init__(self, dimension, num_layers=3, num_class=1):\n super(FCNSG, self).__init__()\n \n self.first_layer = nn.Linear(dimension, 1000)\n self.first_layer_relu = nn.ReLU()\n mid_layers = []\n for i in range(num_layers - 2):\n mid_layers.append(nn.Linear(1000, 1000))\n mid_layers.append(nn.ReLU())\n self.mid_layers = nn.Sequential(*mid_layers)\n\n self.last_layer = nn.Linear(1000, num_class)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n x = self.first_layer(x)\n x = self.first_layer_relu(x)\n for layer in self.mid_layers:\n x = layer(x)\n x = self.last_layer(x)\n x = self.sigmoid(x)\n return x\n",
"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils import data\nimport collections\nfrom collections import Counter\n\nclass Network(nn.Module):\n\tdef __init__(self, input_size, output_size, layer_size):\n\t\tsuper(Network, self).__init__()\n\t\tself.dense1 = nn.Linear(input_size, layer_size[0])\n\t\tself.dense1bn = nn.BatchNorm1d(layer_size[0])\n\n\t\tself.dense2 = nn.Linear(layer_size[0], output_size)\n\n\tdef forward(self, x):\n\t\tx = F.relu(self.dense1bn(self.dense1(x)))\n\t\tx = self.dense2(x)\n\t\treturn F.log_softmax(x,dim=1)\n\t\t#return F.log_softmax(x,dim=1)\n\nclass DatasetTrain(data.Dataset):\n\tdef __init__(self, data, dim, num_class):\n\t\tself.data = data\n\t\tself.input_dim = dim\n\t\tself.num_class = num_class\n\n\tdef __len__(self):\n\t\treturn len(self.data)\n\n\tdef __getitem__(self, index):\n\t\treturn (self.data[index][:self.input_dim], self.data[index][self.input_dim:])\n\nclass DatasetTest(data.Dataset):\n\tdef __init__(self, data, dim, num_class):\n\t\tself.x = data['x']\n\n\t\ty = data['y']\n\t\tlength = max(map(len, y))\n\t\tself.y=np.array([xi+[-1]*(length-len(xi)) for xi in y])\n\n\t\tself.input_dim = dim\n\t\tself.num_class = num_class\n\n\tdef __len__(self):\n\t\treturn len(self.y)\n\n\tdef __getitem__(self, index):\n\t\treturn (self.x[index], self.y[index])\n\t\t#return (self.data[index][:self.input_dim], self.data[index][self.input_dim:])\n\n\n\ndef load_data(train_filepath, test_filepath,batch_size,feature_dim):\n\tfull_data = np.load(train_filepath)\n\ttest_data = np.load(test_filepath).item()\n\n\t#split train valid\n\tlengths = [int(len(full_data) * 0.8), len(full_data) - int(len(full_data) * 0.8) ]\n\tprint(\"train valid data lengths\", lengths)\n\ttrain_data, valid_data = data.random_split(full_data, lengths)\n\n\t# all_data = np.concatenate( (full_data, test_data), axis = 0)\n\t# np.random.shuffle(all_data)\n\t# train_data = all_data[:190000]\n\t# valid_data = all_data[190000:200000 ]\n\t# print(valid_data)\n\t# test_data = all_data[200000 : ]\n\t# print(test_data)\n\n\ttrain_Dataset = DatasetTrain(train_data, feature_dim, num_bins)\n\ttrain_dataloader = data.DataLoader(train_Dataset, batch_size=batch_size, shuffle=True, num_workers=5)\n\n\tvalid_Dataset = DatasetTrain(valid_data, feature_dim, num_bins)\n\tvalid_dataloader = data.DataLoader(valid_Dataset, batch_size=len(valid_data), shuffle=True, num_workers=2)\n\n\ttest_Dataset = DatasetTest(test_data,feature_dim,num_bins)\n\ttest_dataloader = data.DataLoader(test_Dataset, batch_size=len(test_data['y']), shuffle=False, num_workers = 5)\n\n\treturn train_dataloader, valid_dataloader, test_dataloader\n\nif __name__== \"__main__\":\n\n\t# CUDA for PyTorch\n\tuse_cuda = torch.cuda.is_available()\n\tdevice = torch.device(\"cuda:1\" if use_cuda else \"cpu\")\n\tprint(\"device\", device)\n\n\tfeature_dim = 128\n\tnum_bins = 1000\n\thidden_dim= [128]\n\tepoch_num = 20\n\tprint_every = 3000\n\tbatch_size = 32\n\tlr = 0.05\n\n\ttrain_filepath = './data/weight/amz680k/traindata1000_norm.npy'\n\ttest_filepath = './data/weight/amz680k/querydata1000_norm.npy'\n\n\t#train_filepath = './data/weight/amz13k/traindata1000_nonorm.npy'\n\t#test_filepath = './data/weight/amz13k/querydata1000_nonorm.npy'\n\n\ttrain_dataloader, valid_dataloader, test_dataloader = load_data(train_filepath, test_filepath, batch_size, feature_dim)\n\n\t# print(next(iter(train_dataloader)))\n\t# x,y = next(iter(test_dataloader))\n\t# print(len(x))\n\t# print(y)\n\t# print( len(y))\n\n\tnet = Network(feature_dim,num_bins,hidden_dim)\n\tloss_func = nn.NLLLoss() #loss_func = nn.CrossEntropyLoss()\n\toptimizer = optim.SGD(net.parameters(), lr=lr, momentum=0.9)\n\tnet.to(device)\n\tprint(net)\n\n\ttrain_loss_list = []\n\tvalid_loss_list = []\n\tvalid_acc_list=[]\n\tfor epoch in range(epoch_num):\n\n\t\trunning_loss = 0.0\n\t\tfor i, batch in enumerate(train_dataloader):\n\t\t\tx, y = batch\n\t\t\ty = y.reshape(-1)\n\t\t\tx, y = x.to(device), y.to(device)\n\t\t\toptimizer.zero_grad()\n\n\t\t\toutput = net.forward(x.float())\n\t\t\tloss = loss_func(output, y.long())\n\t\t\tloss.backward()\n\t\t\toptimizer.step()\n\n\t\t\t# print statistics\n\t\t\trunning_loss += loss.item()\n\t\t\tif i % print_every == print_every-1: # print every 2000 mini-batches\n\t\t\t\tprint('[%d, %5d] loss: %.3f' % (epoch , i + 1, running_loss / print_every))\n\t\t\t\ttrain_loss_list += [running_loss / print_every]\n\t\t\t\trunning_loss = 0.0\n\n\t\tnet.eval()\n\t\twith torch.no_grad():\n\t\t\tvalid_loss = 0\n\t\t\tvalid_acc = 0\n\t\t\tfor x, y in valid_dataloader:\n\t\t\t\ty = y.reshape(-1)\n\t\t\t\tprint(y)\n\t\t\t\tx, y = x.to(device), y.to(device)\n\t\t\t\toutput = net.forward(x.float())\n\t\t\t\tloss = loss_func(output,y.long())\n\t\t\t\toutput = torch.exp(output)\n\t\t\t\ttop_p,top_c = output.topk(1,dim = 1)\n\t\t\t\tprint(top_c.reshape(-1))\n\t\t\t\tequals = top_c.reshape(-1) == y\n\t\t\t\tvalid_loss += loss.item()\n\t\t\t\tvalid_acc += torch.mean(equals.type(torch.FloatTensor)).item()\n\n\t\t\tprint('[%d] Validation loss: %.3f, Validation accuracy: %.3f\\n' % (epoch, valid_loss/len(valid_dataloader),valid_acc / len(valid_dataloader)))\n\t\t\tvalid_loss_list += [valid_loss/len(valid_dataloader)]\n\t\t\tvalid_acc_list +=[valid_acc / len(valid_dataloader)]\n\t\tnet.train()\n\n\tprint(\"test model\")\n\ttest_loss = 0\n\ttest_acc = 0\n\tnet.eval()\n\twith torch.no_grad():\n\t\tfor x, y in test_dataloader:\n\t\t\t#print(x)\n\t\t\t# print(y)\n\t\t\tprint(\"average number of bin per sample: \",len(y.reshape(-1))/len(y))\n\t\t\tx, y = x.to(device), y.to(device)\n\t\t\toutput = net.forward(x.float())\n\n\t\t\t#get class\n\t\t\toutput = torch.exp(output)\n\t\t\ttop_p,top_c = output.topk(1,dim = 1)\n\n\t\t\ttop_c = top_c.reshape(-1).cpu().detach().numpy()\n\t\t\tprint(\"predict:\", top_c)\n\t\t\tacc = 0\n\t\t\tfor i in range(len(y)):\n\t\t\t\tl = y[i,:].cpu().detach().numpy()\n\t\t\t\t# print(top_c[i])\n\t\t\t\t# print(l)\n\t\t\t\tif top_c[i] in l:\n\t\t\t\t\tacc+=1\n\t\t\tprint(\"test accuracy\", acc / len(top_c))\n\n\n",
"import numpy as np\nfrom sklearn.datasets import load_svmlight_file, dump_svmlight_file\nfrom sklearn import preprocessing\nimport os\nimport sys\n\n\ndef get_query_weight(datafile, weightfile):\n\n # read data file\n #features, labels, num_feat, num_labels = read_data(datafile, header=True)\n features = read_data(datafile, header=True)\n features = features.toarray()\n w0, b0, w1, b1 = read_weight(weightfile)\n\n query =np.matmul(features, w0) + b0\n\n #normalize \n # w1 = preprocessing.normalize(w1, norm = 'l1', axis = 1)\n # query = preprocessing.normalize(query, norm = 'l1', axis = 1)\n\n # print(\"feautre shape\", features.shape)\n # print(\"w0 shape\",w0.shape)\n # print(\"w1 shape\", w1.shape)\n # print(\"query\", query.shape)\n\n return query, w1\n\ndef read_data(filename, header=False, dtype='float32', zero_based=True):\n with open(filename, 'rb') as f:\n _l_shape = None\n if header:\n line = f.readline().decode('utf-8').rstrip(\"\\n\")\n line = line.split(\" \")\n num_samples, num_feat, num_labels = int(line[0]), int(line[1]), int(line[2])\n _l_shape = (num_samples, num_labels)\n else:\n num_samples, num_feat, num_labels = None, None, None\n features, labels = load_svmlight_file(f,n_features = num_feat, multilabel=True)\n return features\n # return features.toarray(), labels, num_feat, num_labels\n\n\ndef read_weight(filename):\n data = np.load(filename)\n w0 = data['W1']\n b0 = data['b1']\n w1 = data['W2']\n b1 = data['b2']\n w1 = np.transpose(w1)\n\n return w0, b0, w1, b1\n\n"
] | [
[
"torch.nn.Softmax",
"torch.nn.Sequential",
"torch.nn.Sigmoid",
"torch.nn.Linear",
"torch.nn.ReLU"
],
[
"torch.nn.BatchNorm1d",
"torch.nn.NLLLoss",
"torch.nn.functional.log_softmax",
"torch.utils.data.DataLoader",
"torch.exp",
"torch.nn.Linear",
"torch.utils.data.random_split",
"torch.no_grad",
"torch.cuda.is_available",
"torch.device",
"numpy.load"
],
[
"numpy.load",
"sklearn.datasets.load_svmlight_file",
"numpy.matmul",
"numpy.transpose"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
pbmanis/pyqtgraph | [
"229f650adfd04053213fe6567d6308a4751a349b",
"229f650adfd04053213fe6567d6308a4751a349b"
] | [
"pyqtgraph/multiprocess/remoteproxy.py",
"examples/HistogramLUT.py"
] | [
"import os, time, sys, traceback, weakref\nimport numpy as np\nimport threading\ntry:\n import __builtin__ as builtins\n import cPickle as pickle\nexcept ImportError:\n import builtins\n import pickle\n\n# color printing for debugging\nfrom ..util import cprint\n\nclass ClosedError(Exception):\n \"\"\"Raised when an event handler receives a request to close the connection\n or discovers that the connection has been closed.\"\"\"\n pass\n\nclass NoResultError(Exception):\n \"\"\"Raised when a request for the return value of a remote call fails\n because the call has not yet returned.\"\"\"\n pass\n\n \nclass RemoteEventHandler(object):\n \"\"\"\n This class handles communication between two processes. One instance is present on \n each process and listens for communication from the other process. This enables\n (amongst other things) ObjectProxy instances to look up their attributes and call \n their methods.\n \n This class is responsible for carrying out actions on behalf of the remote process.\n Each instance holds one end of a Connection which allows python\n objects to be passed between processes.\n \n For the most common operations, see _import(), close(), and transfer()\n \n To handle and respond to incoming requests, RemoteEventHandler requires that its\n processRequests method is called repeatedly (this is usually handled by the Process\n classes defined in multiprocess.processes).\n \n \n \n \n \"\"\"\n handlers = {} ## maps {process ID : handler}. This allows unpickler to determine which process\n ## an object proxy belongs to\n \n def __init__(self, connection, name, pid, debug=False):\n self.debug = debug\n self.conn = connection\n self.name = name\n self.results = {} ## reqId: (status, result); cache of request results received from the remote process\n ## status is either 'result' or 'error'\n ## if 'error', then result will be (exception, formatted exceprion)\n ## where exception may be None if it could not be passed through the Connection.\n self.resultLock = threading.RLock()\n \n self.proxies = {} ## maps {weakref(proxy): proxyId}; used to inform the remote process when a proxy has been deleted.\n self.proxyLock = threading.RLock()\n \n ## attributes that affect the behavior of the proxy. \n ## See ObjectProxy._setProxyOptions for description\n self.proxyOptions = {\n 'callSync': 'sync', ## 'sync', 'async', 'off'\n 'timeout': 10, ## float\n 'returnType': 'auto', ## 'proxy', 'value', 'auto'\n 'autoProxy': False, ## bool\n 'deferGetattr': False, ## True, False\n 'noProxyTypes': [ type(None), str, int, float, tuple, list, dict, LocalObjectProxy, ObjectProxy ],\n }\n if int(sys.version[0]) < 3:\n self.proxyOptions['noProxyTypes'].append(unicode)\n else:\n self.proxyOptions['noProxyTypes'].append(bytes)\n \n self.optsLock = threading.RLock()\n \n self.nextRequestId = 0\n self.exited = False\n \n # Mutexes to help prevent issues when multiple threads access the same RemoteEventHandler\n self.processLock = threading.RLock()\n self.sendLock = threading.RLock()\n \n RemoteEventHandler.handlers[pid] = self ## register this handler as the one communicating with pid\n \n @classmethod\n def getHandler(cls, pid):\n try:\n return cls.handlers[pid]\n except:\n print(pid, cls.handlers)\n raise\n \n def debugMsg(self, msg, *args):\n if not self.debug:\n return\n cprint.cout(self.debug, \"[%d] %s\\n\" % (os.getpid(), str(msg)%args), -1) \n \n def getProxyOption(self, opt):\n with self.optsLock:\n return self.proxyOptions[opt]\n \n def setProxyOptions(self, **kwds):\n \"\"\"\n Set the default behavior options for object proxies.\n See ObjectProxy._setProxyOptions for more info.\n \"\"\"\n with self.optsLock:\n self.proxyOptions.update(kwds)\n \n def processRequests(self):\n \"\"\"Process all pending requests from the pipe, return\n after no more events are immediately available. (non-blocking)\n Returns the number of events processed.\n \"\"\"\n with self.processLock:\n \n if self.exited:\n self.debugMsg(' processRequests: exited already; raise ClosedError.')\n raise ClosedError()\n \n numProcessed = 0\n \n while self.conn.poll():\n #try:\n #poll = self.conn.poll()\n #if not poll:\n #break\n #except IOError: # this can happen if the remote process dies.\n ## might it also happen in other circumstances?\n #raise ClosedError()\n \n try:\n self.handleRequest()\n numProcessed += 1\n except ClosedError:\n self.debugMsg('processRequests: got ClosedError from handleRequest; setting exited=True.')\n self.exited = True\n raise\n #except IOError as err: ## let handleRequest take care of this.\n #self.debugMsg(' got IOError from handleRequest; try again.')\n #if err.errno == 4: ## interrupted system call; try again\n #continue\n #else:\n #raise\n except:\n print(\"Error in process %s\" % self.name)\n sys.excepthook(*sys.exc_info())\n \n if numProcessed > 0:\n self.debugMsg('processRequests: finished %d requests', numProcessed)\n return numProcessed\n \n def handleRequest(self):\n \"\"\"Handle a single request from the remote process. \n Blocks until a request is available.\"\"\"\n result = None\n while True:\n try:\n ## args, kwds are double-pickled to ensure this recv() call never fails \n cmd, reqId, nByteMsgs, optStr = self.conn.recv() \n break\n except EOFError:\n self.debugMsg(' handleRequest: got EOFError from recv; raise ClosedError.')\n ## remote process has shut down; end event loop\n raise ClosedError()\n except IOError as err:\n if err.errno == 4: ## interrupted system call; try again\n self.debugMsg(' handleRequest: got IOError 4 from recv; try again.')\n continue\n else:\n self.debugMsg(' handleRequest: got IOError %d from recv (%s); raise ClosedError.', err.errno, err.strerror)\n raise ClosedError()\n \n self.debugMsg(\" handleRequest: received %s %s\", cmd, reqId)\n \n ## read byte messages following the main request\n byteData = []\n if nByteMsgs > 0:\n self.debugMsg(\" handleRequest: reading %d byte messages\", nByteMsgs)\n for i in range(nByteMsgs):\n while True:\n try:\n byteData.append(self.conn.recv_bytes())\n break\n except EOFError:\n self.debugMsg(\" handleRequest: got EOF while reading byte messages; raise ClosedError.\")\n raise ClosedError()\n except IOError as err:\n if err.errno == 4:\n self.debugMsg(\" handleRequest: got IOError 4 while reading byte messages; try again.\")\n continue\n else:\n self.debugMsg(\" handleRequest: got IOError while reading byte messages; raise ClosedError.\")\n raise ClosedError()\n \n \n try:\n if cmd == 'result' or cmd == 'error':\n resultId = reqId\n reqId = None ## prevents attempt to return information from this request\n ## (this is already a return from a previous request)\n \n opts = pickle.loads(optStr)\n self.debugMsg(\" handleRequest: id=%s opts=%s\", reqId, opts)\n #print os.getpid(), \"received request:\", cmd, reqId, opts\n returnType = opts.get('returnType', 'auto')\n \n if cmd == 'result':\n with self.resultLock:\n self.results[resultId] = ('result', opts['result'])\n elif cmd == 'error':\n with self.resultLock:\n self.results[resultId] = ('error', (opts['exception'], opts['excString']))\n elif cmd == 'getObjAttr':\n result = getattr(opts['obj'], opts['attr'])\n elif cmd == 'callObj':\n obj = opts['obj']\n fnargs = opts['args']\n fnkwds = opts['kwds']\n \n ## If arrays were sent as byte messages, they must be re-inserted into the \n ## arguments\n if len(byteData) > 0:\n for i,arg in enumerate(fnargs):\n if isinstance(arg, tuple) and len(arg) > 0 and arg[0] == '__byte_message__':\n ind = arg[1]\n dtype, shape = arg[2]\n fnargs[i] = np.fromstring(byteData[ind], dtype=dtype).reshape(shape)\n for k,arg in fnkwds.items():\n if isinstance(arg, tuple) and len(arg) > 0 and arg[0] == '__byte_message__':\n ind = arg[1]\n dtype, shape = arg[2]\n fnkwds[k] = np.fromstring(byteData[ind], dtype=dtype).reshape(shape)\n \n if len(fnkwds) == 0: ## need to do this because some functions do not allow keyword arguments.\n try:\n result = obj(*fnargs)\n except:\n print(\"Failed to call object %s: %d, %s\" % (obj, len(fnargs), fnargs[1:]))\n raise\n else:\n result = obj(*fnargs, **fnkwds)\n \n elif cmd == 'getObjValue':\n result = opts['obj'] ## has already been unpickled into its local value\n returnType = 'value'\n elif cmd == 'transfer':\n result = opts['obj']\n returnType = 'proxy'\n elif cmd == 'transferArray':\n ## read array data from next message:\n result = np.fromstring(byteData[0], dtype=opts['dtype']).reshape(opts['shape'])\n returnType = 'proxy'\n elif cmd == 'import':\n name = opts['module']\n fromlist = opts.get('fromlist', [])\n mod = builtins.__import__(name, fromlist=fromlist)\n \n if len(fromlist) == 0:\n parts = name.lstrip('.').split('.')\n result = mod\n for part in parts[1:]:\n result = getattr(result, part)\n else:\n result = map(mod.__getattr__, fromlist)\n \n elif cmd == 'del':\n LocalObjectProxy.releaseProxyId(opts['proxyId'])\n #del self.proxiedObjects[opts['objId']]\n \n elif cmd == 'close':\n if reqId is not None:\n result = True\n returnType = 'value'\n \n exc = None\n except:\n exc = sys.exc_info()\n\n \n \n if reqId is not None:\n if exc is None:\n self.debugMsg(\" handleRequest: sending return value for %d: %s\", reqId, result) \n #print \"returnValue:\", returnValue, result\n if returnType == 'auto':\n with self.optsLock:\n noProxyTypes = self.proxyOptions['noProxyTypes']\n result = self.autoProxy(result, noProxyTypes)\n elif returnType == 'proxy':\n result = LocalObjectProxy(result)\n \n try:\n self.replyResult(reqId, result)\n except:\n sys.excepthook(*sys.exc_info())\n self.replyError(reqId, *sys.exc_info())\n else:\n self.debugMsg(\" handleRequest: returning exception for %d\", reqId) \n self.replyError(reqId, *exc)\n \n elif exc is not None:\n sys.excepthook(*exc)\n \n if cmd == 'close':\n if opts.get('noCleanup', False) is True:\n os._exit(0) ## exit immediately, do not pass GO, do not collect $200.\n ## (more importantly, do not call any code that would\n ## normally be invoked at exit)\n else:\n raise ClosedError()\n \n \n \n def replyResult(self, reqId, result):\n self.send(request='result', reqId=reqId, callSync='off', opts=dict(result=result))\n \n def replyError(self, reqId, *exc):\n print(\"error: %s %s %s\" % (self.name, str(reqId), str(exc[1])))\n excStr = traceback.format_exception(*exc)\n try:\n self.send(request='error', reqId=reqId, callSync='off', opts=dict(exception=exc[1], excString=excStr))\n except:\n self.send(request='error', reqId=reqId, callSync='off', opts=dict(exception=None, excString=excStr))\n \n def send(self, request, opts=None, reqId=None, callSync='sync', timeout=10, returnType=None, byteData=None, **kwds):\n \"\"\"Send a request or return packet to the remote process.\n Generally it is not necessary to call this method directly; it is for internal use.\n (The docstring has information that is nevertheless useful to the programmer\n as it describes the internal protocol used to communicate between processes)\n \n ============== ====================================================================\n **Arguments:**\n request String describing the type of request being sent (see below)\n reqId Integer uniquely linking a result back to the request that generated\n it. (most requests leave this blank)\n callSync 'sync': return the actual result of the request\n 'async': return a Request object which can be used to look up the\n result later\n 'off': return no result\n timeout Time in seconds to wait for a response when callSync=='sync'\n opts Extra arguments sent to the remote process that determine the way\n the request will be handled (see below)\n returnType 'proxy', 'value', or 'auto'\n byteData If specified, this is a list of objects to be sent as byte messages\n to the remote process.\n This is used to send large arrays without the cost of pickling.\n ============== ====================================================================\n \n Description of request strings and options allowed for each:\n \n ============= ============= ========================================================\n request option description\n ------------- ------------- --------------------------------------------------------\n getObjAttr Request the remote process return (proxy to) an\n attribute of an object.\n obj reference to object whose attribute should be \n returned\n attr string name of attribute to return\n returnValue bool or 'auto' indicating whether to return a proxy or\n the actual value. \n \n callObj Request the remote process call a function or \n method. If a request ID is given, then the call's\n return value will be sent back (or information\n about the error that occurred while running the\n function)\n obj the (reference to) object to call\n args tuple of arguments to pass to callable\n kwds dict of keyword arguments to pass to callable\n returnValue bool or 'auto' indicating whether to return a proxy or\n the actual value. \n \n getObjValue Request the remote process return the value of\n a proxied object (must be picklable)\n obj reference to object whose value should be returned\n \n transfer Copy an object to the remote process and request\n it return a proxy for the new object.\n obj The object to transfer.\n \n import Request the remote process import new symbols\n and return proxy(ies) to the imported objects\n module the string name of the module to import\n fromlist optional list of string names to import from module\n \n del Inform the remote process that a proxy has been \n released (thus the remote process may be able to \n release the original object)\n proxyId id of proxy which is no longer referenced by \n remote host\n \n close Instruct the remote process to stop its event loop\n and exit. Optionally, this request may return a \n confirmation.\n \n result Inform the remote process that its request has \n been processed \n result return value of a request\n \n error Inform the remote process that its request failed\n exception the Exception that was raised (or None if the \n exception could not be pickled)\n excString string-formatted version of the exception and \n traceback\n ============= =====================================================================\n \"\"\"\n if self.exited:\n self.debugMsg(' send: exited already; raise ClosedError.')\n raise ClosedError()\n \n with self.sendLock:\n #if len(kwds) > 0:\n #print \"Warning: send() ignored args:\", kwds\n \n if opts is None:\n opts = {}\n \n assert callSync in ['off', 'sync', 'async'], 'callSync must be one of \"off\", \"sync\", or \"async\" (got %r)' % callSync\n if reqId is None:\n if callSync != 'off': ## requested return value; use the next available request ID\n reqId = self.nextRequestId\n self.nextRequestId += 1\n else:\n ## If requestId is provided, this _must_ be a response to a previously received request.\n assert request in ['result', 'error']\n \n if returnType is not None:\n opts['returnType'] = returnType\n \n #print os.getpid(), \"send request:\", request, reqId, opts\n \n ## double-pickle args to ensure that at least status and request ID get through\n try:\n optStr = pickle.dumps(opts)\n except:\n print(\"==== Error pickling this object: ====\")\n print(opts)\n print(\"=======================================\")\n raise\n \n nByteMsgs = 0\n if byteData is not None:\n nByteMsgs = len(byteData)\n \n ## Send primary request\n request = (request, reqId, nByteMsgs, optStr)\n self.debugMsg('send request: cmd=%s nByteMsgs=%d id=%s opts=%s', request[0], nByteMsgs, reqId, opts)\n self.conn.send(request)\n \n ## follow up by sending byte messages\n if byteData is not None:\n for obj in byteData: ## Remote process _must_ be prepared to read the same number of byte messages!\n self.conn.send_bytes(obj)\n self.debugMsg(' sent %d byte messages', len(byteData))\n \n self.debugMsg(' call sync: %s', callSync)\n if callSync == 'off':\n return\n \n req = Request(self, reqId, description=str(request), timeout=timeout)\n if callSync == 'async':\n return req\n \n if callSync == 'sync':\n return req.result()\n \n def close(self, callSync='off', noCleanup=False, **kwds):\n try:\n self.send(request='close', opts=dict(noCleanup=noCleanup), callSync=callSync, **kwds)\n self.exited = True\n except ClosedError:\n pass\n \n def getResult(self, reqId):\n ## raises NoResultError if the result is not available yet\n #print self.results.keys(), os.getpid()\n with self.resultLock:\n haveResult = reqId in self.results\n \n if not haveResult:\n try:\n self.processRequests()\n except ClosedError: ## even if remote connection has closed, we may have \n ## received new data during this call to processRequests()\n pass\n \n with self.resultLock:\n if reqId not in self.results:\n raise NoResultError()\n status, result = self.results.pop(reqId)\n \n if status == 'result': \n return result\n elif status == 'error':\n #print ''.join(result)\n exc, excStr = result\n if exc is not None:\n print(\"===== Remote process raised exception on request: =====\")\n print(''.join(excStr))\n print(\"===== Local Traceback to request follows: =====\")\n raise exc\n else:\n print(''.join(excStr))\n raise Exception(\"Error getting result. See above for exception from remote process.\")\n \n else:\n raise Exception(\"Internal error.\")\n \n def _import(self, mod, **kwds):\n \"\"\"\n Request the remote process import a module (or symbols from a module)\n and return the proxied results. Uses built-in __import__() function, but \n adds a bit more processing:\n \n _import('module') => returns module\n _import('module.submodule') => returns submodule \n (note this differs from behavior of __import__)\n _import('module', fromlist=[name1, name2, ...]) => returns [module.name1, module.name2, ...]\n (this also differs from behavior of __import__)\n \n \"\"\"\n return self.send(request='import', callSync='sync', opts=dict(module=mod), **kwds)\n \n def getObjAttr(self, obj, attr, **kwds):\n return self.send(request='getObjAttr', opts=dict(obj=obj, attr=attr), **kwds)\n \n def getObjValue(self, obj, **kwds):\n return self.send(request='getObjValue', opts=dict(obj=obj), **kwds)\n \n def callObj(self, obj, args, kwds, **opts):\n opts = opts.copy()\n args = list(args)\n \n ## Decide whether to send arguments by value or by proxy\n with self.optsLock:\n noProxyTypes = opts.pop('noProxyTypes', None)\n if noProxyTypes is None:\n noProxyTypes = self.proxyOptions['noProxyTypes']\n \n autoProxy = opts.pop('autoProxy', self.proxyOptions['autoProxy'])\n \n if autoProxy is True:\n args = [self.autoProxy(v, noProxyTypes) for v in args]\n for k, v in kwds.items():\n opts[k] = self.autoProxy(v, noProxyTypes)\n \n byteMsgs = []\n \n ## If there are arrays in the arguments, send those as byte messages.\n ## We do this because pickling arrays is too expensive.\n for i,arg in enumerate(args):\n if arg.__class__ == np.ndarray:\n args[i] = (\"__byte_message__\", len(byteMsgs), (arg.dtype, arg.shape))\n byteMsgs.append(arg)\n for k,v in kwds.items():\n if v.__class__ == np.ndarray:\n kwds[k] = (\"__byte_message__\", len(byteMsgs), (v.dtype, v.shape))\n byteMsgs.append(v)\n \n return self.send(request='callObj', opts=dict(obj=obj, args=args, kwds=kwds), byteData=byteMsgs, **opts)\n\n def registerProxy(self, proxy):\n with self.proxyLock:\n ref = weakref.ref(proxy, self.deleteProxy)\n self.proxies[ref] = proxy._proxyId\n \n def deleteProxy(self, ref):\n if self.send is None:\n # this can happen during shutdown\n return\n\n with self.proxyLock:\n proxyId = self.proxies.pop(ref)\n \n try:\n self.send(request='del', opts=dict(proxyId=proxyId), callSync='off')\n except ClosedError: ## if remote process has closed down, there is no need to send delete requests anymore\n pass\n\n def transfer(self, obj, **kwds):\n \"\"\"\n Transfer an object by value to the remote host (the object must be picklable) \n and return a proxy for the new remote object.\n \"\"\"\n if obj.__class__ is np.ndarray:\n opts = {'dtype': obj.dtype, 'shape': obj.shape}\n return self.send(request='transferArray', opts=opts, byteData=[obj], **kwds) \n else:\n return self.send(request='transfer', opts=dict(obj=obj), **kwds)\n \n def autoProxy(self, obj, noProxyTypes):\n ## Return object wrapped in LocalObjectProxy _unless_ its type is in noProxyTypes.\n for typ in noProxyTypes:\n if isinstance(obj, typ):\n return obj\n return LocalObjectProxy(obj)\n \n \nclass Request(object):\n \"\"\"\n Request objects are returned when calling an ObjectProxy in asynchronous mode\n or if a synchronous call has timed out. Use hasResult() to ask whether\n the result of the call has been returned yet. Use result() to get\n the returned value.\n \"\"\"\n def __init__(self, process, reqId, description=None, timeout=10):\n self.proc = process\n self.description = description\n self.reqId = reqId\n self.gotResult = False\n self._result = None\n self.timeout = timeout\n \n def result(self, block=True, timeout=None):\n \"\"\"\n Return the result for this request. \n \n If block is True, wait until the result has arrived or *timeout* seconds passes.\n If the timeout is reached, raise NoResultError. (use timeout=None to disable)\n If block is False, raise NoResultError immediately if the result has not arrived yet.\n \n If the process's connection has closed before the result arrives, raise ClosedError.\n \"\"\"\n \n if self.gotResult:\n return self._result\n \n if timeout is None:\n timeout = self.timeout \n \n if block:\n start = time.time()\n while not self.hasResult():\n if self.proc.exited:\n raise ClosedError()\n time.sleep(0.005)\n if timeout >= 0 and time.time() - start > timeout:\n print(\"Request timed out: %s\" % self.description)\n import traceback\n traceback.print_stack()\n raise NoResultError()\n return self._result\n else:\n self._result = self.proc.getResult(self.reqId) ## raises NoResultError if result is not available yet\n self.gotResult = True\n return self._result\n \n def hasResult(self):\n \"\"\"Returns True if the result for this request has arrived.\"\"\"\n try:\n self.result(block=False)\n except NoResultError:\n pass\n \n return self.gotResult\n\nclass LocalObjectProxy(object):\n \"\"\"\n Used for wrapping local objects to ensure that they are send by proxy to a remote host.\n Note that 'proxy' is just a shorter alias for LocalObjectProxy.\n \n For example::\n \n data = [1,2,3,4,5]\n remotePlot.plot(data) ## by default, lists are pickled and sent by value\n remotePlot.plot(proxy(data)) ## force the object to be sent by proxy\n \n \"\"\"\n nextProxyId = 0\n proxiedObjects = {} ## maps {proxyId: object}\n \n \n @classmethod\n def registerObject(cls, obj):\n ## assign it a unique ID so we can keep a reference to the local object\n \n pid = cls.nextProxyId\n cls.nextProxyId += 1\n cls.proxiedObjects[pid] = obj\n #print \"register:\", cls.proxiedObjects\n return pid\n \n @classmethod\n def lookupProxyId(cls, pid):\n return cls.proxiedObjects[pid]\n \n @classmethod\n def releaseProxyId(cls, pid):\n del cls.proxiedObjects[pid]\n #print \"release:\", cls.proxiedObjects \n \n def __init__(self, obj, **opts):\n \"\"\"\n Create a 'local' proxy object that, when sent to a remote host,\n will appear as a normal ObjectProxy to *obj*. \n Any extra keyword arguments are passed to proxy._setProxyOptions()\n on the remote side.\n \"\"\"\n self.processId = os.getpid()\n #self.objectId = id(obj)\n self.typeStr = repr(obj)\n #self.handler = handler\n self.obj = obj\n self.opts = opts\n \n def __reduce__(self):\n ## a proxy is being pickled and sent to a remote process.\n ## every time this happens, a new proxy will be generated in the remote process,\n ## so we keep a new ID so we can track when each is released.\n pid = LocalObjectProxy.registerObject(self.obj)\n return (unpickleObjectProxy, (self.processId, pid, self.typeStr, None, self.opts))\n \n## alias\nproxy = LocalObjectProxy\n\ndef unpickleObjectProxy(processId, proxyId, typeStr, attributes=None, opts=None):\n if processId == os.getpid():\n obj = LocalObjectProxy.lookupProxyId(proxyId)\n if attributes is not None:\n for attr in attributes:\n obj = getattr(obj, attr)\n return obj\n else:\n proxy = ObjectProxy(processId, proxyId=proxyId, typeStr=typeStr)\n if opts is not None:\n proxy._setProxyOptions(**opts)\n return proxy\n \nclass ObjectProxy(object):\n \"\"\"\n Proxy to an object stored by the remote process. Proxies are created\n by calling Process._import(), Process.transfer(), or by requesting/calling\n attributes on existing proxy objects.\n \n For the most part, this object can be used exactly as if it\n were a local object::\n \n rsys = proc._import('sys') # returns proxy to sys module on remote process\n rsys.stdout # proxy to remote sys.stdout\n rsys.stdout.write # proxy to remote sys.stdout.write\n rsys.stdout.write('hello') # calls sys.stdout.write('hello') on remote machine\n # and returns the result (None)\n \n When calling a proxy to a remote function, the call can be made synchronous\n (result of call is returned immediately), asynchronous (result is returned later),\n or return can be disabled entirely::\n \n ros = proc._import('os')\n \n ## synchronous call; result is returned immediately\n pid = ros.getpid()\n \n ## asynchronous call\n request = ros.getpid(_callSync='async')\n while not request.hasResult():\n time.sleep(0.01)\n pid = request.result()\n \n ## disable return when we know it isn't needed\n rsys.stdout.write('hello', _callSync='off')\n \n Additionally, values returned from a remote function call are automatically\n returned either by value (must be picklable) or by proxy. \n This behavior can be forced::\n \n rnp = proc._import('numpy')\n arrProxy = rnp.array([1,2,3,4], _returnType='proxy')\n arrValue = rnp.array([1,2,3,4], _returnType='value')\n \n The default callSync and returnType behaviors (as well as others) can be set \n for each proxy individually using ObjectProxy._setProxyOptions() or globally using \n proc.setProxyOptions(). \n \n \"\"\"\n def __init__(self, processId, proxyId, typeStr='', parent=None):\n object.__init__(self)\n ## can't set attributes directly because setattr is overridden.\n self.__dict__['_processId'] = processId\n self.__dict__['_typeStr'] = typeStr\n self.__dict__['_proxyId'] = proxyId\n self.__dict__['_attributes'] = ()\n ## attributes that affect the behavior of the proxy. \n ## in all cases, a value of None causes the proxy to ask\n ## its parent event handler to make the decision\n self.__dict__['_proxyOptions'] = {\n 'callSync': None, ## 'sync', 'async', None \n 'timeout': None, ## float, None\n 'returnType': None, ## 'proxy', 'value', 'auto', None\n 'deferGetattr': None, ## True, False, None\n 'noProxyTypes': None, ## list of types to send by value instead of by proxy\n 'autoProxy': None,\n }\n \n self.__dict__['_handler'] = RemoteEventHandler.getHandler(processId)\n self.__dict__['_handler'].registerProxy(self) ## handler will watch proxy; inform remote process when the proxy is deleted.\n \n def _setProxyOptions(self, **kwds):\n \"\"\"\n Change the behavior of this proxy. For all options, a value of None\n will cause the proxy to instead use the default behavior defined\n by its parent Process.\n \n Options are:\n \n ============= =============================================================\n callSync 'sync', 'async', 'off', or None. \n If 'async', then calling methods will return a Request object\n which can be used to inquire later about the result of the \n method call.\n If 'sync', then calling a method\n will block until the remote process has returned its result\n or the timeout has elapsed (in this case, a Request object\n is returned instead).\n If 'off', then the remote process is instructed _not_ to \n reply and the method call will return None immediately.\n returnType 'auto', 'proxy', 'value', or None. \n If 'proxy', then the value returned when calling a method\n will be a proxy to the object on the remote process.\n If 'value', then attempt to pickle the returned object and\n send it back.\n If 'auto', then the decision is made by consulting the\n 'noProxyTypes' option.\n autoProxy bool or None. If True, arguments to __call__ are \n automatically converted to proxy unless their type is \n listed in noProxyTypes (see below). If False, arguments\n are left untouched. Use proxy(obj) to manually convert\n arguments before sending. \n timeout float or None. Length of time to wait during synchronous \n requests before returning a Request object instead.\n deferGetattr True, False, or None. \n If False, all attribute requests will be sent to the remote \n process immediately and will block until a response is\n received (or timeout has elapsed).\n If True, requesting an attribute from the proxy returns a\n new proxy immediately. The remote process is _not_ contacted\n to make this request. This is faster, but it is possible to \n request an attribute that does not exist on the proxied\n object. In this case, AttributeError will not be raised\n until an attempt is made to look up the attribute on the\n remote process.\n noProxyTypes List of object types that should _not_ be proxied when\n sent to the remote process.\n ============= =============================================================\n \"\"\"\n for k in kwds:\n if k not in self._proxyOptions:\n raise KeyError(\"Unrecognized proxy option '%s'\" % k)\n self._proxyOptions.update(kwds)\n \n def _getValue(self):\n \"\"\"\n Return the value of the proxied object\n (the remote object must be picklable)\n \"\"\"\n return self._handler.getObjValue(self)\n \n def _getProxyOption(self, opt):\n val = self._proxyOptions[opt]\n if val is None:\n return self._handler.getProxyOption(opt)\n return val\n \n def _getProxyOptions(self):\n return dict([(k, self._getProxyOption(k)) for k in self._proxyOptions])\n \n def __reduce__(self):\n return (unpickleObjectProxy, (self._processId, self._proxyId, self._typeStr, self._attributes))\n \n def __repr__(self):\n #objRepr = self.__getattr__('__repr__')(callSync='value')\n return \"<ObjectProxy for process %d, object 0x%x: %s >\" % (self._processId, self._proxyId, self._typeStr)\n \n \n def __getattr__(self, attr, **kwds):\n \"\"\"\n Calls __getattr__ on the remote object and returns the attribute\n by value or by proxy depending on the options set (see\n ObjectProxy._setProxyOptions and RemoteEventHandler.setProxyOptions)\n \n If the option 'deferGetattr' is True for this proxy, then a new proxy object\n is returned _without_ asking the remote object whether the named attribute exists.\n This can save time when making multiple chained attribute requests,\n but may also defer a possible AttributeError until later, making\n them more difficult to debug.\n \"\"\"\n opts = self._getProxyOptions()\n for k in opts:\n if '_'+k in kwds:\n opts[k] = kwds.pop('_'+k)\n if opts['deferGetattr'] is True:\n return self._deferredAttr(attr)\n else:\n #opts = self._getProxyOptions()\n return self._handler.getObjAttr(self, attr, **opts)\n \n def _deferredAttr(self, attr):\n return DeferredObjectProxy(self, attr)\n \n def __call__(self, *args, **kwds):\n \"\"\"\n Attempts to call the proxied object from the remote process.\n Accepts extra keyword arguments:\n \n _callSync 'off', 'sync', or 'async'\n _returnType 'value', 'proxy', or 'auto'\n \n If the remote call raises an exception on the remote process,\n it will be re-raised on the local process.\n \n \"\"\"\n opts = self._getProxyOptions()\n for k in opts:\n if '_'+k in kwds:\n opts[k] = kwds.pop('_'+k)\n return self._handler.callObj(obj=self, args=args, kwds=kwds, **opts)\n \n \n ## Explicitly proxy special methods. Is there a better way to do this??\n \n def _getSpecialAttr(self, attr):\n ## this just gives us an easy way to change the behavior of the special methods\n return self._deferredAttr(attr)\n \n def __getitem__(self, *args):\n return self._getSpecialAttr('__getitem__')(*args)\n \n def __setitem__(self, *args):\n return self._getSpecialAttr('__setitem__')(*args, _callSync='off')\n \n def __setattr__(self, *args):\n return self._getSpecialAttr('__setattr__')(*args, _callSync='off')\n \n def __str__(self, *args):\n return self._getSpecialAttr('__str__')(*args, _returnType='value')\n \n def __len__(self, *args):\n return self._getSpecialAttr('__len__')(*args)\n \n def __add__(self, *args):\n return self._getSpecialAttr('__add__')(*args)\n \n def __sub__(self, *args):\n return self._getSpecialAttr('__sub__')(*args)\n \n def __div__(self, *args):\n return self._getSpecialAttr('__div__')(*args)\n \n def __truediv__(self, *args):\n return self._getSpecialAttr('__truediv__')(*args)\n \n def __floordiv__(self, *args):\n return self._getSpecialAttr('__floordiv__')(*args)\n \n def __mul__(self, *args):\n return self._getSpecialAttr('__mul__')(*args)\n \n def __pow__(self, *args):\n return self._getSpecialAttr('__pow__')(*args)\n \n def __iadd__(self, *args):\n return self._getSpecialAttr('__iadd__')(*args, _callSync='off')\n \n def __isub__(self, *args):\n return self._getSpecialAttr('__isub__')(*args, _callSync='off')\n \n def __idiv__(self, *args):\n return self._getSpecialAttr('__idiv__')(*args, _callSync='off')\n \n def __itruediv__(self, *args):\n return self._getSpecialAttr('__itruediv__')(*args, _callSync='off')\n \n def __ifloordiv__(self, *args):\n return self._getSpecialAttr('__ifloordiv__')(*args, _callSync='off')\n \n def __imul__(self, *args):\n return self._getSpecialAttr('__imul__')(*args, _callSync='off')\n \n def __ipow__(self, *args):\n return self._getSpecialAttr('__ipow__')(*args, _callSync='off')\n \n def __rshift__(self, *args):\n return self._getSpecialAttr('__rshift__')(*args)\n \n def __lshift__(self, *args):\n return self._getSpecialAttr('__lshift__')(*args)\n \n def __irshift__(self, *args):\n return self._getSpecialAttr('__irshift__')(*args, _callSync='off')\n \n def __ilshift__(self, *args):\n return self._getSpecialAttr('__ilshift__')(*args, _callSync='off')\n \n def __eq__(self, *args):\n return self._getSpecialAttr('__eq__')(*args)\n \n def __ne__(self, *args):\n return self._getSpecialAttr('__ne__')(*args)\n \n def __lt__(self, *args):\n return self._getSpecialAttr('__lt__')(*args)\n \n def __gt__(self, *args):\n return self._getSpecialAttr('__gt__')(*args)\n \n def __le__(self, *args):\n return self._getSpecialAttr('__le__')(*args)\n \n def __ge__(self, *args):\n return self._getSpecialAttr('__ge__')(*args)\n \n def __and__(self, *args):\n return self._getSpecialAttr('__and__')(*args)\n \n def __or__(self, *args):\n return self._getSpecialAttr('__or__')(*args)\n \n def __xor__(self, *args):\n return self._getSpecialAttr('__xor__')(*args)\n \n def __iand__(self, *args):\n return self._getSpecialAttr('__iand__')(*args, _callSync='off')\n \n def __ior__(self, *args):\n return self._getSpecialAttr('__ior__')(*args, _callSync='off')\n \n def __ixor__(self, *args):\n return self._getSpecialAttr('__ixor__')(*args, _callSync='off')\n \n def __mod__(self, *args):\n return self._getSpecialAttr('__mod__')(*args)\n \n def __radd__(self, *args):\n return self._getSpecialAttr('__radd__')(*args)\n \n def __rsub__(self, *args):\n return self._getSpecialAttr('__rsub__')(*args)\n \n def __rdiv__(self, *args):\n return self._getSpecialAttr('__rdiv__')(*args)\n \n def __rfloordiv__(self, *args):\n return self._getSpecialAttr('__rfloordiv__')(*args)\n \n def __rtruediv__(self, *args):\n return self._getSpecialAttr('__rtruediv__')(*args)\n \n def __rmul__(self, *args):\n return self._getSpecialAttr('__rmul__')(*args)\n \n def __rpow__(self, *args):\n return self._getSpecialAttr('__rpow__')(*args)\n \n def __rrshift__(self, *args):\n return self._getSpecialAttr('__rrshift__')(*args)\n \n def __rlshift__(self, *args):\n return self._getSpecialAttr('__rlshift__')(*args)\n \n def __rand__(self, *args):\n return self._getSpecialAttr('__rand__')(*args)\n \n def __ror__(self, *args):\n return self._getSpecialAttr('__ror__')(*args)\n \n def __rxor__(self, *args):\n return self._getSpecialAttr('__ror__')(*args)\n \n def __rmod__(self, *args):\n return self._getSpecialAttr('__rmod__')(*args)\n \n def __hash__(self):\n ## Required for python3 since __eq__ is defined.\n return id(self)\n \nclass DeferredObjectProxy(ObjectProxy):\n \"\"\"\n This class represents an attribute (or sub-attribute) of a proxied object.\n It is used to speed up attribute requests. Take the following scenario::\n \n rsys = proc._import('sys')\n rsys.stdout.write('hello')\n \n For this simple example, a total of 4 synchronous requests are made to \n the remote process: \n \n 1) import sys\n 2) getattr(sys, 'stdout')\n 3) getattr(stdout, 'write')\n 4) write('hello')\n \n This takes a lot longer than running the equivalent code locally. To\n speed things up, we can 'defer' the two attribute lookups so they are\n only carried out when neccessary::\n \n rsys = proc._import('sys')\n rsys._setProxyOptions(deferGetattr=True)\n rsys.stdout.write('hello')\n \n This example only makes two requests to the remote process; the two \n attribute lookups immediately return DeferredObjectProxy instances \n immediately without contacting the remote process. When the call \n to write() is made, all attribute requests are processed at the same time.\n \n Note that if the attributes requested do not exist on the remote object, \n making the call to write() will raise an AttributeError.\n \"\"\"\n def __init__(self, parentProxy, attribute):\n ## can't set attributes directly because setattr is overridden.\n for k in ['_processId', '_typeStr', '_proxyId', '_handler']:\n self.__dict__[k] = getattr(parentProxy, k)\n self.__dict__['_parent'] = parentProxy ## make sure parent stays alive\n self.__dict__['_attributes'] = parentProxy._attributes + (attribute,)\n self.__dict__['_proxyOptions'] = parentProxy._proxyOptions.copy()\n \n def __repr__(self):\n return ObjectProxy.__repr__(self) + '.' + '.'.join(self._attributes)\n \n def _undefer(self):\n \"\"\"\n Return a non-deferred ObjectProxy referencing the same object\n \"\"\"\n return self._parent.__getattr__(self._attributes[-1], _deferGetattr=False)\n\n",
"# -*- coding: utf-8 -*-\n\"\"\"\nUse a HistogramLUTWidget to control the contrast / coloration of an image.\n\"\"\"\n\n## Add path to library (just for examples; you do not need this) \nimport initExample\n\nimport numpy as np\nfrom pyqtgraph.Qt import QtGui, QtCore\nimport pyqtgraph as pg\n\n\napp = QtGui.QApplication([])\nwin = QtGui.QMainWindow()\nwin.resize(800,600)\nwin.show()\nwin.setWindowTitle('pyqtgraph example: Histogram LUT')\n\ncw = QtGui.QWidget()\nwin.setCentralWidget(cw)\n\nl = QtGui.QGridLayout()\ncw.setLayout(l)\nl.setSpacing(0)\n\nv = pg.GraphicsView()\nvb = pg.ViewBox()\nvb.setAspectLocked()\nv.setCentralItem(vb)\nl.addWidget(v, 0, 0, 3, 1)\n\nw = pg.HistogramLUTWidget()\nl.addWidget(w, 0, 1)\n\nmonoRadio = QtGui.QRadioButton('mono')\nrgbaRadio = QtGui.QRadioButton('rgba')\nl.addWidget(monoRadio, 1, 1)\nl.addWidget(rgbaRadio, 2, 1)\nmonoRadio.setChecked(True)\n\ndef setLevelMode():\n mode = 'mono' if monoRadio.isChecked() else 'rgba'\n w.setLevelMode(mode)\nmonoRadio.toggled.connect(setLevelMode)\n\ndata = pg.gaussianFilter(np.random.normal(size=(256, 256, 3)), (20, 20, 0))\nfor i in range(32):\n for j in range(32):\n data[i*8, j*8] += .1\nimg = pg.ImageItem(data)\nvb.addItem(img)\nvb.autoRange()\n\nw.setImageItem(img)\n\n\n## Start Qt event loop unless running in interactive mode.\nif __name__ == '__main__':\n import sys\n if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):\n QtGui.QApplication.instance().exec_()\n"
] | [
[
"numpy.fromstring"
],
[
"numpy.random.normal"
]
] | [
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
},
{
"matplotlib": [],
"numpy": [],
"pandas": [],
"scipy": [],
"tensorflow": []
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.