repo_name
stringlengths 8
130
| hexsha
sequence | file_path
sequence | code
sequence | apis
sequence |
---|---|---|---|---|
young24/LFP-simulation-in-turtle-brain | [
"cd801dc02804d027b7c245b0f0ca9c8b00f8d450"
] | [
"simulation-code/old_functions/average_rotated_trials.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 "
] | [
[
"numpy.load"
]
] |
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"
]
] |
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"
]
] |
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"
]
] |
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"
] | [
[
"numpy.vstack",
"numpy.zeros",
"numpy.set_printoptions",
"numpy.random.choice",
"torch.nn.CrossEntropyLoss",
"torch.tensor",
"torch.eq",
"torch.max",
"numpy.array",
"numpy.concatenate"
]
] |
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.ensemble.RandomForestClassifier",
"sklearn.model_selection.train_test_split",
"sklearn.datasets.make_classification"
]
] |
arifmudi/Python-Machine-Learning-By-Example-Third-Edition | [
"7bdc45df2b519e3c0a929b03f0ac6fe30e028382"
] | [
"chapter5/encoding.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)"
] | [
[
"sklearn.feature_extraction.DictVectorizer",
"pandas.DataFrame"
]
] |
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"
]
] |
bvsk35/Hopping_Bot | [
"5a8c7d4fdb4ae0a5ddf96002deb3c9ba1116c216"
] | [
"GPS_Berkley/experiments/mjc_disc_cost_pilqr_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"
] | [
[
"numpy.array",
"numpy.ones"
]
] |
jylinman/tensorflow | [
"5248d111c3aeaf9f560cd77bff0f183f38e31e0b",
"5248d111c3aeaf9f560cd77bff0f183f38e31e0b"
] | [
"tensorflow/python/kernel_tests/py_func_test.py",
"tensorflow/python/kernel_tests/dense_update_ops_no_tsan_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"
] | [
[
"tensorflow.zeros",
"numpy.cosh",
"tensorflow.python.ops.script_ops._py_funcs.size",
"numpy.sinh",
"tensorflow.Graph",
"numpy.array",
"tensorflow.constant",
"numpy.fft.rfft",
"tensorflow.test.main",
"tensorflow.py_func"
],
[
"tensorflow.initialize_all_variables",
"numpy.ones",
"tensorflow.zeros",
"tensorflow.assign_add",
"tensorflow.fill",
"tensorflow.test.main"
]
] |
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.matmul",
"pandas.read_csv",
"numpy.matrix",
"pandas.DataFrame",
"pandas.concat"
]
] |
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.random.uniform",
"numpy.zeros",
"numpy.ascontiguousarray",
"numpy.arange",
"numpy.clip",
"numpy.random.rand",
"numpy.stack",
"numpy.concatenate",
"numpy.random.randint",
"numpy.round",
"numpy.split"
]
] |
jphkun/CEASIOMpy | [
"6425cfeb786019fccfc98aaa2fd676b2de466dac"
] | [
"ceasiompy/utils/WB/UncGeometry/WithFuseGeom/Wings/wingsgeom.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"
] | [
[
"numpy.sqrt",
"numpy.zeros",
"numpy.all",
"numpy.shape",
"numpy.amax",
"numpy.where",
"numpy.mean"
]
] |
ineersa/DeepPavlov | [
"8200bf9a0f0b378baad4ee0eb75b59453f516004"
] | [
"deeppavlov/core/layers/tf_csoftmax_attention.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"
] | [
[
"tensorflow.reshape",
"tensorflow.matmul",
"tensorflow.name_scope",
"tensorflow.concat",
"tensorflow.reduce_sum",
"tensorflow.less",
"tensorflow.constant",
"tensorflow.transpose",
"tensorflow.stack",
"tensorflow.shape",
"tensorflow.ones_like",
"tensorflow.while_loop",
"tensorflow.dynamic_partition",
"tensorflow.layers.dense",
"tensorflow.dynamic_stitch",
"tensorflow.zeros",
"tensorflow.map_fn",
"tensorflow.reduce_mean",
"tensorflow.exp"
]
] |
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.ones",
"numpy.isclose",
"numpy.testing.assert_array_equal",
"numpy.arange",
"numpy.random.rand",
"numpy.linspace"
]
] |
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"
] | [
[
"pandas.Series",
"numpy.zeros",
"numpy.argmin",
"numpy.abs",
"numpy.argmax",
"numpy.concatenate",
"numpy.mean"
]
] |
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.array",
"numpy.concatenate",
"numpy.random.shuffle"
]
] |
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.argpartition",
"numpy.argsort",
"numpy.zeros"
]
] |
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"
]
] |
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.tensor_shape.unknown_shape",
"tensorflow.core.framework.function_pb2.GradientDef",
"tensorflow.core.framework.versions_pb2.VersionDef",
"tensorflow.python.platform.tf_logging.warn",
"tensorflow.python.framework.registry.Registry",
"tensorflow.python.util.compat.as_str",
"tensorflow.python.framework.device.merge_device",
"tensorflow.core.framework.node_def_pb2.NodeDef",
"tensorflow.python.util.compat.as_bytes",
"tensorflow.core.framework.attr_value_pb2.AttrValue.ListValue",
"tensorflow.python.framework.op_def_registry.get_registered_ops",
"tensorflow.python.framework.dtypes.as_dtype",
"tensorflow.python.platform.tf_logging.warning",
"tensorflow.core.framework.tensor_shape_pb2.TensorShapeProto",
"tensorflow.core.framework.graph_pb2.GraphDef"
]
] |
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"
]
] |
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"
] | [
[
"numpy.nanmean",
"matplotlib.pyplot.switch_backend",
"numpy.meshgrid",
"numpy.array"
]
] |
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"
]
] |
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"
]
] |
daq-tools/PyTables | [
"0949d41e611e6882a49248c6d82b1da9a994e788"
] | [
"bench/sqlite3-search-bench.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"
] | [
[
"numpy.arange",
"numpy.random.uniform",
"numpy.array"
]
] |
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.allclose",
"numpy.zeros"
]
] |
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.DataFrame",
"pandas.read_html",
"pandas.to_datetime",
"pandas.concat",
"numpy.round"
]
] |
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"
]
] |
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.cuda.is_available",
"torch.device",
"torch.nn.CrossEntropyLoss"
]
] |
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.close",
"matplotlib.pyplot.subplots"
]
] |
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.ones",
"numpy.sum",
"tensorflow.unstack",
"numpy.asarray",
"numpy.copy",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits",
"numpy.stack",
"tensorflow.image.resize_image_with_crop_or_pad",
"tensorflow.Graph",
"numpy.expand_dims",
"tensorflow.contrib.image.rotate",
"numpy.where",
"numpy.linspace",
"tensorflow.stack",
"tensorflow.shape",
"numpy.zeros",
"tensorflow.contrib.image.transform",
"numpy.equal",
"numpy.argmax",
"tensorflow.image.resize_images",
"numpy.all",
"tensorflow.Session",
"numpy.maximum",
"tensorflow.py_func",
"tensorflow.pad",
"tensorflow.placeholder",
"numpy.array",
"numpy.concatenate"
]
] |
michaelneuder/parkes_lab_fa19 | [
"18d9f564e0df9c17ac5d54619ed869d778d4f6a4"
] | [
"proof_of_work/multiagent/turn_based/v4/selfishagentv4.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 "
] | [
[
"numpy.asarray"
]
] |
qinvador/qiskit-terra | [
"4e104de3c113c01688a0ed06b2f2cb1a958fce44"
] | [
"qiskit/extensions/standard/u2.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"
] | [
[
"numpy.sqrt",
"numpy.exp"
]
] |
a1600012888/mmdetection3d | [
"2e01549c56dabf1965abc975a7301a8d746973ad",
"2e01549c56dabf1965abc975a7301a8d746973ad"
] | [
"plugin/radar/depth_net.py",
"plugin/depth_v3/model.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"
] | [
[
"torch.nn.PixelShuffle",
"torch.sum",
"torch.nn.init.xavier_uniform_",
"torch.no_grad",
"torch.tensor",
"torch.nn.Upsample",
"torch.numel",
"torch.abs",
"torch.cat",
"torch.clamp"
],
[
"torch.sum",
"torch.no_grad",
"torch.tensor",
"torch.numel",
"torch.abs",
"torch.clamp"
]
] |
thomaskuestner/CNNArt | [
"c2fc639dd2ce035f6ca90113290682a0ccd26fb8"
] | [
"utils/RigidPatching.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"
] | [
[
"numpy.multiply",
"tensorflow.stack",
"numpy.zeros",
"numpy.dtype",
"numpy.lib.pad",
"tensorflow.math.multiply",
"tensorflow.Variable",
"numpy.round",
"tensorflow.slice",
"numpy.concatenate"
]
] |
Zshan0/Cirq | [
"610b0d4ea3a7862169610797266734c844ddcc1f"
] | [
"cirq-core/cirq/protocols/apply_unitary_protocol.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"
] | [
[
"numpy.array",
"numpy.empty_like",
"numpy.may_share_memory"
]
] |
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.sum",
"numpy.random.randint",
"numpy.isclose",
"numpy.asarray"
]
] |
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.style.use",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.axvline",
"matplotlib.pyplot.legend",
"numpy.zeros",
"scipy.signal.lombscargle",
"matplotlib.pyplot.figure",
"numpy.random.seed",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"numpy.random.normal",
"numpy.sin",
"numpy.linspace",
"matplotlib.pyplot.xlabel"
]
] |
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"
]
] |
notantony/Grid-Anchor-based-Image-Cropping-Pytorch | [
"32a2dea9151c123c8e589bd196450f56cf3ef7d1"
] | [
"rod_align/_ext/rod_align/__init__.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"
] | [
[
"torch.utils.ffi._wrap_function"
]
] |
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"
] | [
[
"torch.rand",
"torch.cuda.synchronize",
"torch.sqrt",
"torch.cuda.Event",
"matplotlib.pyplot.ylabel",
"torch.eye",
"torch.cuda.empty_cache",
"torch.add",
"matplotlib.pyplot.figure",
"numpy.savez",
"matplotlib.pyplot.savefig",
"torch.norm",
"torch.optim.Adam",
"torch.from_numpy",
"matplotlib.use",
"numpy.load",
"matplotlib.pyplot.tick_params",
"torch.tensor",
"torch.optim.lr_scheduler.StepLR",
"torch.einsum",
"torch.pow",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.grid",
"torch.zeros",
"matplotlib.pyplot.xlabel"
]
] |
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.random.uniform",
"numpy.max",
"numpy.min"
]
] |
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.pyplot.draw",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.suptitle",
"matplotlib.pyplot.hist",
"matplotlib.pyplot.plot",
"matplotlib.ticker.MultipleLocator",
"matplotlib.pyplot.xlabel"
]
] |
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.stack",
"numpy.pad",
"numpy.zeros"
]
] |
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.DataFrame",
"pandas.read_html",
"pandas.compat.StringIO"
]
] |
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"
] | [
[
"torch.utils.data.DataLoader",
"torch.load",
"torch.manual_seed",
"torch.no_grad",
"numpy.random.seed",
"torch.cuda.is_available",
"numpy.std",
"numpy.mean"
]
] |
jych/Theano | [
"c74da33de3768e231ffa0d92d9d11667a2a5aedb",
"c74da33de3768e231ffa0d92d9d11667a2a5aedb"
] | [
"theano/scan_module/scan_op.py",
"theano/sandbox/scan_module/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"
] | [
[
"numpy.asarray",
"numpy.max",
"numpy.min",
"numpy.zeros"
],
[
"numpy.min",
"numpy.int64"
]
] |
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.DataFrame",
"pandas.concat"
]
] |
takeratta/chainer | [
"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"
] | [
"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"
] | [
[
"numpy.array",
"numpy.random.uniform",
"numpy.random.shuffle",
"numpy.arange"
],
[
"numpy.random.uniform"
],
[
"numpy.random.uniform",
"numpy.zeros"
]
] |
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"
]
] |
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"
]
] |
Esail/tensorflow | [
"2538e68a69e585696175bd972cae119e06bde294",
"2538e68a69e585696175bd972cae119e06bde294"
] | [
"tensorflow/contrib/data/python/ops/threadpool.py",
"tensorflow/contrib/data/python/kernel_tests/optimization/map_parallelization_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"
] | [
[
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.data.ops.dataset_ops.flat_structure",
"tensorflow.python.ops.gen_experimental_dataset_ops.experimental_thread_pool_handle",
"tensorflow.python.eager.context.context"
],
[
"tensorflow.contrib.data.python.ops.optimization.optimize",
"tensorflow.contrib.data.python.ops.optimization.assert_next",
"tensorflow.python.ops.math_ops.greater",
"tensorflow.python.data.ops.dataset_ops.Dataset.range",
"tensorflow.python.platform.test.main",
"tensorflow.python.framework.ops.control_dependencies",
"tensorflow.python.ops.random_ops.random_uniform"
]
] |
koonimaru/DeepGMAP | [
"7daac354229fc25fba81649b741921345dc5db05"
] | [
"deepgmap/train/deepshark_local_oop_1d.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 "
] | [
[
"numpy.sum",
"matplotlib.pyplot.plot",
"numpy.polyfit",
"tensorflow.global_variables_initializer",
"numpy.nanmean",
"matplotlib.pyplot.figure",
"tensorflow.device",
"numpy.reshape",
"numpy.vsplit",
"matplotlib.pyplot.title",
"numpy.load",
"tensorflow.get_collection",
"matplotlib.pyplot.axis",
"numpy.poly1d",
"tensorflow.Session",
"numpy.array",
"tensorflow.ConfigProto",
"tensorflow.placeholder",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"numpy.shape",
"numpy.round",
"numpy.concatenate"
]
] |
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.sin",
"numpy.median"
]
] |
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"
] | [
[
"scipy.io.loadmat",
"numpy.zeros",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.imshow",
"scipy.io.savemat",
"matplotlib.pyplot.show"
]
] |
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"
] | [
[
"numpy.matmul",
"numpy.fft.fft",
"numpy.sin",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.tight_layout",
"numpy.size",
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.plot",
"numpy.linspace",
"matplotlib.pyplot.xlabel"
]
] |
EsauPR/3d-pose-baseline | [
"2f521fe3008ddee81b666550606f7405efd2f547"
] | [
"src/3d_pose_vae_filter_kin.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"
] | [
[
"numpy.ones",
"tensorflow.keras.optimizers.Adam",
"tensorflow.math.reduce_std",
"tensorflow.Variable",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.savefig",
"tensorflow.device",
"numpy.random.choice",
"tensorflow.GradientTape",
"tensorflow.train.CheckpointManager",
"matplotlib.use",
"matplotlib.gridspec.GridSpec",
"numpy.tile",
"tensorflow.print",
"matplotlib.pyplot.axis",
"tensorflow.math.reduce_max",
"numpy.arange",
"numpy.array_split",
"tensorflow.math.reduce_mean",
"matplotlib.pyplot.close",
"tensorflow.keras.optimizers.RMSprop",
"matplotlib.pyplot.subplot",
"tensorflow.math.reduce_min",
"numpy.concatenate",
"tensorflow.keras.metrics.Mean"
]
] |
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.nn.Linear",
"torch.randn",
"torch.linspace",
"torch.eye",
"torch.zeros",
"torch.nn.ELU",
"torch.device",
"torch.nn.Softplus"
]
] |
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.linspace",
"numpy.random.seed"
]
] |
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",
"torch.from_numpy",
"torch.cross",
"numpy.sqrt",
"torch.cat"
]
] |
robertjankowski/social-media-influence-on-covid-pandemic | [
"1b04aa4aa88d4788fdfa023eb21b1f00b16f0110"
] | [
"scripts/data_utils.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"
] | [
[
"pandas.read_csv"
]
] |
cffbots/ESMValTool | [
"a9b6592a02f2085634a214ff5f36a736fa18ff47"
] | [
"tests/system/esmvaltool_testlib.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"
] | [
[
"numpy.array_equal"
]
] |
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.array",
"numpy.linalg.inv",
"numpy.roots"
]
] |
gobaRules/eo-learn | [
"25174e5e0759e35b616712423f01b03527a4b227"
] | [
"visualization/eolearn/visualization/eoexecutor_visualization.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"
] | [
[
"matplotlib.use",
"matplotlib.pyplot.switch_backend"
]
] |
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.zeros_like",
"numpy.sum",
"numpy.zeros",
"numpy.ones_like",
"numpy.exp",
"numpy.size",
"numpy.sqrt",
"numpy.linspace"
]
] |
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"
] | [
[
"numpy.array",
"numpy.expand_dims",
"torch.load",
"torch.exp"
]
] |
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.sqrt",
"numpy.ones",
"numpy.diff",
"numpy.linalg.inv",
"numpy.cos",
"numpy.array",
"numpy.dot"
]
] |
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"
] | [
[
"pandas.Series",
"tensorflow.compat.v1.Session",
"tensorflow.compat.v1.ConfigProto",
"tensorflow.keras.models.load_model",
"pandas.DataFrame",
"tensorflow.config.experimental.set_visible_devices",
"pandas.read_hdf",
"numpy.array",
"tensorflow.config.experimental.list_physical_devices"
]
] |
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"
] | [
[
"numpy.load",
"tensorflow.keras.optimizers.Adam",
"matplotlib.pyplot.legend",
"tensorflow.keras.callbacks.TensorBoard",
"matplotlib.pyplot.savefig",
"pandas.DataFrame",
"matplotlib.pyplot.xlabel",
"numpy.argmax",
"matplotlib.pyplot.title",
"tensorflow.keras.callbacks.CSVLogger",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"sklearn.model_selection.KFold",
"numpy.array",
"matplotlib.pyplot.plot",
"numpy.unique"
]
] |
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.DatetimeIndex",
"numpy.hypot",
"pandas.read_csv",
"numpy.any",
"pandas.DataFrame",
"numpy.median",
"pandas.Timedelta",
"numpy.recarray",
"numpy.log10",
"numpy.sqrt",
"numpy.isscalar"
]
] |
SIAAAAAA/MMT-PSM | [
"0835c01c5010d3337778f452e9d96416e0f8a11a"
] | [
"maskrcnn_benchmark/structures/segmentation_mask.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"
] | [
[
"torch.as_tensor",
"torch.from_numpy",
"numpy.zeros"
]
] |
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.utils.data.DataLoader",
"torch.optim.SGD",
"torch.optim.lr_scheduler.LambdaLR",
"torch.manual_seed",
"torch.autograd.Variable",
"numpy.random.seed",
"numpy.logspace",
"numpy.mean"
]
] |
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)"
] | [
[
"numpy.random.seed",
"tensorflow.Session",
"tensorflow.global_variables_initializer"
]
] |
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"
]
] |
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.imsave",
"matplotlib.image.imread"
]
] |
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()"
] | [
[
"pandas.read_csv",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.close",
"matplotlib.pyplot.subplots"
]
] |
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"
]
] |
LUGUANSONG/i2g2i | [
"ec532f2e128301472478c3d8fe4c72929e2967a4"
] | [
"combine_sg2im_neural_motifs/model.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"
] | [
[
"torch.load",
"torch.nn.functional.interpolate"
]
] |
charzy/vocalremover | [
"9bf983ab5579c36c75447c74eec0400d78ab49f9"
] | [
"inference.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"
] | [
[
"torch.load",
"numpy.ceil",
"numpy.concatenate",
"torch.no_grad",
"numpy.abs",
"numpy.asarray",
"numpy.exp",
"torch.cuda.is_available",
"numpy.clip",
"numpy.angle",
"torch.from_numpy",
"numpy.pad",
"torch.device"
]
] |
SaynaEbrahimi/hat | [
"c1333c5f1639a011db336a99eecb75cac8738212"
] | [
"src/run.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"
] | [
[
"torch.cuda.manual_seed",
"numpy.savetxt",
"torch.manual_seed",
"numpy.random.seed",
"torch.cuda.is_available",
"torch.cat"
]
] |
ishani-chakraborty/models | [
"367486482c5fe6fc896868edf9bbde7519deb52d"
] | [
"official/nlp/tasks/question_answering.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"
] | [
[
"tensorflow.zeros",
"tensorflow.data.Dataset.range",
"tensorflow.keras.metrics.SparseCategoricalAccuracy",
"tensorflow.io.gfile.GFile",
"tensorflow.reduce_mean",
"tensorflow.keras.initializers.TruncatedNormal",
"tensorflow.cast",
"tensorflow.constant",
"tensorflow.distribute.get_strategy"
]
] |
t2wain/machine-learning | [
"4b5e1a24fab7c4ab42f646f7785191ff3d3283ba"
] | [
"tnmlearn/other/convenience.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))"
] | [
[
"numpy.zeros",
"numpy.float32",
"numpy.median",
"numpy.abs"
]
] |
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"
]
] |
yonghoonlee/dymos | [
"602109eee4a1b061444dd2b45c7b1ed0ac1aa0f4"
] | [
"dymos/transcriptions/transcription_base.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"
] | [
[
"numpy.asarray",
"numpy.arange",
"numpy.prod",
"numpy.broadcast_to",
"numpy.isscalar"
]
] |
CJL89/pandas | [
"6210077d32a9e9675526ea896e6d1f9189629d4a"
] | [
"pandas/tests/plotting/test_groupby.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"
] | [
[
"pandas.compat.is_platform_windows",
"pandas.DataFrame",
"numpy.random.randn",
"numpy.random.choice",
"pandas._testing.close",
"numpy.arange",
"numpy.random.normal",
"pandas.Index",
"pandas._testing.RNGContext"
]
] |
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.zeros_like",
"numpy.zeros",
"numpy.random.seed",
"numpy.exp",
"numpy.random.rand",
"numpy.dot"
]
] |
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.models.Sequential",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.optimizers.Adam",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.preprocessing.image.ImageDataGenerator",
"tensorflow.keras.layers.MaxPooling2D",
"numpy.set_printoptions",
"matplotlib.pyplot.subplots",
"numpy.argmax",
"matplotlib.pyplot.show",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.Conv2D"
]
] |
mitchelldaneker/deepxde | [
"62e09b62ceaab6bda2ebbd02dc30ad99c2990302"
] | [
"deepxde/model.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"
] | [
[
"numpy.sum",
"numpy.hstack"
]
] |
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.utils.data._utils.worker.ManagerWatchdog",
"torch.multiprocessing.Event",
"torch.manual_seed",
"torch.multiprocessing.Queue",
"torch.cuda.current_device",
"torch._C._set_worker_signal_handlers",
"torch.set_num_threads",
"torch.cuda.is_available",
"torch.utils.data._utils.signal_handling._set_SIGCHLD_handler",
"torch.LongTensor",
"torch.multiprocessing.Process"
]
] |
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.FloatTensor",
"torch.nn.Linear",
"torch.cos",
"numpy.cos",
"torch.sin",
"numpy.power",
"torch.arange",
"torch.nn.Identity",
"numpy.sin",
"torch.nn.Dropout"
]
] |
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"
]
] |
mengkai94/training_results_v0.6 | [
"43dc3e250f8da47b5f8833197d74cb8cf1004fc9"
] | [
"Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/horovod/setup.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"
] | [
[
"tensorflow.sysconfig.get_include",
"torch.utils.ffi.create_extension",
"tensorflow.sysconfig.get_lib",
"tensorflow.sysconfig.get_link_flags",
"tensorflow.sysconfig.get_compile_flags",
"tensorflow.python.framework.load_library.load_op_library"
]
] |
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"
]
] |
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.round",
"torch.cuda.is_available",
"numpy.max",
"numpy.min",
"numpy.array",
"torch.device",
"torch.nn.functional.interpolate"
]
] |
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.xlim",
"numpy.zeros_like",
"matplotlib.pylab.grid",
"numpy.sum",
"matplotlib.pylab.quiver",
"matplotlib.pylab.ylabel",
"matplotlib.pylab.legend",
"matplotlib.pylab.draw",
"matplotlib.pylab.figure",
"matplotlib.pylab.show",
"numpy.arange",
"matplotlib.pylab.xlabel",
"matplotlib.pylab.ylim",
"numpy.array",
"numpy.meshgrid"
]
] |
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"
] | [
[
"scipy.spatial.distance.pdist",
"numpy.zeros",
"scipy.ndimage.label",
"pandas.read_csv",
"scipy.ndimage.measurements.center_of_mass",
"pandas.DataFrame",
"scipy.sparse.csgraph.connected_components",
"numpy.absolute",
"numpy.mean",
"numpy.where",
"scipy.spatial.distance.squareform"
]
] |
GrimRanger/GeneticAlgorithm | [
"93fa476e82d610f8622276526baa269303a058e0"
] | [
"helps/deap/deap-master/examples/ga/xkcd.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"
] | [
[
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
]
] |
BioGeek/model-analysis | [
"03db02c21e21b092bc409c8bf263174b90c4e2ae"
] | [
"tensorflow_model_analysis/evaluators/aggregate.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"
] | [
[
"numpy.random.RandomState"
]
] |
Ottovonxu/islide | [
"5ee9954e378f0b5a0722292351cb3cc74b95c1b3"
] | [
"ctr/model.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"
] | [
[
"torch.nn.Linear",
"torch.nn.Softmax",
"torch.nn.Sequential",
"torch.nn.Sigmoid",
"torch.nn.ReLU"
]
] |
pbmanis/pyqtgraph | [
"229f650adfd04053213fe6567d6308a4751a349b"
] | [
"pyqtgraph/multiprocess/remoteproxy.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"
] | [
[
"numpy.fromstring"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.