repo_name
stringlengths 8
130
| hexsha
sequence | file_path
sequence | code
sequence | apis
sequence |
---|---|---|---|---|
alexandrebouayad/Cirq | [
"4ba730b17b6af6265ee6458eb40172b847bd5684"
] | [
"examples/examples_test.py"
] | [
"# pylint: disable=wrong-or-nonexistent-copyright-notice\nimport itertools\n\nimport networkx\nimport numpy as np\nimport pytest\nimport matplotlib.pyplot as plt\n\nimport cirq\nimport examples.basic_arithmetic\nimport examples.bb84\nimport examples.bell_inequality\nimport examples.bernstein_vazirani\nimport examples.bcs_mean_field\nimport examples.cross_entropy_benchmarking_example\nimport examples.deutsch\nimport examples.grover\nimport examples.heatmaps\nimport examples.hello_qubit\nimport examples.hhl\nimport examples.hidden_shift_algorithm\nimport examples.noisy_simulation_example\nimport examples.phase_estimator\nimport examples.qaoa\nimport examples.quantum_fourier_transform\nimport examples.quantum_teleportation\nimport examples.qubit_characterizations_example\nimport examples.shor\nimport examples.simon_algorithm\nimport examples.superdense_coding\nimport examples.swap_networks\nfrom examples.shors_code import OneQubitShorsCode\n\n\ndef test_example_runs_bernstein_vazirani():\n examples.bernstein_vazirani.main(qubit_count=3)\n\n # Check empty oracle case. Cover both biases.\n a = cirq.NamedQubit('a')\n assert list(examples.bernstein_vazirani.make_oracle([], a, [], False)) == []\n assert list(examples.bernstein_vazirani.make_oracle([], a, [], True)) == [cirq.X(a)]\n\n\ndef test_example_runs_simon():\n examples.simon_algorithm.main()\n\n\ndef test_example_runs_hidden_shift():\n examples.hidden_shift_algorithm.main()\n\n\ndef test_example_runs_deutsch():\n examples.deutsch.main()\n\n\ndef test_example_runs_hello_qubit():\n examples.hello_qubit.main()\n\n\ndef test_example_runs_bell_inequality():\n examples.bell_inequality.main()\n\n\ndef test_example_runs_bb84():\n examples.bb84.main()\n\n\ndef test_example_runs_quantum_fourier_transform():\n examples.quantum_fourier_transform.main()\n\n\ndef test_example_runs_bcs_mean_field():\n pytest.importorskip(\"cirq_google\")\n examples.bcs_mean_field.main()\n\n\ndef test_example_runs_grover():\n examples.grover.main()\n\n\ndef test_example_runs_basic_arithmetic():\n examples.basic_arithmetic.main(n=2)\n\n\ndef test_example_runs_phase_estimator():\n examples.phase_estimator.main(qnums=(2,), repetitions=2)\n\n\[email protected]('closefigures')\ndef test_example_heatmaps():\n pytest.importorskip(\"cirq_google\")\n plt.switch_backend('agg')\n examples.heatmaps.main()\n\n\ndef test_example_runs_qaoa():\n examples.qaoa.main(repetitions=10, maxiter=5, use_boolean_hamiltonian_gate=False)\n examples.qaoa.main(repetitions=10, maxiter=5, use_boolean_hamiltonian_gate=True)\n\n\ndef test_example_qaoa_same_unitary():\n n = 6\n p = 2\n\n qubits = cirq.LineQubit.range(n)\n\n graph = networkx.random_regular_graph(3, n)\n\n betas = np.random.uniform(-np.pi, np.pi, size=p)\n gammas = np.random.uniform(-np.pi, np.pi, size=p)\n circuits = [\n examples.qaoa.qaoa_max_cut_circuit(\n qubits, betas, gammas, graph, use_boolean_hamiltonian_gate\n )\n for use_boolean_hamiltonian_gate in [True, False]\n ]\n\n assert cirq.allclose_up_to_global_phase(cirq.unitary(circuits[0]), cirq.unitary(circuits[1]))\n\n\ndef test_example_runs_quantum_teleportation():\n _, teleported = examples.quantum_teleportation.main(seed=12)\n assert np.allclose(np.array([0.07023552, -0.9968105, -0.03788921]), teleported)\n\n\ndef test_example_runs_superdense_coding():\n examples.superdense_coding.main()\n\n\ndef test_example_runs_hhl():\n examples.hhl.main()\n\n\[email protected]('closefigures')\ndef test_example_runs_qubit_characterizations():\n examples.qubit_characterizations_example.main(\n minimum_cliffords=2, maximum_cliffords=6, cliffords_step=2\n )\n\n\ndef test_example_swap_networks():\n examples.swap_networks.main()\n\n\[email protected]('closefigures')\ndef test_example_cross_entropy_benchmarking():\n examples.cross_entropy_benchmarking_example.main(\n repetitions=10, num_circuits=2, cycles=[2, 3, 4]\n )\n\n\ndef test_example_noisy_simulation():\n examples.noisy_simulation_example.main()\n\n\ndef test_example_shor_modular_exp_register_size():\n with pytest.raises(ValueError):\n _ = examples.shor.ModularExp(target=[2, 2], exponent=[2, 2, 2], base=4, modulus=5)\n\n\ndef test_example_shor_modular_exp_register_type():\n operation = examples.shor.ModularExp(target=[2, 2, 2], exponent=[2, 2], base=4, modulus=5)\n with pytest.raises(ValueError):\n _ = operation.with_registers([2, 2, 2])\n with pytest.raises(ValueError):\n _ = operation.with_registers(1, [2, 2, 2], 4, 5)\n with pytest.raises(ValueError):\n _ = operation.with_registers([2, 2, 2], [2, 2, 2], [2, 2, 2], 5)\n with pytest.raises(ValueError):\n _ = operation.with_registers([2, 2, 2], [2, 2, 2], 4, [2, 2, 2])\n\n\ndef test_example_shor_modular_exp_registers():\n target = [2, 2, 2]\n exponent = [2, 2]\n operation = examples.shor.ModularExp(target, exponent, 4, 5)\n assert operation.registers() == (target, exponent, 4, 5)\n\n new_target = [2, 2, 2]\n new_exponent = [2, 2, 2, 2]\n new_operation = operation.with_registers(new_target, new_exponent, 6, 7)\n assert new_operation.registers() == (new_target, new_exponent, 6, 7)\n\n\ndef test_example_shor_modular_exp_diagram():\n target = [2, 2, 2]\n exponent = [2, 2]\n gate = examples.shor.ModularExp(target, exponent, 4, 5)\n circuit = cirq.Circuit(gate.on(*cirq.LineQubit.range(5)))\n cirq.testing.assert_has_diagram(\n circuit,\n \"\"\"\n0: โโโModularExp(t*4**e % 5)โโโ\n โ\n1: โโโt1โโโโโโโโโโโโโโโโโโโโโโโ\n โ\n2: โโโt2โโโโโโโโโโโโโโโโโโโโโโโ\n โ\n3: โโโe0โโโโโโโโโโโโโโโโโโโโโโโ\n โ\n4: โโโe1โโโโโโโโโโโโโโโโโโโโโโโ\n\"\"\",\n )\n\n gate = gate.with_registers(target, 2, 4, 5)\n circuit = cirq.Circuit(gate.on(*cirq.LineQubit.range(3)))\n cirq.testing.assert_has_diagram(\n circuit,\n \"\"\"\n0: โโโModularExp(t*4**2 % 5)โโโ\n โ\n1: โโโt1โโโโโโโโโโโโโโโโโโโโโโโ\n โ\n2: โโโt2โโโโโโโโโโโโโโโโโโโโโโโ\n\"\"\",\n )\n\n\ndef assert_order(r: int, x: int, n: int) -> None:\n \"\"\"Assert that r is the order of x modulo n.\"\"\"\n y = x\n for _ in range(1, r):\n assert y % n != 1\n y *= x\n assert y % n == 1\n\n\[email protected](\n 'x, n', ((2, 3), (5, 6), (2, 7), (6, 7), (5, 8), (6, 11), (6, 49), (7, 810))\n)\ndef test_example_shor_naive_order_finder(x, n):\n r = examples.shor.naive_order_finder(x, n)\n assert_order(r, x, n)\n\n\[email protected]('x, n', ((2, 3), (5, 6), (2, 7), (6, 7)))\ndef test_example_shor_quantum_order_finder(x, n):\n r = None\n for _ in range(15):\n r = examples.shor.quantum_order_finder(x, n)\n if r is not None:\n break\n assert_order(r, x, n)\n\n\[email protected]('x, n', ((1, 7), (7, 7)))\ndef test_example_shor_naive_order_finder_invalid_x(x, n):\n with pytest.raises(ValueError):\n _ = examples.shor.naive_order_finder(x, n)\n\n\[email protected]('x, n', ((1, 7), (7, 7)))\ndef test_example_shor_quantum_order_finder_invalid_x(x, n):\n with pytest.raises(ValueError):\n _ = examples.shor.quantum_order_finder(x, n)\n\n\[email protected]('n', (4, 6, 15, 125, 101 * 103, 127 * 127))\ndef test_example_shor_find_factor_with_composite_n_and_naive_order_finder(n):\n d = examples.shor.find_factor(n, examples.shor.naive_order_finder)\n assert 1 < d < n\n assert n % d == 0\n\n\[email protected]('n', (4, 6, 15, 125))\ndef test_example_shor_find_factor_with_composite_n_and_quantum_order_finder(n):\n d = examples.shor.find_factor(n, examples.shor.quantum_order_finder)\n assert 1 < d < n\n assert n % d == 0\n\n\[email protected](\n 'n, order_finder',\n itertools.product(\n (2, 3, 5, 11, 101, 127, 907),\n (examples.shor.naive_order_finder, examples.shor.quantum_order_finder),\n ),\n)\ndef test_example_shor_find_factor_with_prime_n(n, order_finder):\n d = examples.shor.find_factor(n, order_finder)\n assert d is None\n\n\[email protected]('n', (2, 3, 15, 17, 2**89 - 1))\ndef test_example_runs_shor_valid(n):\n examples.shor.main(n=n)\n\n\[email protected]('n', (-1, 0, 1))\ndef test_example_runs_shor_invalid(n):\n with pytest.raises(ValueError):\n examples.shor.main(n=n)\n\n\ndef test_example_qec_single_qubit():\n mycode1 = OneQubitShorsCode()\n my_circuit1 = cirq.Circuit(mycode1.encode())\n my_circuit1 += cirq.Circuit(mycode1.correct())\n my_circuit1 += cirq.measure(mycode1.physical_qubits[0])\n sim1 = cirq.DensityMatrixSimulator()\n result1 = sim1.run(my_circuit1, repetitions=1)\n assert result1.measurements['0'] == [[0]]\n\n mycode2 = OneQubitShorsCode()\n my_circuit2 = cirq.Circuit(mycode2.apply_gate(cirq.X, 0))\n with pytest.raises(IndexError):\n mycode2.apply_gate(cirq.Z, 89)\n my_circuit2 += cirq.Circuit(mycode2.encode())\n my_circuit2 += cirq.Circuit(mycode2.correct())\n my_circuit2 += cirq.measure(mycode2.physical_qubits[0])\n sim2 = cirq.DensityMatrixSimulator()\n result2 = sim2.run(my_circuit2, repetitions=1)\n assert result2.measurements['0'] == [[1]]\n"
] | [
[
"numpy.random.uniform",
"matplotlib.pyplot.switch_backend",
"numpy.array"
]
] |
hyperknot/pgairspace | [
"51f02b54cd12bf4c8c3e7077aaccfaed15c40cfa"
] | [
"pgairspace/geom.py"
] | [
"import os\nimport pyproj\nfrom shapely.geometry import Point, LineString, asShape\nfrom shapely.geometry.polygon import Polygon\nfrom .utils import read_json\n\n\ndef generate_circle(lon, lat, radius_meters):\n points = list()\n for dir in range(0, 360, 15):\n p = offset_point(lon, lat, radius_meters, dir)\n points.append(p)\n return Polygon(points)\n\n\ndef offset_point(p1_lon, p1_lat, distance_meters, direction_degrees=0):\n geod = pyproj.Geod(ellps='WGS84')\n p2_lon, p2_lat, _ = geod.fwd(p1_lon, p1_lat, direction_degrees, distance_meters)\n return p2_lon, p2_lat\n\n\ndef plot_polygon(polygon):\n import matplotlib.pyplot as plt\n\n x, y = polygon.exterior.xy\n plt.plot(x, y)\n plt.show()\n\n\ndef plot_line(line):\n import matplotlib.pyplot as plt\n\n x, y = line.xy\n plt.plot(x, y)\n plt.show()\n\n\ndef convert_dms_to_float(deg, min, sec, sign=1):\n return sign * deg + min / 60. + sec / 3600.\n\n\ndef process_border(point_list, border):\n new_point_list = list()\n for i, section in enumerate(point_list):\n # LineString\n if type(section).__name__ == 'LineString':\n assert i != 0 and i != len(point_list) - 1\n point_start = Point(point_list[i - 1])\n point_end = Point(point_list[i + 1])\n\n line_section = calculate_border_between_points(point_start, point_end, section)\n new_point_list.extend(line_section)\n\n # normal point\n else:\n new_point_list.append(section)\n\n return new_point_list\n\n\ndef calculate_border_between_points(point_a, point_b, border):\n dir_sign = 1\n\n dists = [border.project(p) for p in [point_a, point_b]]\n dists_sorted = sorted(dists)\n points = [border.interpolate(d) for d in dists_sorted]\n\n segment_a, segment_bc = cut_line(points[0], border)\n segment_b, segment_c = cut_line(points[1], segment_bc)\n\n segment_round = LineString(list(segment_c.coords) + list(segment_a.coords))\n\n # selecting shorter segment\n if segment_b.length < segment_round.length:\n selected = segment_b\n else:\n selected = segment_round\n dir_sign *= -1\n\n coords = selected.coords\n\n # cutting start and endpoints\n coords = coords[1:-1]\n\n # swapping direction\n if dists != dists_sorted:\n dir_sign *= -1\n\n if dir_sign == -1:\n coords = coords[::-1]\n\n return coords\n\n\ndef cut_line(cut_point, line, eps_mult=1e2):\n dist = line.project(cut_point)\n point = line.interpolate(dist)\n eps = line.distance(point) * eps_mult\n\n coords = list(line.coords)\n\n if point.coords[0] in coords:\n i = coords.index(point.coords[0])\n\n if i == 0:\n return LineString(), line\n if i == len(coords) - 1:\n return line, LineString()\n\n start_segment = LineString(coords[:i + 1])\n end_segment = LineString(coords[i:])\n\n return start_segment, end_segment\n\n\n for i, p in enumerate(coords[:-1]):\n line_segment = LineString([coords[i], coords[i + 1]])\n line_segment_buffer = line_segment.buffer(eps, resolution=1)\n\n if line_segment_buffer.contains(point):\n start_segment = LineString(coords[:i + 1] + [point])\n end_segment = LineString([point] + coords[i + 1:])\n\n return start_segment, end_segment\n\n raise Exception('point not found in line, consider raising eps_mult')\n\n\ndef load_border(filename):\n border_json = read_json(os.path.join('data', 'borders', filename))\n border = asShape(border_json['geometries'][0]).exterior\n border = border.simplify(0.001)\n\n assert border.coords[0] == border.coords[-1]\n return LineString(border)\n\n\ndef feet_to_meters(feet):\n feet_in_meters = 0.3048\n return int(feet * feet_in_meters)\n\n\ndef fl_to_meters(fl):\n feet_in_meters = 0.3048\n return int(fl * 100 * feet_in_meters)\n\n\n# helper function for debugging\ndef visualize_geometries(_locals, names):\n import os\n import geojson\n from geojson import Feature, FeatureCollection\n from ..utils import write_file_contents, run_cmd\n\n features = [Feature(geometry=_locals[name],\n properties={\n 'name': name,\n 'area': _locals[name].area})\n for name in names\n if _locals[name].area > 0]\n\n fc = FeatureCollection(features)\n\n write_file_contents('tmp.json', geojson.dumps(fc))\n run_cmd('geojsonio tmp.json')\n os.remove('tmp.json')\n\n\ndef sort_geojson(geojson):\n features = geojson['features']\n\n features_sorted = sorted(features,\n key=lambda p: ((p.get('geometry', {}) or {}).get('type', ''),\n p.get('properties', {}).get('title', ''),\n p.get('properties', {}).get('description', '')))\n\n data = {\n 'type': 'FeatureCollection',\n 'features': features_sorted\n }\n\n return data\n"
] | [
[
"matplotlib.pyplot.plot",
"matplotlib.pyplot.show"
]
] |
polyc/compilers-classifier | [
"0d7b56a5196110459c9bbd0b9e358ec4ac269d42"
] | [
"test_bl_set.py"
] | [
"\nimport numpy as np\nimport pandas as pd\nimport random\n\nimport joblib\n\nfrom sklearn.feature_extraction.text import *\n\nprint('Libraries imported.')\n\n\"\"\"#Import Dataset e print it\"\"\"\nfilename = 'train_dataset.jsonl'\ndb = pd.read_json(filename,lines=True)\n#print(db)\n\nfilename='test_dataset_blind.jsonl'\ntest_db = pd.read_json(filename,lines=True)\n\ninstructionExamples_train = []\ncurrentExample = ''\n\n\"\"\"# Extracts mnemonics only\"\"\"\nfor example in db.instructions:\n for instr in example:\n mnemonics=instr.split()[0]\n currentExample += mnemonics + ' '\n instructionExamples_train.append(currentExample)\n currentExample = ''\n\ninstructionExamples_test = []\ncurrentExample = ''\n\n\"\"\"# Extracts mnemonics only\"\"\"\nfor example in test_db.instructions:\n for instr in example:\n mnemonics=instr.split()[0]\n currentExample += mnemonics + ' '\n instructionExamples_test.append(currentExample)\n currentExample = ''\n\n#Print a processed examples\nprint(instructionExamples_train[random.randrange(0,len(instructionExamples_train))])\nprint(instructionExamples_test[random.randrange(0,len(instructionExamples_test))])\n\nn_gram_vectorizer = CountVectorizer(ngram_range=(2, 7))\nn_gram_vectorizer.fit(instructionExamples_train)\nX_test_n_grams = n_gram_vectorizer.transform(instructionExamples_test)\n\n#LOAD BEST MODEL\nbestName = 'compilers[cnb_n_grams].joblib'\nbestModel = joblib.load(bestName)\n\nresults_name = \"blind_set_results[compilers].csv\"\nresults = open(results_name, \"a\")\n\n\"\"\"# Predict on Test set\"\"\"\ny_pred = bestModel.predict(X_test_n_grams)\ndf = pd.DataFrame(y_pred)\ndf.to_csv(path_or_buf = results, index=False)\nresults.close()\n"
] | [
[
"pandas.DataFrame",
"pandas.read_json"
]
] |
zyf668/ml_code | [
"fdd2d6c48550860fd481f7d128d41d95d946539b"
] | [
"number_recognization/num_clf_cnn.py"
] | [
"# -*- coding: utf-8 -*-\r\n\r\nimport tensorflow as tf\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\nimport numpy as np\r\n\r\n\r\n### hyper parameters ###\r\nIMG_X = 28\r\nIMG_Y = 28\r\nINPUT_DIM = IMG_X * IMG_Y\r\nOUTPUT_DIM = 10\r\nLR = 1e-4\r\nMAX_LOOP = 10000\r\nBATCH_SIZE = 50\r\nKEEP_PROB = 0.5\r\n### hyper parameters ###\r\n\r\n# load data\r\nmnist = input_data.read_data_sets('data/MNIST_data', one_hot=True)\r\nX_train = mnist.train.images\r\ny_train = mnist.train.labels\r\nX_test = mnist.test.images\r\ny_test = mnist.test.labels\r\n\r\ndef get_batch_data(X, y, batch_size):\r\n ix = np.random.randint(0, len(X), batch_size)\r\n X_batch = X[ix]\r\n y_batch = y[ix]\r\n return X_batch, y_batch\r\n\r\n# generate weight\r\ndef weight_variable(shape):\r\n initial = tf.truncated_normal(shape, stddev=0.1)\r\n return tf.Variable(initial_value=initial)\r\n\r\n# generate bias\r\ndef bias_variable(shape):\r\n initial = tf.constant(value=0.1, shape=shape)\r\n return tf.Variable(initial_value=initial)\r\n\r\n# convolution layer\r\ndef conv_2d(x, W):\r\n return tf.nn.conv2d(input=x, filter=W, strides=[1,1,1,1], padding='SAME')\r\n\r\n# pooling layer\r\ndef max_pool_2x2(x):\r\n return tf.nn.max_pool(value=x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')\r\n\r\ndef train_model(sess):\r\n sess.run(tf.global_variables_initializer())\r\n for i in range(MAX_LOOP):\r\n X_batch, y_batch = get_batch_data(X_train, y_train, BATCH_SIZE)\r\n sess.run(train_step, feed_dict={xs: X_batch, ys: y_batch, keep_prob: KEEP_PROB})\r\n if i % 100 == 0:\r\n print('ๆญฃๅจ่ฎญ็ป: %5.1f' % (100*float(i)/MAX_LOOP), '%')\r\n print('loss:\\t', sess.run(loss, feed_dict={xs: X_batch, ys: y_batch, keep_prob: 1.0}))\r\n print('train accurary:\\t', sess.run(accuracy, feed_dict={xs: X_batch, ys: y_batch, keep_prob: 1.0}))\r\n\r\n# ---------------------------- main ---------------------------- #\r\n# define placeholder\r\nxs = tf.placeholder(dtype=tf.float32, shape=[None, INPUT_DIM])\r\nys = tf.placeholder(dtype=tf.float32, shape=[None, OUTPUT_DIM])\r\nkeep_prob = tf.placeholder(dtype=tf.float32)\r\nx_img = tf.reshape(xs, shape=[-1, IMG_X, IMG_Y, 1])\r\n\r\n### --- build the convolution neural network --- ###\r\n# conv layer 1\r\nW_conv_1 = weight_variable(shape=[5,5,1,32])\r\nb_conv_1 = bias_variable(shape=[32])\r\nh_conv_1 = tf.nn.relu(conv_2d(x_img, W_conv_1) + b_conv_1) # out [-1,28,28,32]\r\nh_pool_1 = max_pool_2x2(h_conv_1) # out [-1,14,14,32]\r\n\r\n# conv layer 2\r\nW_conv_2 = weight_variable(shape=[5,5,32,64])\r\nb_conv_2 = bias_variable(shape=[64])\r\nh_conv_2 = tf.nn.relu(conv_2d(h_pool_1, W_conv_2) + b_conv_2) # out [-1,14,14,64]\r\nh_pool_2 = max_pool_2x2(h_conv_2) # out [-1,7,7,64]\r\n\r\n# fully-connected layer 1\r\nW_fc_1 = weight_variable(shape=[7*7*64, 1024])\r\nb_fc_1 = bias_variable(shape=[1024])\r\nh_pool_2_flatten = tf.reshape(h_pool_2, shape=[-1, 7*7*64])\r\nh_fc_1 = tf.nn.relu(tf.matmul(h_pool_2_flatten, W_fc_1) + b_fc_1)\r\nh_fc_1_drop = tf.nn.dropout(h_fc_1, keep_prob=keep_prob)\r\n\r\n# fully-connected layer 2 (out layer)\r\nW_fc_2 = weight_variable(shape=[1024, OUTPUT_DIM])\r\nb_fc_2 = bias_variable(shape=[OUTPUT_DIM])\r\nh_fc_2 = tf.nn.softmax(tf.matmul(h_fc_1_drop, W_fc_2) + b_fc_2)\r\ny_pred = h_fc_2\r\n### --- build the convolution neural network --- ###\r\n\r\n# loss & train\r\nloss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=ys, logits=y_pred))\r\ntrain_step = tf.train.AdamOptimizer(LR).minimize(loss)\r\n\r\n# evaluation\r\ncorrect_prediction = tf.equal(tf.argmax(y_pred, 1), tf.argmax(ys, 1))\r\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\r\n\r\nsaver = tf.train.Saver()\r\n\r\n# start session\r\nconfig = tf.ConfigProto()\r\nconfig.gpu_options.allow_growth = True\r\nwith tf.Session(config=config) as sess:\r\n train_model(sess)\r\n \r\n #saver.restore(sess, \"./Model/cnn_model.ckpt\")\r\n #saver.save(sess, 'Model/cnn_model.ckpt')\r\n \r\n import img_proc\r\n for num in range(10):\r\n #filename = 'test_data/0_28x28.jpg'\r\n filename = 'test_data/' + str(num) + '.jpg'\r\n digit_test = img_proc.getImgAsMatFromFile(filename)\r\n digit_test = digit_test.reshape((-1))\r\n pred = sess.run(y_pred, feed_dict={xs: digit_test[np.newaxis, :], keep_prob: 1.0})\r\n print('----------', num, '----------')\r\n print('predict:\\t', pred)\r\n print('predict_number:\\t', np.argmax(pred, 1))\r\n\r\nprint('\\n--- DONE! ---')\r\n\r\nimport os\r\nos.system('pause')\r\n"
] | [
[
"tensorflow.nn.softmax_cross_entropy_with_logits",
"tensorflow.reshape",
"tensorflow.matmul",
"tensorflow.Variable",
"tensorflow.nn.dropout",
"tensorflow.nn.max_pool",
"tensorflow.global_variables_initializer",
"tensorflow.constant",
"numpy.argmax",
"tensorflow.cast",
"tensorflow.train.Saver",
"tensorflow.Session",
"tensorflow.ConfigProto",
"tensorflow.placeholder",
"tensorflow.truncated_normal",
"tensorflow.train.AdamOptimizer",
"tensorflow.examples.tutorials.mnist.input_data.read_data_sets",
"tensorflow.nn.conv2d",
"tensorflow.argmax"
]
] |
Sanjay8874/pandas | [
"a2e599499667b256bc5b8b13a75f0601eccfd432",
"a2e599499667b256bc5b8b13a75f0601eccfd432",
"a2e599499667b256bc5b8b13a75f0601eccfd432"
] | [
"asv_bench/benchmarks/index_object.py",
"pandas/tests/indexes/multi/test_reindex.py",
"pandas/tests/io/parser/test_read_fwf.py"
] | [
"import numpy as np\nimport pandas.util.testing as tm\nfrom pandas import (Series, date_range, DatetimeIndex, Index, RangeIndex,\n Float64Index)\n\n\nclass SetOperations(object):\n\n params = (['datetime', 'date_string', 'int', 'strings'],\n ['intersection', 'union', 'symmetric_difference'])\n param_names = ['dtype', 'method']\n\n def setup(self, dtype, method):\n N = 10**5\n dates_left = date_range('1/1/2000', periods=N, freq='T')\n fmt = '%Y-%m-%d %H:%M:%S'\n date_str_left = Index(dates_left.strftime(fmt))\n int_left = Index(np.arange(N))\n str_left = tm.makeStringIndex(N)\n data = {'datetime': {'left': dates_left, 'right': dates_left[:-1]},\n 'date_string': {'left': date_str_left,\n 'right': date_str_left[:-1]},\n 'int': {'left': int_left, 'right': int_left[:-1]},\n 'strings': {'left': str_left, 'right': str_left[:-1]}}\n self.left = data[dtype]['left']\n self.right = data[dtype]['right']\n\n def time_operation(self, dtype, method):\n getattr(self.left, method)(self.right)\n\n\nclass SetDisjoint(object):\n\n def setup(self):\n N = 10**5\n B = N + 20000\n self.datetime_left = DatetimeIndex(range(N))\n self.datetime_right = DatetimeIndex(range(N, B))\n\n def time_datetime_difference_disjoint(self):\n self.datetime_left.difference(self.datetime_right)\n\n\nclass Datetime(object):\n\n def setup(self):\n self.dr = date_range('20000101', freq='D', periods=10000)\n\n def time_is_dates_only(self):\n self.dr._is_dates_only\n\n\nclass Ops(object):\n\n sample_time = 0.2\n params = ['float', 'int']\n param_names = ['dtype']\n\n def setup(self, dtype):\n N = 10**6\n indexes = {'int': 'makeIntIndex', 'float': 'makeFloatIndex'}\n self.index = getattr(tm, indexes[dtype])(N)\n\n def time_add(self, dtype):\n self.index + 2\n\n def time_subtract(self, dtype):\n self.index - 2\n\n def time_multiply(self, dtype):\n self.index * 2\n\n def time_divide(self, dtype):\n self.index / 2\n\n def time_modulo(self, dtype):\n self.index % 2\n\n\nclass Range(object):\n\n def setup(self):\n self.idx_inc = RangeIndex(start=0, stop=10**7, step=3)\n self.idx_dec = RangeIndex(start=10**7, stop=-1, step=-3)\n\n def time_max(self):\n self.idx_inc.max()\n\n def time_max_trivial(self):\n self.idx_dec.max()\n\n def time_min(self):\n self.idx_dec.min()\n\n def time_min_trivial(self):\n self.idx_inc.min()\n\n\nclass IndexAppend(object):\n\n def setup(self):\n\n N = 10000\n self.range_idx = RangeIndex(0, 100)\n self.int_idx = self.range_idx.astype(int)\n self.obj_idx = self.int_idx.astype(str)\n self.range_idxs = []\n self.int_idxs = []\n self.object_idxs = []\n for i in range(1, N):\n r_idx = RangeIndex(i * 100, (i + 1) * 100)\n self.range_idxs.append(r_idx)\n i_idx = r_idx.astype(int)\n self.int_idxs.append(i_idx)\n o_idx = i_idx.astype(str)\n self.object_idxs.append(o_idx)\n\n def time_append_range_list(self):\n self.range_idx.append(self.range_idxs)\n\n def time_append_int_list(self):\n self.int_idx.append(self.int_idxs)\n\n def time_append_obj_list(self):\n self.obj_idx.append(self.object_idxs)\n\n\nclass Indexing(object):\n\n params = ['String', 'Float', 'Int']\n param_names = ['dtype']\n\n def setup(self, dtype):\n N = 10**6\n self.idx = getattr(tm, 'make{}Index'.format(dtype))(N)\n self.array_mask = (np.arange(N) % 3) == 0\n self.series_mask = Series(self.array_mask)\n self.sorted = self.idx.sort_values()\n half = N // 2\n self.non_unique = self.idx[:half].append(self.idx[:half])\n self.non_unique_sorted = self.sorted[:half].append(self.sorted[:half])\n self.key = self.sorted[N // 4]\n\n def time_boolean_array(self, dtype):\n self.idx[self.array_mask]\n\n def time_boolean_series(self, dtype):\n self.idx[self.series_mask]\n\n def time_get(self, dtype):\n self.idx[1]\n\n def time_slice(self, dtype):\n self.idx[:-1]\n\n def time_slice_step(self, dtype):\n self.idx[::2]\n\n def time_get_loc(self, dtype):\n self.idx.get_loc(self.key)\n\n def time_get_loc_sorted(self, dtype):\n self.sorted.get_loc(self.key)\n\n def time_get_loc_non_unique(self, dtype):\n self.non_unique.get_loc(self.key)\n\n def time_get_loc_non_unique_sorted(self, dtype):\n self.non_unique_sorted.get_loc(self.key)\n\n\nclass Float64IndexMethod(object):\n # GH 13166\n def setup(self):\n N = 100000\n a = np.arange(N)\n self.ind = Float64Index(a * 4.8000000418824129e-08)\n\n def time_get_loc(self):\n self.ind.get_loc(0)\n\n\nfrom .pandas_vb_common import setup # noqa: F401\n",
"# -*- coding: utf-8 -*-\n\n\nimport numpy as np\n\nimport pandas as pd\nimport pandas.util.testing as tm\nfrom pandas import Index, MultiIndex\n\n\ndef check_level_names(index, names):\n assert [level.name for level in index.levels] == list(names)\n\n\ndef test_reindex(idx):\n result, indexer = idx.reindex(list(idx[:4]))\n assert isinstance(result, MultiIndex)\n check_level_names(result, idx[:4].names)\n\n result, indexer = idx.reindex(list(idx))\n assert isinstance(result, MultiIndex)\n assert indexer is None\n check_level_names(result, idx.names)\n\n\ndef test_reindex_level(idx):\n index = Index(['one'])\n\n target, indexer = idx.reindex(index, level='second')\n target2, indexer2 = index.reindex(idx, level='second')\n\n exp_index = idx.join(index, level='second', how='right')\n exp_index2 = idx.join(index, level='second', how='left')\n\n assert target.equals(exp_index)\n exp_indexer = np.array([0, 2, 4])\n tm.assert_numpy_array_equal(indexer, exp_indexer, check_dtype=False)\n\n assert target2.equals(exp_index2)\n exp_indexer2 = np.array([0, -1, 0, -1, 0, -1])\n tm.assert_numpy_array_equal(indexer2, exp_indexer2, check_dtype=False)\n\n tm.assert_raises_regex(TypeError, \"Fill method not supported\",\n idx.reindex, idx,\n method='pad', level='second')\n\n tm.assert_raises_regex(TypeError, \"Fill method not supported\",\n index.reindex, index, method='bfill',\n level='first')\n\n\ndef test_reindex_preserves_names_when_target_is_list_or_ndarray(idx):\n # GH6552\n idx = idx.copy()\n target = idx.copy()\n idx.names = target.names = [None, None]\n\n other_dtype = pd.MultiIndex.from_product([[1, 2], [3, 4]])\n\n # list & ndarray cases\n assert idx.reindex([])[0].names == [None, None]\n assert idx.reindex(np.array([]))[0].names == [None, None]\n assert idx.reindex(target.tolist())[0].names == [None, None]\n assert idx.reindex(target.values)[0].names == [None, None]\n assert idx.reindex(other_dtype.tolist())[0].names == [None, None]\n assert idx.reindex(other_dtype.values)[0].names == [None, None]\n\n idx.names = ['foo', 'bar']\n assert idx.reindex([])[0].names == ['foo', 'bar']\n assert idx.reindex(np.array([]))[0].names == ['foo', 'bar']\n assert idx.reindex(target.tolist())[0].names == ['foo', 'bar']\n assert idx.reindex(target.values)[0].names == ['foo', 'bar']\n assert idx.reindex(other_dtype.tolist())[0].names == ['foo', 'bar']\n assert idx.reindex(other_dtype.values)[0].names == ['foo', 'bar']\n\n\ndef test_reindex_lvl_preserves_names_when_target_is_list_or_array():\n # GH7774\n idx = pd.MultiIndex.from_product([[0, 1], ['a', 'b']],\n names=['foo', 'bar'])\n assert idx.reindex([], level=0)[0].names == ['foo', 'bar']\n assert idx.reindex([], level=1)[0].names == ['foo', 'bar']\n\n\ndef test_reindex_lvl_preserves_type_if_target_is_empty_list_or_array():\n # GH7774\n idx = pd.MultiIndex.from_product([[0, 1], ['a', 'b']])\n assert idx.reindex([], level=0)[0].levels[0].dtype.type == np.int64\n assert idx.reindex([], level=1)[0].levels[1].dtype.type == np.object_\n\n\ndef test_reindex_base(idx):\n idx = idx\n expected = np.arange(idx.size, dtype=np.intp)\n\n actual = idx.get_indexer(idx)\n tm.assert_numpy_array_equal(expected, actual)\n\n with tm.assert_raises_regex(ValueError, 'Invalid fill method'):\n idx.get_indexer(idx, method='invalid')\n\n\ndef test_reindex_non_unique():\n idx = pd.MultiIndex.from_tuples([(0, 0), (1, 1), (1, 1), (2, 2)])\n a = pd.Series(np.arange(4), index=idx)\n new_idx = pd.MultiIndex.from_tuples([(0, 0), (1, 1), (2, 2)])\n with tm.assert_raises_regex(ValueError,\n 'cannot handle a non-unique multi-index!'):\n a.reindex(new_idx)\n",
"# -*- coding: utf-8 -*-\n\n\"\"\"\nTests the 'read_fwf' function in parsers.py. This\ntest suite is independent of the others because the\nengine is set to 'python-fwf' internally.\n\"\"\"\n\nfrom datetime import datetime\n\nimport numpy as np\nimport pytest\n\nimport pandas.compat as compat\nfrom pandas.compat import BytesIO, StringIO\n\nimport pandas as pd\nfrom pandas import DataFrame\nimport pandas.util.testing as tm\n\nfrom pandas.io.parsers import EmptyDataError, read_csv, read_fwf\n\n\nclass TestFwfParsing(object):\n\n def test_fwf(self):\n data_expected = \"\"\"\\\n2011,58,360.242940,149.910199,11950.7\n2011,59,444.953632,166.985655,11788.4\n2011,60,364.136849,183.628767,11806.2\n2011,61,413.836124,184.375703,11916.8\n2011,62,502.953953,173.237159,12468.3\n\"\"\"\n expected = read_csv(StringIO(data_expected),\n engine='python', header=None)\n\n data1 = \"\"\"\\\n201158 360.242940 149.910199 11950.7\n201159 444.953632 166.985655 11788.4\n201160 364.136849 183.628767 11806.2\n201161 413.836124 184.375703 11916.8\n201162 502.953953 173.237159 12468.3\n\"\"\"\n colspecs = [(0, 4), (4, 8), (8, 20), (21, 33), (34, 43)]\n df = read_fwf(StringIO(data1), colspecs=colspecs, header=None)\n tm.assert_frame_equal(df, expected)\n\n data2 = \"\"\"\\\n2011 58 360.242940 149.910199 11950.7\n2011 59 444.953632 166.985655 11788.4\n2011 60 364.136849 183.628767 11806.2\n2011 61 413.836124 184.375703 11916.8\n2011 62 502.953953 173.237159 12468.3\n\"\"\"\n df = read_fwf(StringIO(data2), widths=[5, 5, 13, 13, 7], header=None)\n tm.assert_frame_equal(df, expected)\n\n # From Thomas Kluyver: apparently some non-space filler characters can\n # be seen, this is supported by specifying the 'delimiter' character:\n # http://publib.boulder.ibm.com/infocenter/dmndhelp/v6r1mx/index.jsp?topic=/com.ibm.wbit.612.help.config.doc/topics/rfixwidth.html\n data3 = \"\"\"\\\n201158~~~~360.242940~~~149.910199~~~11950.7\n201159~~~~444.953632~~~166.985655~~~11788.4\n201160~~~~364.136849~~~183.628767~~~11806.2\n201161~~~~413.836124~~~184.375703~~~11916.8\n201162~~~~502.953953~~~173.237159~~~12468.3\n\"\"\"\n df = read_fwf(\n StringIO(data3), colspecs=colspecs, delimiter='~', header=None)\n tm.assert_frame_equal(df, expected)\n\n with tm.assert_raises_regex(ValueError,\n \"must specify only one of\"):\n read_fwf(StringIO(data3), colspecs=colspecs, widths=[6, 10, 10, 7])\n\n with tm.assert_raises_regex(ValueError, \"Must specify either\"):\n read_fwf(StringIO(data3), colspecs=None, widths=None)\n\n def test_BytesIO_input(self):\n if not compat.PY3:\n pytest.skip(\n \"Bytes-related test - only needs to work on Python 3\")\n\n result = read_fwf(BytesIO(\"ืฉืืื\\nืฉืืื\".encode('utf8')), widths=[\n 2, 2], encoding='utf8')\n expected = DataFrame([[\"ืฉื\", \"ืื\"]], columns=[\"ืฉื\", \"ืื\"])\n tm.assert_frame_equal(result, expected)\n\n def test_fwf_colspecs_is_list_or_tuple(self):\n data = \"\"\"index,A,B,C,D\nfoo,2,3,4,5\nbar,7,8,9,10\nbaz,12,13,14,15\nqux,12,13,14,15\nfoo2,12,13,14,15\nbar2,12,13,14,15\n\"\"\"\n\n with tm.assert_raises_regex(TypeError,\n 'column specifications must '\n 'be a list or tuple.+'):\n pd.io.parsers.FixedWidthReader(StringIO(data),\n {'a': 1}, ',', '#')\n\n def test_fwf_colspecs_is_list_or_tuple_of_two_element_tuples(self):\n data = \"\"\"index,A,B,C,D\nfoo,2,3,4,5\nbar,7,8,9,10\nbaz,12,13,14,15\nqux,12,13,14,15\nfoo2,12,13,14,15\nbar2,12,13,14,15\n\"\"\"\n\n with tm.assert_raises_regex(TypeError,\n 'Each column specification '\n 'must be.+'):\n read_fwf(StringIO(data), [('a', 1)])\n\n def test_fwf_colspecs_None(self):\n # GH 7079\n data = \"\"\"\\\n123456\n456789\n\"\"\"\n colspecs = [(0, 3), (3, None)]\n result = read_fwf(StringIO(data), colspecs=colspecs, header=None)\n expected = DataFrame([[123, 456], [456, 789]])\n tm.assert_frame_equal(result, expected)\n\n colspecs = [(None, 3), (3, 6)]\n result = read_fwf(StringIO(data), colspecs=colspecs, header=None)\n expected = DataFrame([[123, 456], [456, 789]])\n tm.assert_frame_equal(result, expected)\n\n colspecs = [(0, None), (3, None)]\n result = read_fwf(StringIO(data), colspecs=colspecs, header=None)\n expected = DataFrame([[123456, 456], [456789, 789]])\n tm.assert_frame_equal(result, expected)\n\n colspecs = [(None, None), (3, 6)]\n result = read_fwf(StringIO(data), colspecs=colspecs, header=None)\n expected = DataFrame([[123456, 456], [456789, 789]])\n tm.assert_frame_equal(result, expected)\n\n def test_fwf_regression(self):\n # GH 3594\n # turns out 'T060' is parsable as a datetime slice!\n\n tzlist = [1, 10, 20, 30, 60, 80, 100]\n ntz = len(tzlist)\n tcolspecs = [16] + [8] * ntz\n tcolnames = ['SST'] + [\"T%03d\" % z for z in tzlist[1:]]\n data = \"\"\" 2009164202000 9.5403 9.4105 8.6571 7.8372 6.0612 5.8843 5.5192\n 2009164203000 9.5435 9.2010 8.6167 7.8176 6.0804 5.8728 5.4869\n 2009164204000 9.5873 9.1326 8.4694 7.5889 6.0422 5.8526 5.4657\n 2009164205000 9.5810 9.0896 8.4009 7.4652 6.0322 5.8189 5.4379\n 2009164210000 9.6034 9.0897 8.3822 7.4905 6.0908 5.7904 5.4039\n\"\"\"\n\n df = read_fwf(StringIO(data),\n index_col=0,\n header=None,\n names=tcolnames,\n widths=tcolspecs,\n parse_dates=True,\n date_parser=lambda s: datetime.strptime(s, '%Y%j%H%M%S'))\n\n for c in df.columns:\n res = df.loc[:, c]\n assert len(res)\n\n def test_fwf_for_uint8(self):\n data = \"\"\"1421302965.213420 PRI=3 PGN=0xef00 DST=0x17 SRC=0x28 04 154 00 00 00 00 00 127\n1421302964.226776 PRI=6 PGN=0xf002 SRC=0x47 243 00 00 255 247 00 00 71\"\"\" # noqa\n df = read_fwf(StringIO(data),\n colspecs=[(0, 17), (25, 26), (33, 37),\n (49, 51), (58, 62), (63, 1000)],\n names=['time', 'pri', 'pgn', 'dst', 'src', 'data'],\n converters={\n 'pgn': lambda x: int(x, 16),\n 'src': lambda x: int(x, 16),\n 'dst': lambda x: int(x, 16),\n 'data': lambda x: len(x.split(' '))})\n\n expected = DataFrame([[1421302965.213420, 3, 61184, 23, 40, 8],\n [1421302964.226776, 6, 61442, None, 71, 8]],\n columns=[\"time\", \"pri\", \"pgn\",\n \"dst\", \"src\", \"data\"])\n expected[\"dst\"] = expected[\"dst\"].astype(object)\n\n tm.assert_frame_equal(df, expected)\n\n def test_fwf_compression(self):\n try:\n import gzip\n import bz2\n except ImportError:\n pytest.skip(\"Need gzip and bz2 to run this test\")\n\n data = \"\"\"1111111111\n 2222222222\n 3333333333\"\"\".strip()\n widths = [5, 5]\n names = ['one', 'two']\n expected = read_fwf(StringIO(data), widths=widths, names=names)\n if compat.PY3:\n data = bytes(data, encoding='utf-8')\n comps = [('gzip', gzip.GzipFile), ('bz2', bz2.BZ2File)]\n for comp_name, compresser in comps:\n with tm.ensure_clean() as path:\n tmp = compresser(path, mode='wb')\n tmp.write(data)\n tmp.close()\n result = read_fwf(path, widths=widths, names=names,\n compression=comp_name)\n tm.assert_frame_equal(result, expected)\n\n def test_comment_fwf(self):\n data = \"\"\"\n 1 2. 4 #hello world\n 5 NaN 10.0\n\"\"\"\n expected = np.array([[1, 2., 4],\n [5, np.nan, 10.]])\n df = read_fwf(StringIO(data), colspecs=[(0, 3), (4, 9), (9, 25)],\n comment='#')\n tm.assert_almost_equal(df.values, expected)\n\n def test_1000_fwf(self):\n data = \"\"\"\n 1 2,334.0 5\n10 13 10.\n\"\"\"\n expected = np.array([[1, 2334., 5],\n [10, 13, 10]])\n df = read_fwf(StringIO(data), colspecs=[(0, 3), (3, 11), (12, 16)],\n thousands=',')\n tm.assert_almost_equal(df.values, expected)\n\n def test_bool_header_arg(self):\n # see gh-6114\n data = \"\"\"\\\nMyColumn\n a\n b\n a\n b\"\"\"\n for arg in [True, False]:\n with pytest.raises(TypeError):\n read_fwf(StringIO(data), header=arg)\n\n def test_full_file(self):\n # File with all values\n test = \"\"\"index A B C\n2000-01-03T00:00:00 0.980268513777 3 foo\n2000-01-04T00:00:00 1.04791624281 -4 bar\n2000-01-05T00:00:00 0.498580885705 73 baz\n2000-01-06T00:00:00 1.12020151869 1 foo\n2000-01-07T00:00:00 0.487094399463 0 bar\n2000-01-10T00:00:00 0.836648671666 2 baz\n2000-01-11T00:00:00 0.157160753327 34 foo\"\"\"\n colspecs = ((0, 19), (21, 35), (38, 40), (42, 45))\n expected = read_fwf(StringIO(test), colspecs=colspecs)\n tm.assert_frame_equal(expected, read_fwf(StringIO(test)))\n\n def test_full_file_with_missing(self):\n # File with missing values\n test = \"\"\"index A B C\n2000-01-03T00:00:00 0.980268513777 3 foo\n2000-01-04T00:00:00 1.04791624281 -4 bar\n 0.498580885705 73 baz\n2000-01-06T00:00:00 1.12020151869 1 foo\n2000-01-07T00:00:00 0 bar\n2000-01-10T00:00:00 0.836648671666 2 baz\n 34\"\"\"\n colspecs = ((0, 19), (21, 35), (38, 40), (42, 45))\n expected = read_fwf(StringIO(test), colspecs=colspecs)\n tm.assert_frame_equal(expected, read_fwf(StringIO(test)))\n\n def test_full_file_with_spaces(self):\n # File with spaces in columns\n test = \"\"\"\nAccount Name Balance CreditLimit AccountCreated\n101 Keanu Reeves 9315.45 10000.00 1/17/1998\n312 Gerard Butler 90.00 1000.00 8/6/2003\n868 Jennifer Love Hewitt 0 17000.00 5/25/1985\n761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006\n317 Bill Murray 789.65 5000.00 2/5/2007\n\"\"\".strip('\\r\\n')\n colspecs = ((0, 7), (8, 28), (30, 38), (42, 53), (56, 70))\n expected = read_fwf(StringIO(test), colspecs=colspecs)\n tm.assert_frame_equal(expected, read_fwf(StringIO(test)))\n\n def test_full_file_with_spaces_and_missing(self):\n # File with spaces and missing values in columns\n test = \"\"\"\nAccount Name Balance CreditLimit AccountCreated\n101 10000.00 1/17/1998\n312 Gerard Butler 90.00 1000.00 8/6/2003\n868 5/25/1985\n761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006\n317 Bill Murray 789.65\n\"\"\".strip('\\r\\n')\n colspecs = ((0, 7), (8, 28), (30, 38), (42, 53), (56, 70))\n expected = read_fwf(StringIO(test), colspecs=colspecs)\n tm.assert_frame_equal(expected, read_fwf(StringIO(test)))\n\n def test_messed_up_data(self):\n # Completely messed up file\n test = \"\"\"\n Account Name Balance Credit Limit Account Created\n 101 10000.00 1/17/1998\n 312 Gerard Butler 90.00 1000.00\n\n 761 Jada Pinkett-Smith 49654.87 100000.00 12/5/2006\n 317 Bill Murray 789.65\n\"\"\".strip('\\r\\n')\n colspecs = ((2, 10), (15, 33), (37, 45), (49, 61), (64, 79))\n expected = read_fwf(StringIO(test), colspecs=colspecs)\n tm.assert_frame_equal(expected, read_fwf(StringIO(test)))\n\n def test_multiple_delimiters(self):\n test = r\"\"\"\ncol1~~~~~col2 col3++++++++++++++++++col4\n~~22.....11.0+++foo~~~~~~~~~~Keanu Reeves\n 33+++122.33\\\\\\bar.........Gerard Butler\n++44~~~~12.01 baz~~Jennifer Love Hewitt\n~~55 11+++foo++++Jada Pinkett-Smith\n..66++++++.03~~~bar Bill Murray\n\"\"\".strip('\\r\\n')\n colspecs = ((0, 4), (7, 13), (15, 19), (21, 41))\n expected = read_fwf(StringIO(test), colspecs=colspecs,\n delimiter=' +~.\\\\')\n tm.assert_frame_equal(expected, read_fwf(StringIO(test),\n delimiter=' +~.\\\\'))\n\n def test_variable_width_unicode(self):\n if not compat.PY3:\n pytest.skip(\n 'Bytes-related test - only needs to work on Python 3')\n test = \"\"\"\nืฉืืื ืฉืืื\nืื ืฉืื\nืฉื ืื\n\"\"\".strip('\\r\\n')\n expected = read_fwf(BytesIO(test.encode('utf8')),\n colspecs=[(0, 4), (5, 9)],\n header=None, encoding='utf8')\n tm.assert_frame_equal(expected, read_fwf(\n BytesIO(test.encode('utf8')), header=None, encoding='utf8'))\n\n def test_dtype(self):\n data = \"\"\" a b c\n1 2 3.2\n3 4 5.2\n\"\"\"\n colspecs = [(0, 5), (5, 10), (10, None)]\n result = pd.read_fwf(StringIO(data), colspecs=colspecs)\n expected = pd.DataFrame({\n 'a': [1, 3],\n 'b': [2, 4],\n 'c': [3.2, 5.2]}, columns=['a', 'b', 'c'])\n tm.assert_frame_equal(result, expected)\n\n expected['a'] = expected['a'].astype('float64')\n expected['b'] = expected['b'].astype(str)\n expected['c'] = expected['c'].astype('int32')\n result = pd.read_fwf(StringIO(data), colspecs=colspecs,\n dtype={'a': 'float64', 'b': str, 'c': 'int32'})\n tm.assert_frame_equal(result, expected)\n\n def test_skiprows_inference(self):\n # GH11256\n test = \"\"\"\nText contained in the file header\n\nDataCol1 DataCol2\n 0.0 1.0\n 101.6 956.1\n\"\"\".strip()\n expected = read_csv(StringIO(test), skiprows=2,\n delim_whitespace=True)\n tm.assert_frame_equal(expected, read_fwf(\n StringIO(test), skiprows=2))\n\n def test_skiprows_by_index_inference(self):\n test = \"\"\"\nTo be skipped\nNot To Be Skipped\nOnce more to be skipped\n123 34 8 123\n456 78 9 456\n\"\"\".strip()\n\n expected = read_csv(StringIO(test), skiprows=[0, 2],\n delim_whitespace=True)\n tm.assert_frame_equal(expected, read_fwf(\n StringIO(test), skiprows=[0, 2]))\n\n def test_skiprows_inference_empty(self):\n test = \"\"\"\nAA BBB C\n12 345 6\n78 901 2\n\"\"\".strip()\n\n with pytest.raises(EmptyDataError):\n read_fwf(StringIO(test), skiprows=3)\n\n def test_whitespace_preservation(self):\n # Addresses Issue #16772\n data_expected = \"\"\"\n a ,bbb\n cc,dd \"\"\"\n expected = read_csv(StringIO(data_expected), header=None)\n\n test_data = \"\"\"\n a bbb\n ccdd \"\"\"\n result = read_fwf(StringIO(test_data), widths=[3, 3],\n header=None, skiprows=[0], delimiter=\"\\n\\t\")\n\n tm.assert_frame_equal(result, expected)\n\n def test_default_delimiter(self):\n data_expected = \"\"\"\na,bbb\ncc,dd\"\"\"\n expected = read_csv(StringIO(data_expected), header=None)\n\n test_data = \"\"\"\na \\tbbb\ncc\\tdd \"\"\"\n result = read_fwf(StringIO(test_data), widths=[3, 3],\n header=None, skiprows=[0])\n\n tm.assert_frame_equal(result, expected)\n"
] | [
[
"pandas.Series",
"pandas.date_range",
"pandas.Float64Index",
"numpy.arange",
"pandas.RangeIndex",
"pandas.util.testing.makeStringIndex"
],
[
"pandas.util.testing.assert_raises_regex",
"pandas.util.testing.assert_numpy_array_equal",
"pandas.MultiIndex.from_product",
"numpy.arange",
"pandas.MultiIndex.from_tuples",
"numpy.array",
"pandas.Index"
],
[
"pandas.util.testing.ensure_clean",
"pandas.util.testing.assert_raises_regex",
"pandas.DataFrame",
"pandas.compat.StringIO",
"pandas.util.testing.assert_almost_equal",
"numpy.array",
"pandas.util.testing.assert_frame_equal",
"pandas.io.parsers.read_fwf"
]
] |
mayank0926/pidnn-double-pendulum | [
"e6f77ffc22ca4ff31dfd6a327e5fec0b61df17a0"
] | [
"dp_driver.py"
] | [
"import torch\nimport yaml\nimport numpy as np\nimport pandas as pd\nimport os\nimport sys\nfrom dp_datagen import double_pendulum_data\nfrom dp_pidnn import pidnn_driver\nfrom dp_dataloader import testloader\nfrom dp_ff import ff_driver\n\nif len(sys.argv) > 2:\n config_filename = sys.argv[2]\nelse:\n config_filename = \"dp_config.yaml\"\n\nwith open(config_filename, \"r\") as f:\n all_configs = yaml.safe_load(f)\n common_config = all_configs['COMMON'].copy()\n # Filling in models from model templates\n for instance in common_config['MODEL_CONFIGS']:\n template_name = instance[:instance.rfind('_')]\n training_points = int(instance[(instance.rfind('_')+1):])\n template_config = all_configs[template_name].copy()\n template_config['num_datadriven'] = training_points\n # if template_config['num_collocation'] == -1: template_config['num_collocation'] = 10 * training_points\n template_config['model_name'] = template_name.lower() + '_' + str(training_points)\n all_configs[template_name + '_' + str(training_points)] = template_config\n\ndef generate_folders():\n datadir = './Data'\n for filename in common_config['DATA_CONFIGS']:\n path = os.path.join(datadir, filename.lower())\n try:\n os.makedirs(path, exist_ok = True)\n print(\"Successfully created '%s'\" % (datadir+'/'+filename.lower()))\n except OSError as error:\n print(\"'%s' can not be created\" % (datadir+'/'+filename.lower()))\n modeldir = './Models'\n for seed in common_config['SEEDS']:\n seeddir = f'SEED_{seed}'\n for noise in common_config['NOISE_CONFIGS']:\n noisedir = f'Noise_{int(100*noise)}'\n for filename in common_config['DATA_CONFIGS']:\n path = os.path.join(modeldir, seeddir + '/' + noisedir + '/' + filename.lower())\n try:\n os.makedirs(path, exist_ok = True)\n print(\"Successfully created '%s'\" % (modeldir + '/' + seeddir + '/' + noisedir + '/' + filename.lower()))\n for modelname in common_config['ALL_MODEL_CONFIGS']:\n modelpath = os.path.join(path, modelname.lower())\n os.makedirs(modelpath, exist_ok = True)\n print(\"Successfully created '%s'\" % (path + '/' + modelname.lower()))\n except OSError as error:\n print(\"'%s' can not be created\" % (modeldir + '/' + noisedir + '/' + filename.lower()))\n print('Successfully created all directories!')\n\ndef generate_all_datasets():\n for active_data_config_name in common_config['DATA_CONFIGS']:\n active_data_config = all_configs[active_data_config_name].copy()\n active_data_config.update(common_config)\n config = active_data_config\n\n config['datafile'] = config['TRAINFILE']\n config['theta_range'] = np.linspace(config['TRAIN_THETA_START']*np.pi/180.0, config['TRAIN_THETA_END']*np.pi/180.0, num = config['TRAIN_THETA_VALUES'], dtype=np.float32)\n config['t_range'] = np.arange(start=0.0, stop = config['TIMESTEP']*config['TRAIN_ITERATIONS'], step = config['TIMESTEP'])\n\n if config['DATASET_CACHING'] and os.path.isfile(config['datadir']+config['datafile']):\n print('Skipping ' + config['datadir'] + config['datafile'])\n else:\n double_pendulum_data(config)\n \n config['datafile'] = config['TESTFILE']\n new_theta_range = []\n for i in range(len(config['theta_range'])-1):\n new_theta_range.append(np.random.uniform(low=config['theta_range'][i], high=config['theta_range'][i+1], size=(config['TESTSET_MULTIPLIER'],)))\n config['theta_range'] = np.array(new_theta_range).reshape((-1,))\n\n if config['DATASET_CACHING'] and os.path.isfile(config['datadir']+config['datafile']):\n print('Skipping ' + config['datadir'] + config['datafile'])\n else:\n double_pendulum_data(config)\n\n\n# generate_all_datasets()\n \ndef train_all_models():\n for seed in common_config['SEEDS']:\n for noise in common_config['NOISE_CONFIGS']:\n for active_data_config_name in common_config['DATA_CONFIGS']:\n active_data_config = all_configs[active_data_config_name].copy()\n active_data_config.update(common_config)\n\n for active_model_config_name in common_config['MODEL_CONFIGS']:\n if common_config['MODEL_CACHING'] and os.path.isfile(f'./Models/SEED_{seed}/Noise_{int(100*noise)}/{active_data_config_name.lower()}/{active_model_config_name.lower()}.pt'):\n print(f'======================= Skipping ./Models/SEED_{seed}/Noise_{int(100*noise)}/{active_data_config_name.lower()}/{active_model_config_name.lower()}.pt =======================')\n continue\n\n active_model_config = all_configs[active_model_config_name].copy()\n active_model_config.update(active_data_config)\n config = active_model_config\n\n config['datafile'] = config['TRAINFILE']\n config['noise'] = noise\n config['seed'] = seed\n config['modeldir'] = 'Models/' + f'SEED_{seed}/' + f'Noise_{int(100*noise)}/' + active_data_config_name.lower() + '/'\n\n print(f'======================={active_data_config_name}, {active_model_config_name}, Noise {int(100*noise)}%=======================')\n if config['take_differential_points']:\n pidnn_driver(config)\n else:\n ff_driver(config)\n\n# train_all_models()\n\ndef test_all_models():\n dicts_testdata = []\n for noise in common_config['NOISE_CONFIGS']:\n for active_data_config_name in common_config['DATA_CONFIGS']:\n active_data_config = all_configs[active_data_config_name].copy()\n active_data_config.update(common_config)\n\n for active_model_config_name in common_config['MODEL_CONFIGS']:\n active_model_config = all_configs[active_model_config_name].copy()\n active_model_config.update(active_data_config)\n config = active_model_config\n\n seed_results = []\n for seed in common_config['SEEDS']:\n model = torch.load(f'Models/SEED_{seed}/Noise_' + f'{int(100*noise)}/{active_data_config_name.lower()}/' + active_model_config_name.lower() + '.pt')\n model.eval()\n seed_results.append(testloader(config, config['datadir'] + config['TESTFILE'], model).item())\n seed_results = np.array(seed_results)\n\n result = (noise,\n active_data_config_name,\n active_model_config_name,\n np.mean(seed_results),\n np.std(seed_results),\n np.max(seed_results),\n np.min(seed_results),\n np.std(-np.log(seed_results))\n )\n print(result)\n dicts_testdata.append(result)\n \n df_testdata = pd.DataFrame(dicts_testdata,\\\n columns=['NOISE', 'DATASET', 'MODEL', 'ERR_AVG', 'ERR_STD', 'ERR_MAX', 'ERR_MIN', 'LOG_STD'])\n df_testdata.to_csv(f'Inferences/inferences.csv')\n\n# test_all_models()\n\nif __name__==\"__main__\":\n command = sys.argv[1]\n if command == 'folders':\n generate_folders()\n elif command == 'datasets':\n generate_all_datasets()\n elif command == 'train':\n train_all_models()\n elif command == 'test':\n test_all_models()\n else:\n print('Please input valid keyword')\n sys.exit(1)\n \n"
] | [
[
"numpy.random.uniform",
"pandas.DataFrame",
"numpy.arange",
"numpy.max",
"numpy.log",
"numpy.min",
"numpy.array",
"numpy.std",
"numpy.linspace",
"numpy.mean"
]
] |
ShubhamGupta577/Amazing-Python-Scripts | [
"deeb542a77b96fdcfbe21440eee4c620fa06daa9"
] | [
"corona cases forecasting/main.py"
] | [
"# importing libraries\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom statsmodels.tsa.arima_model import ARIMA\r\nimport datetime\r\nfrom datetime import date\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\nplt.style.use('fivethirtyeight')\r\nfrom pmdarima import auto_arima\r\n\r\nconfirmed_cases = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv')\r\ndeaths_reported = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv')\r\nrecovered_cases = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv')\r\nlatest_data = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/07-15-2020.csv')\r\n## attributes\r\n# Fetching all the columns from confirmed dataset\r\ncols = confirmed_cases.keys()\r\n# Extracting the date columns\r\nconfirmed = confirmed_cases.loc[:, cols[4]:cols[-1]]\r\ndeaths = deaths_reported.loc[:, cols[4]:cols[-1]]\r\nrecoveries = recovered_cases.loc[:, cols[4]:cols[-1]]\r\n# Range of date\r\ndates = confirmed.keys()\r\n# Summary\r\nworld_cases = []\r\ntotal_deaths = []\r\nmortality_rate = []\r\nrecovery_rate = []\r\ntotal_recovered = []\r\ntotal_active = []\r\n# Confirmed\r\nindia_cases = []\r\n# Death\r\nindia_deaths = []\r\n# Recovered\r\nindia_recoveries = []\r\n# Fill with the dataset\r\nfor i in dates:\r\n india_cases.append(confirmed_cases[confirmed_cases['Country/Region'] == 'India'][i].sum())\r\n india_deaths.append(deaths_reported[deaths_reported['Country/Region'] == 'India'][i].sum())\r\n india_recoveries.append(recovered_cases[recovered_cases['Country/Region'] == 'India'][i].sum())\r\n\r\ndef daily_increase(data):\r\n d = []\r\n for i in range(len(data)):\r\n if i == 0:\r\n d.append(data[0])\r\n else:\r\n d.append(data[i]-data[i-1])\r\n return d\r\n\r\ndef fresh_cases_daily():\r\n #confirmed cases\r\n india_daily_increase = daily_increase(india_cases)\r\n\r\n # Dates pre processing\r\n days_since_1_22 = np.array([i for i in range(len(dates))]).reshape(-1, 1)\r\n\r\n days_in_future = 0\r\n future_forecast = np.array([i for i in range(len(dates)+days_in_future)]).reshape(-1, 1)\r\n\r\n start = '1/22/2020'\r\n start_date = datetime.datetime.strptime(start, '%m/%d/%Y')\r\n future_forecast_dates = []\r\n for i in range(len(future_forecast)):\r\n future_forecast_dates.append((start_date + datetime.timedelta(days=i)).strftime('%m/%d/%Y'))\r\n\r\n dataCovid= pd.DataFrame({ 'Dates': future_forecast_dates , 'Daily Increase':india_daily_increase })\r\n train = dataCovid[:int(0.7*(len(dataCovid)))]\r\n valid = dataCovid[int(0.7*(len(dataCovid))):]\r\n #preprocessing (since arima takes univariate series as input)\r\n train.drop('Dates',axis=1,inplace=True)\r\n valid.drop('Dates',axis=1,inplace=True)\r\n model = auto_arima(train, trace=True, error_action='ignore', suppress_warnings=True)\r\n model.fit(train)\r\n forecast = model.predict(n_periods=len(valid))\r\n forecast = pd.DataFrame(forecast,index = valid.index,columns=['Prediction'])\r\n\r\n def ARIMAmodel(series, order, days = 21):\r\n # Fitting and forecast the series\r\n train = [x for x in series]\r\n model = ARIMA(train, order = order)\r\n model_fit = model.fit(disp=0)\r\n forecast, err, ci = model_fit.forecast(steps = days, alpha = 0.05)\r\n start_day = date.today() + datetime.timedelta(days = 1)\r\n predictions_df = pd.DataFrame({'Forecast':forecast.round()}, index=pd.date_range(start = start_day, periods=days, freq='D'))\r\n return predictions_df, ci\r\n \r\n new_positives = dataCovid['Daily Increase'].values\r\n order = {\r\n 'new_positives': (2, 1, 5),\r\n }\r\n new_positives_today=new_positives[-1]\r\n # Forecasting with ARIMA models\r\n new_positives_pred, new_positives_ci = ARIMAmodel(new_positives, order['new_positives'])\r\n casesY=[]\r\n datesX=[]\r\n list1 = new_positives_pred.iloc[: ,0]\r\n for i in range(0,21):\r\n casesY.append(list1[i])\r\n datesX.append((date.today()+ datetime.timedelta(days=i)).strftime('%m/%d/%Y'))\r\n\r\n # Plot Results for forecasted dates only (detailed)\r\n plt.plot(datesX,casesY,color='red')\r\n plt.title('New active Cases Forecast')\r\n plt.xticks(rotation=90)\r\n # plt.figure(figsize=(22,22))\r\n plt.savefig(\"./corona cases forecasting/Results/plot1.png\",bbox_inches='tight')\r\n plt.autoscale()\r\n plt.show()\r\n\r\ndef death_cases_daily():\r\n #confirmed cases\r\n india_daily_increase = daily_increase(india_deaths)\r\n\r\n # Dates pre processing\r\n days_since_1_22 = np.array([i for i in range(len(dates))]).reshape(-1, 1)\r\n\r\n days_in_future = 0\r\n future_forecast = np.array([i for i in range(len(dates)+days_in_future)]).reshape(-1, 1)\r\n\r\n start = '1/22/2020'\r\n start_date = datetime.datetime.strptime(start, '%m/%d/%Y')\r\n future_forecast_dates = []\r\n for i in range(len(future_forecast)):\r\n future_forecast_dates.append((start_date + datetime.timedelta(days=i)).strftime('%m/%d/%Y'))\r\n\r\n dataCovid= pd.DataFrame({ 'Dates': future_forecast_dates , 'Daily Increase':india_daily_increase })\r\n train = dataCovid[:int(0.7*(len(dataCovid)))]\r\n valid = dataCovid[int(0.7*(len(dataCovid))):]\r\n #preprocessing (since arima takes univariate series as input)\r\n train.drop('Dates',axis=1,inplace=True)\r\n valid.drop('Dates',axis=1,inplace=True)\r\n model = auto_arima(train, trace=True, error_action='ignore', suppress_warnings=True)\r\n model.fit(train)\r\n forecast = model.predict(n_periods=len(valid))\r\n forecast = pd.DataFrame(forecast,index = valid.index,columns=['Prediction'])\r\n\r\n def ARIMAmodel(series, order, days = 21):\r\n # Fitting and forecast the series\r\n train = [x for x in series]\r\n model = ARIMA(train, order = order)\r\n model_fit = model.fit(disp=0)\r\n forecast, err, ci = model_fit.forecast(steps = days, alpha = 0.05)\r\n start_day = date.today() + datetime.timedelta(days = 1)\r\n predictions_df = pd.DataFrame({'Forecast':forecast.round()}, index=pd.date_range(start = start_day, periods=days, freq='D'))\r\n return predictions_df, ci\r\n\r\n new_deaths = dataCovid['Daily Increase'].values\r\n order = {\r\n 'new_deaths': (0, 1, 1),\r\n }\r\n new_deaths_today=new_deaths[-1]\r\n # Forecasting with ARIMA models\r\n new_deaths_pred, new_deaths_ci = ARIMAmodel(new_deaths, order['new_deaths'])\r\n casesY=[]\r\n datesX=[]\r\n list1 = new_deaths_pred.iloc[: ,0]\r\n for i in range(0,21):\r\n casesY.append(list1[i])\r\n datesX.append((date.today()+ datetime.timedelta(days=i)).strftime('%m/%d/%Y'))\r\n\r\n # Plot Results for forecasted dates only (detailed)\r\n plt.plot(datesX,casesY,color='red')\r\n plt.title('New death Cases Forecast')\r\n plt.xticks(rotation=90)\r\n # plt.figure(figsize=(22,22))\r\n plt.savefig(\"./corona cases forecasting/Results/plot2.png\",bbox_inches='tight')\r\n plt.autoscale()\r\n plt.show()\r\n\r\ndef recovered_cases_daily():\r\n #confirmed cases\r\n india_daily_increase = daily_increase(india_recoveries)\r\n # Dates pre processing\r\n days_since_1_22 = np.array([i for i in range(len(dates))]).reshape(-1, 1)\r\n days_in_future = 0\r\n future_forecast = np.array([i for i in range(len(dates)+days_in_future)]).reshape(-1, 1)\r\n start = '1/22/2020'\r\n start_date = datetime.datetime.strptime(start, '%m/%d/%Y')\r\n future_forecast_dates = []\r\n for i in range(len(future_forecast)):\r\n future_forecast_dates.append((start_date + datetime.timedelta(days=i)).strftime('%m/%d/%Y'))\r\n\r\n dataCovid= pd.DataFrame({ 'Dates': future_forecast_dates , 'Daily recoveries':india_daily_increase })\r\n train = dataCovid[:int(0.7*(len(dataCovid)))]\r\n valid = dataCovid[int(0.7*(len(dataCovid))):]\r\n #preprocessing (since arima takes univariate series as input)\r\n train.drop('Dates',axis=1,inplace=True)\r\n valid.drop('Dates',axis=1,inplace=True)\r\n model = auto_arima(train, trace=True, error_action='ignore', suppress_warnings=True)\r\n model.fit(train)\r\n forecast = model.predict(n_periods=len(valid))\r\n forecast = pd.DataFrame(forecast,index = valid.index,columns=['Prediction'])\r\n\r\n def ARIMAmodel(series, order, days = 21):\r\n # Fitting and forecast the series\r\n train = [x for x in series]\r\n model = ARIMA(train, order = order)\r\n model_fit = model.fit(disp=0)\r\n forecast, err, ci = model_fit.forecast(steps = days, alpha = 0.05)\r\n start_day = date.today() + datetime.timedelta(days = 1)\r\n predictions_df = pd.DataFrame({'Forecast':forecast.round()}, index=pd.date_range(start = start_day, periods=days, freq='D'))\r\n return predictions_df, ci\r\n\r\n new_recoveries = dataCovid['Daily recoveries'].values\r\n order = {\r\n 'new_recoveries': (1, 1, 2),\r\n }\r\n new_recoveries_today=new_recoveries[-1]\r\n # Forecasting with ARIMA models\r\n new_recoveries_pred, new_recoveries_ci = ARIMAmodel(new_recoveries, order['new_recoveries'])\r\n casesY=[]\r\n datesX=[]\r\n list1 = new_recoveries_pred.iloc[: ,0]\r\n for i in range(0,21):\r\n casesY.append(list1[i])\r\n datesX.append((date.today()+ datetime.timedelta(days=i)).strftime('%m/%d/%Y'))\r\n\r\n # Plot Results for forecasted dates only (detailed)\r\n plt.plot(datesX,casesY,color='red')\r\n plt.title('New recovered Cases Forecast')\r\n plt.xticks(rotation=90)\r\n # plt.figure(figsize=(22,22))\r\n plt.savefig(\"./corona cases forecasting/Results/plot3.png\",bbox_inches='tight')\r\n plt.autoscale()\r\n plt.show()\r\n \r\n# Taking user input choice for type of prediction method to be intitiated\r\nchoice=input(\"F for fresh cases,D for death cases,R for recovered cases prediction : \")\r\nif choice=='F':\r\n fresh_cases_daily()\r\nelif choice=='D':\r\n death_cases_daily()\r\nelif choice=='R':\r\n recovered_cases_daily()\r\nelse:\r\n print(\"Enter a valid choice\")\r\n"
] | [
[
"matplotlib.pyplot.autoscale",
"matplotlib.pyplot.style.use",
"pandas.date_range",
"matplotlib.pyplot.xticks",
"pandas.read_csv",
"matplotlib.pyplot.savefig",
"pandas.DataFrame",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot"
]
] |
richarajpal/deep_qa | [
"d918335a1bed71b9cfccf1d5743321cee9c61952"
] | [
"tests/tensors/backend_test.py"
] | [
"# pylint: disable=no-self-use,invalid-name\nimport numpy\nfrom deep_qa.tensors.backend import hardmax\nfrom deep_qa.testing.test_case import DeepQaTestCase\nfrom keras import backend as K\n\n\nclass TestBackendTensorFunctions(DeepQaTestCase):\n def test_hardmax(self):\n batch_size = 3\n knowledge_length = 5\n unnormalized_attention = K.variable(numpy.random.rand(batch_size, knowledge_length))\n hardmax_output = hardmax(unnormalized_attention, knowledge_length)\n input_value = K.eval(unnormalized_attention)\n output_value = K.eval(hardmax_output)\n assert output_value.shape == (batch_size, knowledge_length) # pylint: disable=no-member\n # Assert all elements other than the ones are zeros\n assert numpy.count_nonzero(output_value) == batch_size\n # Assert the max values in all rows are ones\n assert numpy.all(numpy.equal(numpy.max(output_value, axis=1),\n numpy.ones((batch_size,))))\n # Assert ones are in the right places\n assert numpy.all(numpy.equal(numpy.argmax(output_value, axis=1),\n numpy.argmax(input_value, axis=1)))\n"
] | [
[
"numpy.ones",
"numpy.argmax",
"numpy.count_nonzero",
"numpy.max",
"numpy.random.rand"
]
] |
zbsjila/CarND-Advanced-Lane-Lines | [
"07f93a4926741a12fdb873e6f6b0fb77550cf492"
] | [
"scripts/process_image_with_parameters.py"
] | [
"#!/usr/bin/env python\n## import\nimport sys\nimport lanefindlib\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport cv2\nimport pickle\nimport os\n\n## argin\nif len(sys.argv) < 4 or len(sys.argv) > 5:\n print(\"Syntax error! Usage: \");\n print(sys.argv[0], \"../test_images/test1.jpg ../output_images/test1 camera_data.p [showSaveFig=1]\");\n sys.exit(1);\nimg_fname = sys.argv[1]; \noutput_prefix = sys.argv[2]; \ncamera_data_pfile = sys.argv[3]; # \"camera_calibration_output.p\";\nif len(sys.argv) == 5:\n showSaveFig = int(sys.argv[4]);\nelse:\n showSaveFig = 1;\n\n## imread\nprint(\"imread \", img_fname);\nimg = mpimg.imread(img_fname);\n\n## load camera_data_pfile\ncamera_data_pickle = pickle.load(open(camera_data_pfile, \"rb\" ) ); \ncameraMatrix = camera_data_pickle[\"cameraMatrix\"];\ndistCoeffs = camera_data_pickle[\"distCoeffs\"];\nperspectiveTransform = camera_data_pickle[\"perspectiveTransform\"]; \nperspectiveTransformInv = np.linalg.inv(perspectiveTransform);\n#dx_m = camera_data_pickle[\"dx_m\"]; \n#dy_m = camera_data_pickle[\"dy_m\"]; \nxCarWarped = camera_data_pickle[\"xCarWarped\"]; \n\n## process_image_with_parameters\nprint(\"process_image_with_parameters\");\nimg_annotated = lanefindlib.process_image_with_parameters(img, cameraMatrix, distCoeffs, perspectiveTransform, perspectiveTransformInv, xCarWarped, verbose=True, showSaveFig=True, output_prefix=output_prefix)[0];\n\n## imsave\nimg_annotated_fname = output_prefix + '_img_annotated.png'\nprint(\"imsave\", img_annotated_fname);\nmpimg.imsave(img_annotated_fname, img_annotated);\n\n## end\nif showSaveFig:\n plt.show();\n"
] | [
[
"numpy.linalg.inv",
"matplotlib.pyplot.show",
"matplotlib.image.imsave",
"matplotlib.image.imread"
]
] |
FlyBrainLab/FBLClient | [
"c85de23d428a38fe13491b2f5eb30b690610108e"
] | [
"flybrainlab/utilities/neurowatch.py"
] | [
"\"\"\"\nThis file contains some utilities from Neurowatch for visualizing local files of neurons and meshes in FlyBrainLab.\n\"\"\"\n\nimport json\nimport pandas as pd\n\ndef loadJSON(client, file_name, uname=None, mesh_class = 'Neuropil'):\n \"\"\"Loads a mesh stored in the .json format.\n # Arguments\n client (FlyBrainLab Client): A FlyBrainLab Client.\n file_name (str): Database ID of the neuron or node.\n scale_factor (float): A scale factor to scale the neuron's dimensions with. Defaults to 1.\n uname (str): Unique name to use in the frontend. Defaults to the file_name.\n mesh_class (str): Mesh class to use. Can be \"Neuropil\" or \"MorphologyData\". Defaults to \"Neuropil\".\n # Examples:\n loadJSON(client, 'cloud.json', uname = 'my_neuropil')\n\n \"\"\"\n with open(file_name) as f:\n data = json.load(f)\n if uname == None:\n uname = file_name.split('.')[0]\n rid = '#'+uname\n mesh_data = {'data': {'data': {rid: {'name': uname,\n 'uname': uname,\n 'morph_type': 'mesh',\n 'faces': data['faces'],\n 'vertices': data['vertices'],\n 'class': mesh_class}},\n 'queryID': '0-0'},\n 'messageType': 'Data',\n 'widget': 'NLP'}\n client.tryComms(mesh_data)\n \ndef loadSWC(client, file_name, scale_factor=1., uname=None):\n \"\"\"Loads a neuron skeleton stored in the .swc format.\n # Arguments\n client (FlyBrainLab Client): A FlyBrainLab Client.\n file_name (str): Database ID of the neuron or node.\n scale_factor (float): A scale factor to scale the neuron's dimensions with. Defaults to 1.\n uname (str): Unique name to use in the frontend. Defaults to the file_name.\n \"\"\"\n neuron_pd = pd.read_csv(file_name,\n names=['sample','identifier','x','y','z','r','parent'],\n comment='#',\n delim_whitespace=True)\n if uname == None:\n uname = file_name.split('.')[0]\n rid = '#'+file_name\n neuron_data = {'data': {'data': {rid: {'name': file_name,\n 'uname': uname,\n 'morph_type': 'mesh',\n 'faces': list(scale_factor * neuron_pd['x']),\n 'vertices': list(scale_factor * neuron_pd['y']),\n 'class': 'MorphologyData'}},\n 'queryID': '0-0'},\n 'messageType': 'Data',\n 'widget': 'NLP'}\n client.tryComms(neuron_data)\n\n return True"
] | [
[
"pandas.read_csv"
]
] |
zhouliupku/LGtagging_LSTM | [
"4db0d34f7544913b75e66253ef63a08fb74cc993"
] | [
"lg_utils.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 21 00:11:24 2019\n\n@author: Zhou\n\"\"\"\n\nimport os\nimport re\nimport pickle\nimport numpy as np\nimport pandas as pd\nimport itertools\n\nimport config\n\ndef convert_to_orig(s):\n \"\"\"\n Convert string from database to corresponding original text\n \"\"\"\n return s.replace(' ', config.PADDING_CHAR)\n\n\ndef concat_lists(ls):\n return list(itertools.chain.from_iterable(ls))\n\n\ndef random_separate(xs, percs):\n \"\"\"\n given a list of objects xs, split it randomly into n+1 parts where n=len(percs)\n \"\"\"\n ns = list(map(int, [p * len(xs) for p in percs]))\n index_permuted = np.random.permutation(len(xs))\n bs = np.clip(np.array(ns).cumsum(), 0, len(xs))\n bs = [0] + list(bs) + [len(xs)]\n return [[xs[i] for i in index_permuted[beg:end]] for beg, end in zip(bs[:-1], bs[1:])]\n\n\ndef modify_tag_seq(text, tag_seq, keyword, tagname):\n \"\"\"\n Modify tag_seq in the same location of keyword in text by tagname\n \"\"\"\n if is_empty_cell(keyword):\n return\n keyword = convert_to_orig(keyword)\n if keyword not in text or len(text) != len(tag_seq):\n return\n begin_locs = [loc.start() for loc in re.finditer(keyword, text)]\n for begin_loc in begin_locs:\n for loc in range(begin_loc, begin_loc + len(keyword)):\n if tag_seq[loc] != config.NULL_TAG:\n raise ValueError(\"Same char cannot bear more than one tag!\")\n tag_seq[loc] = tagname\n \n\ndef is_empty_cell(x):\n return (not isinstance(x, str)) or len(x) == 0\n \n \ndef nan_weighted_average(arr, w):\n a = np.array(arr)\n weights = np.array(w)\n indices = ~np.isnan(a)\n return np.average(a[indices], weights=weights[indices])\n\n\ndef get_sent_len_for_pages(tag_seq_list, eos_tag):\n \"\"\"\n tag_seq_list: list of list of tags\n \"\"\"\n parsed_sent_len_for_pages = []\n for tag_seq in tag_seq_list:\n # make list of int (i.e. sentence lengths) out of list of tags\n parsed_sent_len = []\n current_len = 0\n for tag in tag_seq[1:-1]: # ignore <S> and </S>\n current_len += 1\n if tag == eos_tag:\n parsed_sent_len.append(current_len)\n current_len = 0\n # in case last char is not tagged as 'S'\n if current_len > 0:\n parsed_sent_len.append(current_len)\n parsed_sent_len_for_pages.append(parsed_sent_len)\n return parsed_sent_len_for_pages\n\n\ndef get_keywords_from_tagged_record(char_samples, tag_name):\n res = []\n is_inside_keyword = False\n current_keyword = \"\"\n for cs in char_samples:\n if cs.get_tag() == tag_name:\n is_inside_keyword = True\n current_keyword += cs.get_char()\n else:\n if is_inside_keyword: # First char sample after keyword\n res.append(current_keyword)\n current_keyword = \"\"\n is_inside_keyword = False\n # In case last keyword is by end of sentence\n if len(current_keyword) > 0:\n res.append(current_keyword)\n return res\n\n\ndef get_data_from_samples(samples, x_encoder, y_encoder):\n retv = []\n for i, p in enumerate(samples):\n if i % 1000 == 0:\n print(i)\n retv.append((p.get_x(x_encoder), p.get_y(y_encoder)))\n return retv\n \n \ndef prepare_confusion_matrix(tag_true, tag_pred, tag_list):\n tag_to_idx = {t: i for i, t in enumerate(tag_list)}\n confusion_matrix = np.zeros([len(tag_list), len(tag_list)])\n \n for ps, ts in zip(tag_pred, tag_true):\n assert len(ps) == len(ts)\n for p, t in zip(ps, ts):\n if p not in tag_list or t not in tag_list:\n continue\n confusion_matrix[tag_to_idx[t], tag_to_idx[p]] += 1\n \n return tag_to_idx, confusion_matrix\n\n\ndef process_confusion_matrix(confusion_matrix, tag_idx):\n tp = confusion_matrix[tag_idx, tag_idx]\n fp = confusion_matrix[:, tag_idx].sum() - tp\n fn = confusion_matrix[tag_idx, :].sum() - tp\n tn = confusion_matrix.sum() - tp - fp - fn\n precision = 0 if tp + fp == 0 else tp / float(tp + fp)\n recall = 0 if tp + fn == 0 else tp / float(tp + fn)\n accuracy = (tp + tn) / float(confusion_matrix.sum())\n f_score = 0 if precision == 0 or recall == 0 else 2 / (1 / precision + 1 / recall)\n return precision, recall, accuracy, f_score\n\n\ndef process_confusion_matrix_macro(confusion_matrix, tag_to_idx,\n ignore_tags=[], weighted=True):\n #TODO: unit tests\n precisions, recalls, accuracys, weights = [], [], [], []\n# idx_not_ignored = [tag_idx for tag_name, tag_idx in tag_to_idx.items() if tag_name not in ignore_tags]\n for tag_name, tag_idx in tag_to_idx.items():\n if tag_name in ignore_tags:\n continue\n weights.append(confusion_matrix[tag_idx, :].sum() if weighted else 1.0)\n tp = confusion_matrix[tag_idx, tag_idx]\n fp = confusion_matrix[:, tag_idx].sum() - tp\n fn = confusion_matrix[tag_idx, :].sum() - tp\n tn = confusion_matrix[:, :].sum() - tp - fp - fn\n precision = 0 if tp + fp == 0 else tp / float(tp + fp)\n recall = 0 if tp + fn == 0 else tp / float(tp + fn)\n accuracy = (tp + tn) / float(tp + tn + fp + fn)\n precisions.append(precision)\n recalls.append(recall)\n accuracys.append(accuracy)\n \n precision_macro = nan_weighted_average(precisions, weights)\n recall_macro = nan_weighted_average(recalls, weights)\n accuracy_macro = nan_weighted_average(accuracys, weights)\n f_score_macro = 0 if precision_macro == 0 or recall_macro == 0 else 2 / (1 / precision_macro + 1 / recall_macro)\n return precision_macro, recall_macro, accuracy_macro, f_score_macro\n\n\ndef process_confusion_matrix_micro(confusion_matrix, tag_to_idx, ignore_tags=[]):\n tps, fps, fns, tns = [], [], [], []\n# idx_not_ignored = [tag_idx for tag_name, tag_idx in tag_to_idx.items() if tag_name not in ignore_tags]\n for tag_name, tag_idx in tag_to_idx.items():\n if tag_name in ignore_tags:\n continue\n tp = confusion_matrix[tag_idx, tag_idx]\n fp = confusion_matrix[:, tag_idx].sum() - tp\n fn = confusion_matrix[tag_idx, :].sum() - tp\n tn = confusion_matrix[:, :].sum() - tp - fp - fn\n tps.append(tp)\n fps.append(fp)\n fns.append(fn)\n tns.append(tn)\n precision = 0 if sum(tps) + sum(fps) == 0 else sum(tps) / float(sum(tps) + sum(fps))\n recall = 0 if sum(tps) + sum(fns) == 0 else sum(tps) / float(sum(tps) + sum(fns))\n accuracy = (sum(tps) + sum(tns)) / float(sum(tps) + sum(fps) + sum(fns) + sum(tns))\n f_score = 0 if precision == 0 or recall == 0 else 2 / (1 / precision + 1 / recall)\n return precision, recall, accuracy, f_score\n\n\ndef calc_entity_metrics(tag_pred, tag_true):\n \"\"\"\n Both tag_pred and tag_true are list of list of tag\n calculate metrics based on exact match\n \"\"\"\n sum_num_matched_chunk = 0\n sum_num_true_chunk = 0\n sum_num_pred_chunk = 0\n for ps, ts in zip(tag_pred, tag_true):\n num_matched_chunk, num_true_chunk, num_pred_chunk = chunk_count(ps, ts)\n sum_num_matched_chunk += num_matched_chunk\n sum_num_true_chunk += num_true_chunk\n sum_num_pred_chunk += num_pred_chunk\n \n precision = 0 if sum_num_pred_chunk == 0 else sum_num_matched_chunk / float(sum_num_pred_chunk)\n recall = 0 if sum_num_true_chunk == 0 else sum_num_matched_chunk / float(sum_num_true_chunk)\n if precision == 0 or recall == 0:\n f_score = 0\n else:\n f_score = 2.0 / (1.0 / precision + 1.0 / recall)\n return precision, recall, f_score\n\n \ndef chunk_count(ps, ts):\n \"\"\"\n given two lists of tags, count matched words and total words of both lists\n all counts exclude special tags, i.e. BEG, END, etc\n With BIO style tags, consecutive O's is treated as chunks too\n Tags with same type starting from B-tag_type followed by several I-tag_type\n are treated as a chunk\n In case of illegal sequence, following conll 2003\n https://github.com/sighsmile/conlleval.git\n treat I-tag_type without preceding B-tag_type or I-tag_type as B-tag_type\n Return: num_matched_chunk, num_true_chunk, num_pred_chunk\n \"\"\"\n pred_chunk = get_chunk(ps)\n true_chunk = get_chunk(ts)\n matches = [c for c in pred_chunk if c in true_chunk]\n return len(matches), len(true_chunk), len(pred_chunk)\n \n \ndef get_chunk(seq):\n \"\"\"\n Chunk represented as triplets (start_index, end_index, tag_type)\n Tags in config.special_tag_list are excluded in counts\n \"\"\"\n if len(seq) == 0:\n return []\n triplets = []\n start, last_chunk_type = 0, None\n for i, tag in enumerate(seq):\n # Cases where previous chunk is ended:\n # 1. current tag is special tag\n # 2. current tag type (ignoring B/I) is diff than prev chunk type\n # 3. current tag prefix is B-, regardless of prev chunk type\n tag_prefix, tag_type = parse_tag(tag)\n if tag_type in config.special_tag_list:\n if last_chunk_type is not None:\n triplets.append((start, i, last_chunk_type))\n last_chunk_type = None\n elif tag_type != last_chunk_type or tag_prefix == config.BEG_PREFIX:\n if last_chunk_type is not None:\n triplets.append((start, i, last_chunk_type))\n start, last_chunk_type = i, tag_type\n if last_chunk_type is not None: \n triplets.append((start, len(seq), last_chunk_type))\n return triplets\n\n\ndef parse_tag(tag):\n \"\"\"\n Helper function for parsing tag prefix and tag type from tag\n \"\"\"\n if tag in config.special_tag_list:\n return tag, tag\n elif tag == config.NULL_TAG:\n return tag, tag\n else:\n return tag[:config.BIO_PREFIX_LEN], tag[config.BIO_PREFIX_LEN:]\n \n \ndef correct_ratio_calculation(samples, model, args, subset_name, logger):\n '''\n Take in samples (pages / records), input_encoder, model, output_encoder \n Get the predict tags and return the correct ratio\n '''\n inputs = [(s.get_x(), s.get_y()) for s in samples] \n tags = model.evaluate_model(inputs, args) # list of (list of tags, list of tags)\n tag_pred = [tag[0] for tag in tags]\n tag_true = [tag[1] for tag in tags]\n assert len(tag_pred) == len(tag_true)\n \n# do_stats_for_tags(tag_true, subset_name, \"real\")\n# correct_tag_pred = [[p for p,t in zip(ps,ts) \\\n# if p == t and t not in config.special_tag_list] \\\n# for ps,ts in zip(tag_pred, tag_true)]\n# do_stats_for_tags(correct_tag_pred, subset_name, \"correctly predicted\")\n \n for x, y in zip(tag_pred, tag_true):\n assert len(x) == len(y)\n if args.task_type == \"page\": # only calculate the EOS tag for page model\n upstairs = [sum([p==t for p,t in zip(ps, ts) if t == config.EOS_TAG]) \\\n for ps, ts in zip(tag_pred, tag_true)]\n downstairs = [len([r for r in rs if r == config.EOS_TAG]) for rs in tag_true]\n else: # ignore BEG, END etc for record model, although they are learned\n upstairs = [sum([p==t for p,t in zip(ps, ts) if t not in config.special_tag_list]) \\\n for ps, ts in zip(tag_pred, tag_true)]\n downstairs = [len([r for r in rs if r not in config.special_tag_list]) for rs in tag_true]\n # There should be no empty page/record so no check for divide-by-zero needed here\n correct_ratio = sum(upstairs) / float(sum(downstairs))\n \n # Log info of correct ratio\n info_log = \"Correct ratio of {} set is {}\".format(subset_name, correct_ratio)\n print(info_log)\n logger.info(info_log)\n \n return correct_ratio\n\n\ndef do_stats_for_tags(tag_seq, subset_name, stat_type):\n flatted_tag_true = [item for sub_list in tag_seq for item in sub_list] #list of tags\n true_tag_set = set(flatted_tag_true)\n for tag in true_tag_set:\n count = 0\n for item in flatted_tag_true:\n if item == tag:\n count += 1\n print(\"For {} data, the number of {} tag {} : {}\".format(subset_name, stat_type, tag, count))\n \n \n\n\ndef tag_count(samples, model, subset_name, args):\n '''\n Take in samples (pages / records), input_encoder, model, output_encoder \n Get the counts of each tags\n '''\n inputs = [(s.get_x(), s.get_y()) for s in samples] \n tags = model.evaluate_model(inputs, args) # list of (list of tags, list of tags)\n tag_pred = [tag[0] for tag in tags] # list of list of tags\n tag_true = [tag[1] for tag in tags]\n assert len(tag_pred) == len(tag_true)\n \n true_tag_statistics = []\n flatted_tag_true = [item for sub_list in tag_true for item in sub_list] #list of tags\n true_tag_set = set(flatted_tag_true)\n for tag in true_tag_set:\n count = 0\n for item in flatted_tag_true:\n if item == tag:\n count += 1\n true_tag_statistics.append((tag, count))\n for t,c in true_tag_statistics:\n print(\"For {} data, the number of real tag {} : {}\".format(subset_name, t, c))\n \n for x, y in zip(tag_pred, tag_true):\n assert len(x) == len(y)\n correct_pairs = []\n for ps,ts in zip(tag_pred, tag_true):\n for p,t in zip(ps,ts):\n if p == t and t not in config.special_tag_list:\n correct_pairs.append((p,t))\n tag_set = set([item[0] for item in correct_pairs]) \n tag_statistics = [] \n for tag in tag_set:\n count = 0\n for item in correct_pairs:\n if item[1] == tag:\n count += 1\n tag_statistics.append((tag, count))\n for t,c in tag_statistics:\n print(\"For {} data, the number of correctly predicted tag {} : {}\".format(subset_name, t, c))\n return tag_statistics\n\ndef load_data_from_pickle(filename, size):\n path = os.path.join(config.DATA_PATH, size)\n return pickle.load(open(os.path.join(path, filename), \"rb\"))\n\n\ndef get_filename_from_embed_type(embed_type):\n return os.path.join(config.EMBEDDING_PATH,\n config.EMBEDDING_FILENAME_DICT[embed_type])\n"
] | [
[
"numpy.array",
"numpy.average",
"numpy.isnan"
]
] |
ewellchen/Entanglement_detection | [
"6622ffbdfb09c12389af79e35a98b65b367f15f7"
] | [
"2-qubit/generate_data.py"
] | [
"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\nimport numpy as np\r\nfrom tools import mkdir\r\n\r\n\r\n# 1. Create a random Complex matrix H.\r\n# 2. Make it positive, and normalize to unity.\r\n\r\nclass Generate_separable_state(object):\r\n def __init__(self, name='sep_train_set', size=10000, sub_dim=2, space_number=2, mix_number=10):\r\n self.name = name\r\n self.size = size\r\n self.sub_dim = sub_dim\r\n self.space_number = space_number\r\n self.mix_number = mix_number\r\n self.set = []\r\n\r\n def generate_sub_state(self):\r\n q1 = np.random.normal(0, 1, [self.sub_dim, self.sub_dim])\r\n q2 = np.random.normal(0, 1, [self.sub_dim, self.sub_dim])\r\n q = q1 + 1j * q2\r\n q = np.matrix(q) # Create a random Complex matrix H.\r\n q = (q + q.H) / 2 # Generate GUE\r\n q = np.dot(q, q.H) / np.trace(np.dot(q, q.H)) # Make it positive, and normalize to unity.\r\n return q\r\n\r\n def generate(self):\r\n for i in range(int(self.size / self.mix_number)):\r\n state = []\r\n for j in range(self.mix_number):\r\n s = 0\r\n if self.space_number > 1:\r\n for number in range(self.space_number - 1):\r\n s = np.reshape(np.einsum('ij,kl->ikjl', self.generate_sub_state(), self.generate_sub_state()),\r\n [self.sub_dim ** self.space_number, self.sub_dim ** self.space_number])\r\n state.append(s)\r\n for j in range(self.mix_number):\r\n weight = np.random.random([j + 1])\r\n weight = weight / np.sum(weight)\r\n mix = np.zeros([self.sub_dim ** self.space_number, self.sub_dim ** self.space_number])\r\n for k in range(j + 1):\r\n mix = mix + weight[k] * state[k]\r\n self.set.append(mix)\r\n Set = np.array(self.set)\r\n shape = list(Set.shape)\r\n shape.append(1)\r\n Set_r = np.reshape(np.real(Set), shape)\r\n Set_i = np.reshape(np.imag(Set), shape)\r\n Set_2 = np.concatenate((Set_r, Set_i), axis=-1)\r\n mkdir('./Data/')\r\n np.save('./Data/' + self.name + '.npy', Set_2)\r\n\r\n\r\nclass Generate_entangled_state(object):\r\n def __init__(self, name='ent_test_set', size=10000, dim=4):\r\n self.name = name\r\n self.size = size\r\n self.dim = dim\r\n self.state = []\r\n\r\n def ppt_criterion(self, rho, dims, mask):\r\n rho = np.array(rho)\r\n shape = rho.shape\r\n nsys = len(mask)\r\n pt_dims = np.arange(2 * nsys).reshape(2, nsys).T\r\n pt_idx = np.concatenate([[pt_dims[n, mask[n]] for n in range(nsys)],\r\n [pt_dims[n, 1 - mask[n]] for n in range(nsys)]])\r\n\r\n data = rho.reshape(\r\n np.array(dims).flatten()).transpose(pt_idx).reshape(shape)\r\n return np.all(np.linalg.eigvals(data) > 0)\r\n\r\n def generate(self):\r\n sum = 0\r\n while sum < self.size:\r\n s1 = np.random.normal(0, 1, [self.dim, self.dim])\r\n s2 = np.random.normal(0, 1, [self.dim, self.dim])\r\n s = s1 + 1j * s2\r\n s = np.matrix(s) # Create a random Complex matrix H.\r\n s = (s + s.H) / 2 # Generate GUE\r\n s = np.dot(s, s.H) / np.trace(np.dot(s, s.H)) # Make it positive, and normalize to unity.\r\n if self.ppt_criterion(s, dims=[[2, 2], [2, 2]], mask=[0, 1]):\r\n a = 1\r\n else:\r\n self.state.append(s)\r\n sum += 1\r\n Set = np.array(self.state)\r\n shape = list(Set.shape)\r\n shape.append(1)\r\n Set_r = np.reshape(np.real(Set), shape)\r\n Set_i = np.reshape(np.imag(Set), shape)\r\n Set_2 = np.concatenate((Set_r, Set_i), axis=-1)\r\n mkdir('./Data/')\r\n np.save('./Data/' + self.name + '.npy', Set_2)\r\n\r\n\r\nif __name__ == '__main__':\r\n set_name = 'mix'\r\n train_size = 160000\r\n test_size = 40000\r\n Generate_separable_state(name='sep_train_set', size=train_size, sub_dim=2, space_number=2, mix_number=10).generate()\r\n Generate_separable_state(name='sep_test_set', size=test_size, sub_dim=2, space_number=2, mix_number=10).generate()\r\n Generate_entangled_state(name='ent_test_set', size=test_size, dim=4).generate()\r\n\r\n print('Generating data is finished!')\r\n"
] | [
[
"numpy.save",
"numpy.sum",
"numpy.dot",
"numpy.zeros",
"numpy.matrix",
"numpy.random.random",
"numpy.arange",
"numpy.linalg.eigvals",
"numpy.random.normal",
"numpy.concatenate",
"numpy.array",
"numpy.real",
"numpy.imag"
]
] |
srihari-humbarwadi/neural-structured-learning | [
"345b8d644dd7745179263bf6dc9aeb8a921528f4"
] | [
"neural_structured_learning/examples/graph_keras_mlp_cora.py"
] | [
"# Copyright 2019 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.\nr\"\"\"An example Keras trainer for the Cora data set using graph regularization.\n\nUSAGE:\n python graph_keras_mlp_cora.py [flags] train.tfr test.tfr\n\nSee https://linqs.soe.ucsc.edu/data for a description of the Cora data set, and\nthe corresponding graph and training data set.\n\nThis example demonstrates the use of sequential, functional, and subclass models\nin Keras for graph regularization. Users may change 'base_models' defined in\nmain() as necessary, to select a subset of the supported Keras base model types.\nIn all cases, the base model used is a multi-layer perceptron containing two\nhidden layers with drop out.\n\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nimport attr\n\nimport neural_structured_learning as nsl\n\nimport tensorflow as tf\n\nFLAGS = flags.FLAGS\nFLAGS.showprefixforinfo = False\n\nflags.DEFINE_integer('train_epochs', None, 'Number of epochs to train.')\nflags.DEFINE_integer('eval_steps', None, 'Number of steps to evaluate.')\n\nNBR_FEATURE_PREFIX = 'NL_nbr_'\nNBR_WEIGHT_SUFFIX = '_weight'\n\n\[email protected]\nclass HParams(object):\n \"\"\"Hyper-parameters used for training.\"\"\"\n ### dataset parameters\n num_classes = attr.ib(default=7)\n max_seq_length = attr.ib(default=1433)\n ### NGM parameters\n distance_type = attr.ib(default=nsl.configs.DistanceType.L2)\n graph_regularization_multiplier = attr.ib(default=0.1)\n num_neighbors = attr.ib(default=1)\n ### model architecture\n num_fc_units = attr.ib(default=[50, 50])\n ### training parameters\n train_epochs = attr.ib(default=10)\n batch_size = attr.ib(default=128)\n dropout_rate = attr.ib(default=0.5)\n ### eval parameters\n eval_steps = attr.ib(default=None) # Every test instance is evaluated.\n\n\ndef get_hyper_parameters():\n \"\"\"Returns the hyper-parameters used for training.\"\"\"\n hparams = HParams()\n if FLAGS.train_epochs:\n hparams.train_epochs = FLAGS.train_epochs\n if FLAGS.eval_steps:\n hparams.eval_steps = FLAGS.eval_steps\n return hparams\n\n\ndef load_dataset(filename):\n \"\"\"Reads a file in the `.tfrecord` format.\n\n Args:\n filename: Name of the file containing `tf.train.Example` objects.\n\n Returns:\n An instance of `tf.data.TFRecordDataset` containing the `tf.train.Example`\n objects.\n \"\"\"\n return tf.data.TFRecordDataset([filename])\n\n\ndef make_dataset(file_path, training, include_nbr_features, hparams):\n \"\"\"Returns a `tf.data.Dataset` instance based on data in `file_path`.\"\"\"\n\n def parse_example(example_proto):\n \"\"\"Extracts relevant fields from the `example_proto`.\n\n Args:\n example_proto: An instance of `tf.train.Example`.\n\n Returns:\n A pair whose first value is a dictionary containing relevant features\n and whose second value contains the ground truth labels.\n \"\"\"\n # The 'words' feature is a multi-hot, bag-of-words representation of the\n # original raw text. A default value is required for examples that don't\n # have the feature.\n feature_spec = {\n 'words':\n tf.io.FixedLenFeature([hparams.max_seq_length],\n tf.int64,\n default_value=tf.constant(\n 0,\n dtype=tf.int64,\n shape=[hparams.max_seq_length])),\n 'label':\n tf.io.FixedLenFeature((), tf.int64, default_value=-1),\n }\n if include_nbr_features:\n for i in range(hparams.num_neighbors):\n nbr_feature_key = '{}{}_{}'.format(NBR_FEATURE_PREFIX, i, 'words')\n nbr_weight_key = '{}{}{}'.format(NBR_FEATURE_PREFIX, i,\n NBR_WEIGHT_SUFFIX)\n nbr_id_key = '{}{}_{}'.format(NBR_FEATURE_PREFIX, i, 'id')\n feature_spec[nbr_feature_key] = tf.io.FixedLenFeature(\n [hparams.max_seq_length],\n tf.int64,\n default_value=tf.constant(\n 0, dtype=tf.int64, shape=[hparams.max_seq_length]))\n feature_spec[nbr_weight_key] = tf.io.FixedLenFeature(\n [1], tf.float32, default_value=tf.constant([0.0]))\n feature_spec[nbr_id_key] = tf.io.FixedLenFeature(\n (), tf.string, default_value='')\n\n features = tf.io.parse_single_example(example_proto, feature_spec)\n\n labels = features.pop('label')\n return features, labels\n\n # If the dataset is sharded, the following code may be required:\n # filenames = tf.data.Dataset.list_files(file_path, shuffle=True)\n # dataset = filenames.interleave(load_dataset, cycle_length=1)\n dataset = load_dataset(file_path)\n if training:\n dataset = dataset.shuffle(10000)\n dataset = dataset.map(parse_example)\n dataset = dataset.batch(hparams.batch_size)\n return dataset\n\n\ndef make_mlp_sequential_model(hparams):\n \"\"\"Creates a sequential multi-layer perceptron model.\"\"\"\n model = tf.keras.Sequential()\n model.add(\n tf.keras.layers.InputLayer(\n input_shape=(hparams.max_seq_length,), name='words'))\n # Input is already one-hot encoded in the integer format. We cast it to\n # floating point format here.\n model.add(\n tf.keras.layers.Lambda(lambda x: tf.keras.backend.cast(x, tf.float32)))\n for num_units in hparams.num_fc_units:\n model.add(tf.keras.layers.Dense(num_units, activation='relu'))\n model.add(tf.keras.layers.Dropout(hparams.dropout_rate))\n model.add(tf.keras.layers.Dense(hparams.num_classes, activation='softmax'))\n return model\n\n\ndef make_mlp_functional_model(hparams):\n \"\"\"Creates a functional API-based multi-layer perceptron model.\"\"\"\n inputs = tf.keras.Input(\n shape=(hparams.max_seq_length,), dtype='int64', name='words')\n\n # Input is already one-hot encoded in the integer format. We cast it to\n # floating point format here.\n cur_layer = tf.keras.layers.Lambda(\n lambda x: tf.keras.backend.cast(x, tf.float32))(\n inputs)\n\n for num_units in hparams.num_fc_units:\n cur_layer = tf.keras.layers.Dense(num_units, activation='relu')(cur_layer)\n # For functional models, by default, Keras ensures that the 'dropout' layer\n # is invoked only during training.\n cur_layer = tf.keras.layers.Dropout(hparams.dropout_rate)(cur_layer)\n\n outputs = tf.keras.layers.Dense(\n hparams.num_classes, activation='softmax')(\n cur_layer)\n\n model = tf.keras.Model(inputs, outputs=outputs)\n return model\n\n\ndef make_mlp_subclass_model(hparams):\n \"\"\"Creates a multi-layer perceptron subclass model in Keras.\"\"\"\n\n class MLP(tf.keras.Model):\n \"\"\"Subclass model defining a multi-layer perceptron.\"\"\"\n\n def __init__(self):\n super(MLP, self).__init__()\n self.cast_to_float_layer = tf.keras.layers.Lambda(\n lambda x: tf.keras.backend.cast(x, tf.float32))\n self.dense_layers = [\n tf.keras.layers.Dense(num_units, activation='relu')\n for num_units in hparams.num_fc_units\n ]\n self.dropout_layer = tf.keras.layers.Dropout(hparams.dropout_rate)\n self.output_layer = tf.keras.layers.Dense(\n hparams.num_classes, activation='softmax')\n\n def call(self, inputs, training=False):\n cur_layer = self.cast_to_float_layer(inputs['words'])\n for dense_layer in self.dense_layers:\n cur_layer = dense_layer(cur_layer)\n cur_layer = self.dropout_layer(cur_layer, training=training)\n\n outputs = self.output_layer(cur_layer)\n\n return outputs\n\n return MLP()\n\n\ndef log_metrics(model_desc, eval_metrics):\n \"\"\"Logs evaluation metrics at `logging.INFO` level.\n\n Args:\n model_desc: A description of the model.\n eval_metrics: A dictionary mapping metric names to corresponding values. It\n must contain the loss and accuracy metrics.\n \"\"\"\n logging.info('\\n')\n logging.info('Eval accuracy for %s: %s', model_desc, eval_metrics['accuracy'])\n logging.info('Eval loss for %s: %s', model_desc, eval_metrics['loss'])\n if 'graph_loss' in eval_metrics:\n logging.info('Eval graph loss for %s: %s', model_desc,\n eval_metrics['graph_loss'])\n\n\ndef train_and_evaluate(model, model_desc, train_dataset, test_dataset, hparams):\n \"\"\"Compiles, trains, and evaluates a `Keras` model.\n\n Args:\n model: An instance of `tf.Keras.Model`.\n model_desc: A description of the model.\n train_dataset: An instance of `tf.data.Dataset` representing training data.\n test_dataset: An instance of `tf.data.Dataset` representing test data.\n hparams: An instance of `Hparams`.\n \"\"\"\n model.compile(\n optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),\n metrics=['accuracy'])\n model.fit(train_dataset, epochs=hparams.train_epochs, verbose=1)\n eval_results = dict(\n zip(model.metrics_names,\n model.evaluate(test_dataset, steps=hparams.eval_steps)))\n log_metrics(model_desc, eval_results)\n\n\ndef main(argv):\n # Check that the correct number of arguments have been provided. The\n # training and test data should contain 'tf.train.Example' objects in the\n # TFRecord format.\n if len(argv) != 3:\n raise app.UsageError('Invalid number of arguments; expected 2, got %d' %\n (len(argv) - 1))\n\n hparams = get_hyper_parameters()\n train_data_path = argv[1]\n test_data_path = argv[2]\n\n # Graph regularization configuration.\n graph_reg_config = nsl.configs.make_graph_reg_config(\n max_neighbors=hparams.num_neighbors,\n multiplier=hparams.graph_regularization_multiplier,\n distance_type=hparams.distance_type,\n sum_over_axis=-1)\n\n # Create the base MLP models.\n base_models = {\n 'FUNCTIONAL': make_mlp_functional_model(hparams),\n 'SEQUENTIAL': make_mlp_sequential_model(hparams),\n 'SUBCLASS': make_mlp_subclass_model(hparams)\n }\n for base_model_tag, base_model in base_models.items():\n logging.info('\\n====== %s BASE MODEL TEST BEGIN ======', base_model_tag)\n train_dataset = make_dataset(train_data_path, True, False, hparams)\n test_dataset = make_dataset(test_data_path, False, False, hparams)\n train_and_evaluate(base_model, 'Base MLP model', train_dataset,\n test_dataset, hparams)\n\n logging.info('\\n====== TRAINING WITH GRAPH REGULARIZATION ======\\n')\n\n # Wrap the base MLP model with graph regularization.\n graph_reg_model = nsl.keras.GraphRegularization(base_model,\n graph_reg_config)\n train_dataset = make_dataset(train_data_path, True, True, hparams)\n test_dataset = make_dataset(test_data_path, False, False, hparams)\n train_and_evaluate(graph_reg_model, 'MLP + graph regularization',\n train_dataset, test_dataset, hparams)\n\n logging.info('\\n====== %s BASE MODEL TEST END ======', base_model_tag)\n\n\nif __name__ == '__main__':\n tf.compat.v1.enable_v2_behavior()\n app.run(main)\n"
] | [
[
"tensorflow.data.TFRecordDataset",
"tensorflow.io.parse_single_example",
"tensorflow.keras.layers.Dropout",
"tensorflow.keras.losses.SparseCategoricalCrossentropy",
"tensorflow.keras.Sequential",
"tensorflow.keras.Model",
"tensorflow.keras.backend.cast",
"tensorflow.io.FixedLenFeature",
"tensorflow.keras.layers.InputLayer",
"tensorflow.keras.layers.Dense",
"tensorflow.compat.v1.enable_v2_behavior",
"tensorflow.constant",
"tensorflow.keras.Input"
]
] |
alwc/Text-Image-Augmentation-python | [
"20da2089280098d09069407f7da09eac78eb2eb7"
] | [
"warp_mls.py"
] | [
"# -*- coding:utf-8 -*-\r\n# Author: RubanSeven\r\nimport math\r\n\r\nimport numpy as np\r\n\r\n\r\nclass WarpMLS:\r\n def __init__(self, src, src_pts, dst_pts, dst_w, dst_h, trans_ratio=1.):\r\n self.src = src\r\n self.src_pts = src_pts\r\n self.dst_pts = dst_pts\r\n self.pt_count = len(self.dst_pts)\r\n self.dst_w = dst_w\r\n self.dst_h = dst_h\r\n self.trans_ratio = trans_ratio\r\n self.grid_size = 100\r\n self.rdx = np.zeros((self.dst_h, self.dst_w))\r\n self.rdy = np.zeros((self.dst_h, self.dst_w))\r\n\r\n @staticmethod\r\n def __bilinear_interp(x, y, v11, v12, v21, v22):\r\n return (v11 * (1 - y) + v12 * y) * (1 - x) + (v21 * (1 - y) + v22 * y) * x\r\n\r\n def generate(self):\r\n self.calc_delta()\r\n return self.gen_img()\r\n\r\n def calc_delta(self):\r\n w = np.zeros(self.pt_count, dtype=np.float32)\r\n\r\n if self.pt_count < 2:\r\n return\r\n\r\n i = 0\r\n while 1:\r\n if self.dst_w <= i < self.dst_w + self.grid_size - 1:\r\n i = self.dst_w - 1\r\n elif i >= self.dst_w:\r\n break\r\n\r\n j = 0\r\n while 1:\r\n if self.dst_h <= j < self.dst_h + self.grid_size - 1:\r\n j = self.dst_h - 1\r\n elif j >= self.dst_h:\r\n break\r\n\r\n sw = 0\r\n swp = np.zeros(2, dtype=np.float32)\r\n swq = np.zeros(2, dtype=np.float32)\r\n new_pt = np.zeros(2, dtype=np.float32)\r\n cur_pt = np.array([i, j], dtype=np.float32)\r\n\r\n k = 0\r\n for k in range(self.pt_count):\r\n if i == self.dst_pts[k][0] and j == self.dst_pts[k][1]:\r\n break\r\n\r\n w[k] = 1. / ((i - self.dst_pts[k][0]) * (i - self.dst_pts[k][0]) +\r\n (j - self.dst_pts[k][1]) * (j - self.dst_pts[k][1]))\r\n\r\n sw += w[k]\r\n swp = swp + w[k] * np.array(self.dst_pts[k])\r\n swq = swq + w[k] * np.array(self.src_pts[k])\r\n\r\n if k == self.pt_count - 1:\r\n pstar = 1 / sw * swp\r\n qstar = 1 / sw * swq\r\n\r\n miu_s = 0\r\n for k in range(self.pt_count):\r\n if i == self.dst_pts[k][0] and j == self.dst_pts[k][1]:\r\n continue\r\n pt_i = self.dst_pts[k] - pstar\r\n miu_s += w[k] * np.sum(pt_i * pt_i)\r\n\r\n cur_pt -= pstar\r\n cur_pt_j = np.array([-cur_pt[1], cur_pt[0]])\r\n\r\n for k in range(self.pt_count):\r\n if i == self.dst_pts[k][0] and j == self.dst_pts[k][1]:\r\n continue\r\n\r\n pt_i = self.dst_pts[k] - pstar\r\n pt_j = np.array([-pt_i[1], pt_i[0]])\r\n\r\n tmp_pt = np.zeros(2, dtype=np.float32)\r\n tmp_pt[0] = np.sum(pt_i * cur_pt) * self.src_pts[k][0] - \\\r\n np.sum(pt_j * cur_pt) * self.src_pts[k][1]\r\n tmp_pt[1] = -np.sum(pt_i * cur_pt_j) * self.src_pts[k][0] + \\\r\n np.sum(pt_j * cur_pt_j) * self.src_pts[k][1]\r\n tmp_pt *= (w[k] / miu_s)\r\n new_pt += tmp_pt\r\n\r\n new_pt += qstar\r\n else:\r\n new_pt = self.src_pts[k]\r\n\r\n self.rdx[j, i] = new_pt[0] - i\r\n self.rdy[j, i] = new_pt[1] - j\r\n\r\n j += self.grid_size\r\n i += self.grid_size\r\n\r\n def gen_img(self):\r\n src_h, src_w = self.src.shape[:2]\r\n dst = np.zeros_like(self.src, dtype=np.float32)\r\n\r\n for i in np.arange(0, self.dst_h, self.grid_size):\r\n for j in np.arange(0, self.dst_w, self.grid_size):\r\n ni = i + self.grid_size\r\n nj = j + self.grid_size\r\n w = h = self.grid_size\r\n if ni >= self.dst_h:\r\n ni = self.dst_h - 1\r\n h = ni - i + 1\r\n if nj >= self.dst_w:\r\n nj = self.dst_w - 1\r\n w = nj - j + 1\r\n\r\n di = np.reshape(np.arange(h), (-1, 1))\r\n dj = np.reshape(np.arange(w), (1, -1))\r\n delta_x = self.__bilinear_interp(di / h, dj / w,\r\n self.rdx[i, j], self.rdx[i, nj],\r\n self.rdx[ni, j], self.rdx[ni, nj])\r\n delta_y = self.__bilinear_interp(di / h, dj / w,\r\n self.rdy[i, j], self.rdy[i, nj],\r\n self.rdy[ni, j], self.rdy[ni, nj])\r\n nx = j + dj + delta_x * self.trans_ratio\r\n ny = i + di + delta_y * self.trans_ratio\r\n nx = np.clip(nx, 0, src_w - 1)\r\n ny = np.clip(ny, 0, src_h - 1)\r\n nxi = np.array(np.floor(nx), dtype=np.int32)\r\n nyi = np.array(np.floor(ny), dtype=np.int32)\r\n nxi1 = np.array(np.ceil(nx), dtype=np.int32)\r\n nyi1 = np.array(np.ceil(ny), dtype=np.int32)\r\n\r\n dst[i:i + h, j:j + w] = self.__bilinear_interp(np.tile(np.expand_dims(ny - nyi, axis=-1), (1, 1, 3)),\r\n np.tile(np.expand_dims(nx - nxi, axis=-1), (1, 1, 3)),\r\n self.src[nyi, nxi],\r\n self.src[nyi, nxi1],\r\n self.src[nyi1, nxi],\r\n self.src[nyi1, nxi1]\r\n )\r\n\r\n # for di in range(h):\r\n # for dj in range(w):\r\n # # print(ni, nj, i, j)\r\n # delta_x = self.__bilinear_interp(di / h, dj / w, self.rdx[i, j], self.rdx[i, nj],\r\n # self.rdx[ni, j], self.rdx[ni, nj])\r\n # delta_y = self.__bilinear_interp(di / h, dj / w, self.rdy[i, j], self.rdy[i, nj],\r\n # self.rdy[ni, j], self.rdy[ni, nj])\r\n # nx = j + dj + delta_x * self.trans_ratio\r\n # ny = i + di + delta_y * self.trans_ratio\r\n # nx = min(src_w - 1, max(0, nx))\r\n # ny = min(src_h - 1, max(0, ny))\r\n # nxi = int(nx)\r\n # nyi = int(ny)\r\n # nxi1 = math.ceil(nx)\r\n # nyi1 = math.ceil(ny)\r\n #\r\n # dst[i + di, j + dj] = self.__bilinear_interp(ny - nyi, nx - nxi,\r\n # self.src[nyi, nxi],\r\n # self.src[nyi, nxi1],\r\n # self.src[nyi1, nxi],\r\n # self.src[nyi1, nxi1]\r\n # )\r\n\r\n dst = np.clip(dst, 0, 255)\r\n dst = np.array(dst, dtype=np.uint8)\r\n\r\n return dst\r\n"
] | [
[
"numpy.zeros_like",
"numpy.sum",
"numpy.ceil",
"numpy.zeros",
"numpy.floor",
"numpy.arange",
"numpy.clip",
"numpy.expand_dims",
"numpy.array"
]
] |
juancastillo0/tfjs | [
"a53aae8fd99762ab41a25ac362ece95b4bbb8cf6"
] | [
"tfjs-converter/python/tensorflowjs/converters/fold_batch_norms.py"
] | [
"# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Folding the BatchNorm op into Conv2D.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\n\nimport numpy as np\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.core.framework import graph_pb2\nfrom tensorflow.core.framework import node_def_pb2\nfrom tensorflow.python.framework import tensor_util\nfrom tensorflow.python.platform import tf_logging\n\nfrom tensorflowjs.converters import graph_rewrite_util\n\nINPUT_ORDER = {\n # Order of inputs for BatchNormWithGlobalNormalization.\n \"BatchNormWithGlobalNormalization\": [\n \"conv_op\", \"mean_op\", \"var_op\", \"beta_op\", \"gamma_op\"\n ],\n # Order of inputs for FusedBatchNorm.\n \"FusedBatchNorm\": [\"conv_op\", \"gamma_op\", \"beta_op\", \"mean_op\", \"var_op\"],\n # Order of inputs for FusedBatchNormV3.\n \"FusedBatchNormV3\": [\"conv_op\", \"gamma_op\", \"beta_op\", \"mean_op\", \"var_op\"]\n}\n# Name of the attribute epsilon value is stored in.\nEPSILON_ATTR = {\n \"BatchNormWithGlobalNormalization\": \"variance_epsilon\",\n \"FusedBatchNorm\": \"epsilon\",\n \"FusedBatchNormV3\": \"epsilon\"\n}\n\n# pylint: disable=R0915\ndef fold_batch_norms(input_graph_def):\n \"\"\"Removes batch normalization ops by folding them into convolutions.\n\n Batch normalization during training has multiple dynamic parameters that are\n updated, but once the graph is finalized these become constants. That means\n there's an opportunity to reduce the computations down to a scale and\n addition, rather than the more expensive multiple ops, and even bake the\n scaling into the convolution weights. This function identifies the typical\n pattern of batch normalization subgraphs, and performs the transformation to\n fold the computations down into a simpler form. It currently only supports\n batch normalization that's performed by the BatchNormWithGlobalNormalization\n FusedBatchNorm and FusedBatchNormV3 ops, and will need to be extended in the\n future to handle the newer style.\n\n Args:\n input_graph_def: A GraphDef containing a model.\n\n Returns:\n Modified graph with BN ops removed, and modified weights.\n\n Raises:\n ValueError: If the graph is badly formed with duplicate node names.\n \"\"\"\n input_node_map = {}\n for node in input_graph_def.node:\n if node.name not in input_node_map:\n input_node_map[node.name] = node\n else:\n raise ValueError(\"Duplicate node names detected for \", node.name)\n\n nodes_to_skip = {}\n new_ops = []\n for node in input_graph_def.node:\n if (node.op not in (\"BatchNormWithGlobalNormalization\",\n \"FusedBatchNorm\", \"FusedBatchNormV3\")):\n continue\n\n bias = None\n conv_op = graph_rewrite_util.node_from_map(\n input_node_map,\n node.input[INPUT_ORDER[node.op].index(\"conv_op\")])\n # There might be an Add/BiasAdd op between the conv and the batchnorm,\n # which we can fold into the mean param of the batchnorm.\n if conv_op.op in ['BiasAdd', 'Add', 'AddV2']:\n add_op = conv_op\n # Follow the first input of the add to get to the conv.\n conv_op = graph_rewrite_util.node_from_map(\n input_node_map, add_op.input[0])\n bias = graph_rewrite_util.node_from_map(input_node_map, add_op.input[1])\n if conv_op.op not in [\"Conv2D\", \"DepthwiseConv2dNative\"]:\n # Follow the second input of the add to get to the conv.\n conv_op = graph_rewrite_util.node_from_map(\n input_node_map, add_op.input[1])\n bias = graph_rewrite_util.node_from_map(input_node_map, add_op.input[0])\n if bias and bias.op != 'Const':\n tf_logging.warning(\"The bias %s after the conv %s was not a constant. \"\n \"Maybe because freeze_graph wasn't \"\n \"run first?\" % (bias.name, conv_op.name))\n continue\n if conv_op.op not in [\"Conv2D\", \"DepthwiseConv2dNative\"]:\n tf_logging.warning(\"Didn't find expected Conv2D or DepthwiseConv2dNative\"\n \" input to '%s'\" % node.name)\n continue\n weights_op = graph_rewrite_util.node_from_map(\n input_node_map, conv_op.input[1])\n if weights_op.op != \"Const\":\n tf_logging.warning(\"Didn't find expected conv Constant input to '%s',\"\n \" found %s instead. Maybe because freeze_graph wasn't\"\n \" run first?\" % (conv_op.name, weights_op))\n continue\n weights = graph_rewrite_util.values_from_const(weights_op)\n if conv_op.op == \"Conv2D\":\n channel_count = weights.shape[3]\n elif conv_op.op == \"DepthwiseConv2dNative\":\n channel_count = weights.shape[2] * weights.shape[3]\n\n mean_op = graph_rewrite_util.node_from_map(\n input_node_map,\n node.input[INPUT_ORDER[node.op].index(\"mean_op\")])\n if mean_op.op != \"Const\":\n tf_logging.warning(\"Didn't find expected mean Constant input to '%s',\"\n \" found %s instead. Maybe because freeze_graph wasn't\"\n \" run first?\" % (node.name, mean_op))\n continue\n mean_value = graph_rewrite_util.values_from_const(mean_op)\n if bias is not None:\n # Adjust the mean of the batchnorm based on the add op in-between the conv\n # and the batchnorm.\n mean_value = mean_value - graph_rewrite_util.values_from_const(bias)\n if mean_value.shape != (channel_count,):\n tf_logging.warning(\"Incorrect shape for mean, found %s, expected %s,\"\n \" for node %s\" % (str(mean_value.shape), str(\n (channel_count,)), node.name))\n continue\n\n var_op = graph_rewrite_util.node_from_map(\n input_node_map,\n node.input[INPUT_ORDER[node.op].index(\"var_op\")])\n if var_op.op != \"Const\":\n tf_logging.warning(\"Didn't find expected var Constant input to '%s',\"\n \" found %s instead. Maybe because freeze_graph wasn't\"\n \" run first?\" % (node.name, var_op))\n continue\n var_value = graph_rewrite_util.values_from_const(var_op)\n if var_value.shape != (channel_count,):\n tf_logging.warning(\"Incorrect shape for var, found %s, expected %s,\"\n \" for node %s\" % (str(var_value.shape), str(\n (channel_count,)), node.name))\n continue\n\n beta_op = graph_rewrite_util.node_from_map(\n input_node_map,\n node.input[INPUT_ORDER[node.op].index(\"beta_op\")])\n if beta_op.op != \"Const\":\n tf_logging.warning(\"Didn't find expected beta Constant input to '%s',\"\n \" found %s instead. Maybe because freeze_graph wasn't\"\n \" run first?\" % (node.name, beta_op))\n continue\n beta_value = graph_rewrite_util.values_from_const(beta_op)\n if beta_value.shape != (channel_count,):\n tf_logging.warning(\"Incorrect shape for beta, found %s, expected %s,\"\n \" for node %s\" % (str(beta_value.shape), str(\n (channel_count,)), node.name))\n continue\n\n gamma_op = graph_rewrite_util.node_from_map(\n input_node_map,\n node.input[INPUT_ORDER[node.op].index(\"gamma_op\")])\n if gamma_op.op != \"Const\":\n tf_logging.warning(\"Didn't find expected gamma Constant input to '%s',\"\n \" found %s instead. Maybe because freeze_graph wasn't\"\n \" run first?\" % (node.name, gamma_op))\n continue\n gamma_value = graph_rewrite_util.values_from_const(gamma_op)\n if gamma_value.shape != (channel_count,):\n tf_logging.warning(\"Incorrect shape for gamma, found %s, expected %s,\"\n \" for node %s\" % (str(gamma_value.shape), str(\n (channel_count,)), node.name))\n continue\n\n variance_epsilon_value = node.attr[EPSILON_ATTR[node.op]].f\n nodes_to_skip[node.name] = True\n nodes_to_skip[weights_op.name] = True\n nodes_to_skip[conv_op.name] = True\n if bias is not None:\n nodes_to_skip[add_op.name] = True\n\n if scale_after_normalization(node):\n scale_value = (\n (1.0 / np.vectorize(math.sqrt)(var_value + variance_epsilon_value)) *\n gamma_value)\n else:\n scale_value = (\n 1.0 / np.vectorize(math.sqrt)(var_value + variance_epsilon_value))\n offset_value = (-mean_value * scale_value) + beta_value\n scaled_weights = np.copy(weights)\n it = np.nditer(\n scaled_weights, flags=[\"multi_index\"], op_flags=[\"readwrite\"])\n if conv_op.op == \"Conv2D\":\n while not it.finished:\n current_scale = scale_value[it.multi_index[3]]\n it[0] *= current_scale\n it.iternext()\n elif conv_op.op == \"DepthwiseConv2dNative\":\n channel_multiplier = weights.shape[3]\n while not it.finished:\n current_scale = scale_value[it.multi_index[2] * channel_multiplier +\n it.multi_index[3]]\n it[0] *= current_scale\n it.iternext()\n scaled_weights_op = node_def_pb2.NodeDef()\n scaled_weights_op.op = \"Const\"\n scaled_weights_op.name = conv_op.name + '_weights'\n scaled_weights_op.attr[\"dtype\"].CopyFrom(weights_op.attr[\"dtype\"])\n scaled_weights_op.attr[\"value\"].CopyFrom(\n attr_value_pb2.AttrValue(tensor=tensor_util.make_tensor_proto(\n scaled_weights, weights.dtype.type, weights.shape)))\n # Replace the weights node with scaled weights node\n for i, weights_node in enumerate(conv_op.input):\n if weights_node == weights_op.name:\n conv_op.input[i] = scaled_weights_op.name\n\n new_conv_op = node_def_pb2.NodeDef()\n new_conv_op.CopyFrom(conv_op)\n offset_op = node_def_pb2.NodeDef()\n offset_op.op = \"Const\"\n offset_op.name = conv_op.name + \"_bn_offset\"\n offset_op.attr[\"dtype\"].CopyFrom(mean_op.attr[\"dtype\"])\n offset_op.attr[\"value\"].CopyFrom(\n attr_value_pb2.AttrValue(tensor=tensor_util.make_tensor_proto(\n offset_value, mean_value.dtype.type, offset_value.shape)))\n bias_add_op = node_def_pb2.NodeDef()\n bias_add_op.op = \"BiasAdd\"\n bias_add_op.name = node.name\n bias_add_op.attr[\"T\"].CopyFrom(conv_op.attr[\"T\"])\n bias_add_op.attr[\"data_format\"].CopyFrom(conv_op.attr[\"data_format\"])\n bias_add_op.input.extend([new_conv_op.name, offset_op.name])\n new_ops.extend([scaled_weights_op, new_conv_op, offset_op, bias_add_op])\n\n result_graph_def = graph_pb2.GraphDef()\n for node in input_graph_def.node:\n if node.name in nodes_to_skip:\n continue\n new_node = node_def_pb2.NodeDef()\n new_node.CopyFrom(node)\n retained_input = []\n for input_node in new_node.input:\n if not input_node.startswith('^') or input_node[1:] not in nodes_to_skip:\n retained_input.append(input_node)\n new_node.input[:] = retained_input\n\n result_graph_def.node.extend([new_node])\n\n result_graph_def.node.extend(new_ops)\n result_graph_def.library.CopyFrom(input_graph_def.library)\n result_graph_def.versions.CopyFrom(input_graph_def.versions)\n return result_graph_def\n\n# Whether to scale by gamma after normalization.\ndef scale_after_normalization(node):\n if node.op == \"BatchNormWithGlobalNormalization\":\n return node.attr[\"scale_after_normalization\"].b\n return True\n"
] | [
[
"numpy.vectorize",
"numpy.copy",
"numpy.nditer",
"tensorflow.core.framework.node_def_pb2.NodeDef",
"tensorflow.python.framework.tensor_util.make_tensor_proto",
"tensorflow.python.platform.tf_logging.warning",
"tensorflow.core.framework.graph_pb2.GraphDef"
]
] |
PYH-torder/robot-test | [
"381df1e8911d8ca43c2a57613a7a75e674fea7b6"
] | [
"source/mq/dyccon.py"
] | [
"import sys\nimport time\nimport os\nimport config\nimport setmq\nfrom socket import *\nimport numpy as np\nimport time\nimport binascii\n\n#๋์์ปคํผ๋จธ์ ์ํ ๊ฐ์ ธ์ค๊ธฐ\nhost = \"192.168.103.140\"\ngseq = 0\ngcrc_16 = 0x8005\ntable_crc = []\n\ndef buildTable16(aPoly):\n for i in range(0, 256):\n data = np.uint16(i << 8)\n accum = 0\n for j in range(0, 8):\n if(((data ^ accum) & 0x8000) != 0):\n accum = np.uint16((accum << 1) ^ np.uint16(aPoly))\n else:\n accum <<= 1\n data <<= 1\n\n table_crc.append(np.uint16(accum))\n \n # print(table_crc)\n\ndef crc_16(data):\n accum = 0\n for i in range(0, len(data)):\n accum = np.uint16(accum << 8) ^ table_crc[(accum >> 8) ^ data[i]]\n\n return accum\n\nbuildTable16(gcrc_16)\n\ndef sendPacket(cmd, data, hport):\n global gseq, host\n\n gseq = (gseq + 1) % 256\n\n tmp = b'\\x02' # stx\n tmp += bytes([gseq]) # seq\n tmp += b'\\x0B' # sender id\n tmp += b'\\x01' # sender idx\n tmp += b'\\x0E' # receiver id\n tmp += b'\\x01' # receiver idx\n tmp += cmd\n tmp += bytes([int(len(data) / 256)])\n tmp += bytes([int(len(data) % 256)])\n if(data != b''):\n tmp += data\n \n tmp2 = b''\n for i in range(1, len(data) + 9):\n tmp2 += bytes([tmp[i]])\n\n tmp3 = crc_16(tmp2)\n\n tmp4 = int(tmp3 / 256)\n tmp5 = int(tmp3 % 256)\n\n tmp += bytes([int(tmp4)])\n tmp += bytes([int(tmp5)])\n\n tmp += b'\\x03'\n\n print(\"request data :: \", binascii.hexlify(tmp))\n\n try:\n clso = socket(AF_INET, SOCK_STREAM)\n clso.connect((host, hport))\n print(\"connect\")\n\n clso.send(tmp)\n print(\"send message\")\n\n data = clso.recv(2028)\n print(\"response data :: \", binascii.hexlify(data))\n\n clso.close()\n except:\n print(sys.exc_info())\n return \"\"\n else:\n return binascii.hexlify(data)\n\n\ndef order(order):\n\n try_count = 0\n rtnval = {\n \"code\" : 200,\n \"msg\" : \"ok\",\n \"result\" : b''\n }\n\n while True:\n try:\n if(order == \"cup0\"): #์ผ๋ฐ์ปต\n rtn2 = sendPacket(b'\\xB4', b'\\x11', 10201)\n if(rtn2[18:20] == b'00'):\n return rtnval\n break\n elif(order == \"cup1\"): #์ผ์์ปต\n rtn2 = sendPacket(b'\\xB4', b'\\x12', 10201)\n if(rtn2[18:20] == b'00'):\n time.sleep(2)\n rtn3 = sendPacket(b'\\xB4', b'\\x13\\x21', 10201)\n\n if(rtn3[18:20] == b'00'):\n return rtnval\n break\n\n elif(order == \"cup2\"): #์ผ์\n rtn = sendPacket(b'\\xB4', b'\\x13\\x21', 10201)\n if(rtn[18:20] == b'00'):\n return rtnval\n break\n\n elif(order == \"cup3\"): #์ผ์์ปต 1/2\n rtn2 = sendPacket(b'\\xB4', b'\\x12', 10201)\n if(rtn2[18:20] == b'00'):\n time.sleep(2)\n rtn3 = sendPacket(b'\\xB4', b'\\x13\\x1b', 10201)\n\n if(rtn3[18:20] == b'00'):\n return rtnval\n break\n \n elif(order == \"ade1\"): #ade1\n print(\"start ade 1 : valve\")\n rtn2 = sendPacket(b'\\xB7', b'\\x27\\x01\\x65', 10202)\n time.sleep(1)\n rtn4 = sendPacket(b'\\xB5', b'\\x26\\x01\\x15', 10200)\n time.sleep(3)\n print(\"\\nstart ade 1 : make\")\n rtn3 = sendPacket(b'\\xB5', b'\\x21\\x00\\x19', 10200)\n\n if(rtn2[18:20] == b'00' and rtn3[18:20] == b'00' and rtn4[18:20] == b'00'):\n time.sleep(5)\n rtn4 = sendPacket(b'\\xB5', b'\\x26\\x01\\x10', 10200)\n\n if(rtn4[18:20] == b'00'):\n return rtnval\n break\n else:\n rtnval[\"code\"] = 601\n rtnval[\"message\"] = \"ade make error\"\n return rtnval\n break\n\n elif(order == \"ade2\"): #ade2\n print(\"start ade 2 : valve\")\n rtn2 = sendPacket(b'\\xB7', b'\\x27\\x02\\x65', 10202)\n time.sleep(1)\n rtn4 = sendPacket(b'\\xB5', b'\\x26\\x02\\x10', 10200)\n time.sleep(3)\n print(\"\\nstart ade 2 : make\")\n rtn3 = sendPacket(b'\\xB5', b'\\x22\\x00\\x19', 10200)\n\n if(rtn2[18:20] == b'00' and rtn3[18:20] == b'00' and rtn4[18:20] == b'00'):\n time.sleep(5)\n rtn4 = sendPacket(b'\\xB5', b'\\x26\\x02\\x10', 10200)\n\n if(rtn4[18:20] == b'00'):\n return rtnval\n break\n else:\n rtnval[\"code\"] = 601\n rtnval[\"message\"] = \"ade make error\"\n return rtnval\n break\n\n elif(order == \"ade3\"): #ade3\n print(\"start ade 3 : valve\")\n rtn2 = sendPacket(b'\\xB7', b'\\x27\\x03\\x65', 10202)\n time.sleep(1)\n rtn4 = sendPacket(b'\\xB5', b'\\x26\\x05\\x15', 10200)\n time.sleep(3)\n print(\"\\nstart ade 3 : make\")\n rtn3 = sendPacket(b'\\xB5', b'\\x23\\x00\\x19', 10200)\n\n if(rtn2[18:20] == b'00' and rtn3[18:20] == b'00' and rtn4[18:20] == b'00'):\n time.sleep(5)\n rtn4 = sendPacket(b'\\xB5', b'\\x26\\x05\\x10', 10200)\n\n if(rtn4[18:20] == b'00'):\n return rtnval\n break\n else:\n rtnval[\"code\"] = 601\n rtnval[\"message\"] = \"ade make error\"\n return rtnval\n break\n\n elif(order == \"ade4\"): #ade4\n print(\"start ade 4 : valve\")\n rtn2 = sendPacket(b'\\xB7', b'\\x27\\x04\\x65', 10202)\n time.sleep(1)\n rtn4 = sendPacket(b'\\xB5', b'\\x26\\x04\\x15', 10200)\n time.sleep(3)\n print(\"\\nstart ade 4 : make\")\n rtn3 = sendPacket(b'\\xB5', b'\\x24\\x00\\x19', 10200)\n\n if(rtn2[18:20] == b'00' and rtn3[18:20] == b'00' and rtn4[18:20] == b'00'):\n time.sleep(6)\n rtn4 = sendPacket(b'\\xB5', b'\\x26\\x04\\x10', 10200)\n\n if(rtn4[18:20] == b'00'):\n return rtnval\n break\n else:\n rtnval[\"code\"] = 601\n rtnval[\"message\"] = \"ade make error\"\n return rtnval\n break\n\n elif(order == \"ade5\"): #ade5\n print(\"start ade 5 : valve\")\n rtn2 = sendPacket(b'\\xB7', b'\\x27\\x05\\x65', 10202)\n time.sleep(1)\n rtn4 = sendPacket(b'\\xB5', b'\\x26\\x03\\x15', 10200)\n time.sleep(3)\n print(\"\\nstart ade 5 : make\")\n rtn3 = sendPacket(b'\\xB5', b'\\x25\\x00\\x19', 10200)\n if(rtn2[18:20] == b'00' and rtn3[18:20] == b'00' and rtn4[18:20] == b'00'):\n time.sleep(6)\n rtn4 = sendPacket(b'\\xB5', b'\\x26\\x03\\x10', 10200)\n\n if(rtn4[18:20] == b'00'):\n return rtnval\n break\n else:\n rtnval[\"code\"] = 601\n rtnval[\"message\"] = \"ade make error\"\n return rtnval\n break\n \n elif(order == \"spacle\"): #clear\n print(\"start clear\")\n\n rtn2 = sendPacket(b'\\xB7', b'\\x27\\x02\\x30', 10202)\n if(rtn2[18:20] == b'00'):\n time.sleep(1)\n print(\"\\nade Make Start\")\n rtn4 = sendPacket(b'\\xB5', b'\\x26\\x02\\x25', 10200)\n\n if(rtn4[18:20] == b'00'):\n return rtnval\n break\n else:\n rtnval[\"code\"] = 601\n rtnval[\"message\"] = \"ade make error\"\n return rtnval\n break\n\n elif(order == \"coffee\"): \n sendPacket(b'\\xB9', b'\\x00\\x00\\x00\\x80', 10203)\n time.sleep(1)\n rtn2 = sendPacket(b'\\xB6', b'\\x04\\x02\\x41\\x4d\\x65\\x00\\x60\\x00\\x40\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', 10203)\n if(rtn2[18:20] == b'00'):\n return rtnval\n break\n elif(order == \"coffeedouble\"):\n sendPacket(b'\\xB9', b'\\x00\\x00\\x00\\x80', 10203)\n time.sleep(2)\n rtn2 = sendPacket(b'\\xB6', b'\\x04\\x02\\x41\\x4d\\x69\\x00\\x40\\x00\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', 10203)\n if(rtn2[18:20] == b'00'):\n return rtnval\n break\n elif(order == \"espresso\"):\n sendPacket(b'\\xB9', b'\\x00\\x00\\x00\\x80', 10203)\n time.sleep(1)\n rtn2 = sendPacket(b'\\xB6', b'\\x04\\x02\\x41\\x4d\\x50\\x00\\x30\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', 10203)\n if(rtn2[18:20] == b'00'):\n return rtnval\n break\n elif(order == \"coffeeice\"):\n sendPacket(b'\\xB9', b'\\x00\\x00\\x00\\x80', 10203)\n time.sleep(1)\n rtn2 = sendPacket(b'\\xB6', b'\\x04\\x02\\x49\\x41\\x65\\x00\\x40\\x00\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', 10203)\n if(rtn2[18:20] == b'00'):\n return rtnval\n break\n elif(order == \"hotchoco\"):\n sendPacket(b'\\xB9', b'\\x00\\x00\\x00\\x80', 10203)\n time.sleep(1)\n rtn2 = sendPacket(b'\\xB6', b'\\x04\\x02\\x43\\x4d\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x40\\x00\\x85\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', 10203)\n if(rtn2[18:20] == b'00'):\n return rtnval\n break\n elif(order == \"capuccino\"):\n sendPacket(b'\\xB9', b'\\x00\\x00\\x00\\x80', 10203)\n time.sleep(1)\n rtn2 = sendPacket(b'\\xB6', b'\\x04\\x02\\x43\\x41\\x65\\x00\\x50\\x00\\x00\\x00\\x02\\x00\\x30\\x00\\x00\\x00\\x00\\x00\\x30\\x00\\x30\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', 10203)\n if(rtn2[18:20] == b'00'):\n return rtnval\n break\n elif(order == \"latte\"):\n sendPacket(b'\\xB9', b'\\x00\\x00\\x00\\x80', 10203)\n time.sleep(1)\n rtn2 = sendPacket(b'\\xB6', b'\\x04\\x02\\x43\\x4d\\x65\\x00\\x50\\x00\\x00\\x00\\x02\\x00\\x30\\x00\\x00\\x00\\x00\\x00\\x30\\x00\\x30\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', 10203)\n if(rtn2[18:20] == b'00'):\n return rtnval\n break\n elif(order == \"lattenosugar\"):\n sendPacket(b'\\xB9', b'\\x00\\x00\\x00\\x80', 10203)\n time.sleep(1)\n rtn2 = sendPacket(b'\\xB6', b'\\x04\\x02\\x43\\x4d\\x65\\x00\\x50\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x10\\x00\\x35\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', 10203)\n if(rtn2[18:20] == b'00'):\n return rtnval\n break\n elif(order == \"mocha\"):\n sendPacket(b'\\xB9', b'\\x00\\x00\\x00\\x80', 10203)\n time.sleep(1)\n rtn2 = sendPacket(b'\\xB6', b'\\x04\\x02\\x43\\x4d\\x65\\x00\\x50\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x15\\x00\\x00\\x00\\x18\\x00\\x40\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', 10203)\n if(rtn2[18:20] == b'00'):\n return rtnval\n break\n\n except:\n print(\"error\")\n \n try_count = try_count + 1\n\n if(try_count > 40):\n rtnval[\"code\"] = 900\n rtnval[\"data\"] = \"time out\"\n return rtnval\n break\n\n time.sleep(1)\n \n # while True:\n\n# def order(order):\n\ndef status():\n cup = 1\n cupout = 1\n icup = 1\n icupout = 1\n coffee = 1\n ade = 1\n rtnval = \"Ready\"\n\n rtn = sendPacket(b'\\xB1', b'\\x10', 10201) \n if(rtn[18:20] == b'01'):\n if(rtn[20:22] == b'00'):\n rtnval = \"CupEmpty\"\n\n if(rtn[22:24] == b'01'):\n rtnval = \"CupOut\"\n\n if(rtn[24:26] == b'00'):\n rtnval = \"IcecupEmpty\"\n \n if(rtn[26:28] == b'01'):\n rtnval = \"IcecupEmpty\"\n\n rtn2 = sendPacket(b'\\xB2', b'', 10203)\n if(rtn2[18:20] == b'ff'):\n rtnval = \"CoffeeError\"\n\n rtn3 = sendPacket(b'\\xB2', b'', 10200)\n if(rtn3[18:20] == b'21'):\n rtnval = \"AdeError\"\n\n rtn4 = sendPacket(b'\\xB2', b'', 10202)\n if(rtn4[18:20] == b'21'):\n rtnval = \"AdeError\"\n\n return rtnval\n\n# def status():\n\n\n# print(order(\"cup1\"))\n# print(order(\"coffeedouble\"))"
] | [
[
"numpy.uint16"
]
] |
AkshayJainG/veles | [
"21106f41a8e7e7e74453cd16a5059a0e6b1c315e"
] | [
"veles/tests/test_velescli.py"
] | [
"# -*- coding: utf-8 -*-\n\"\"\"\n.. invisible:\n _ _ _____ _ _____ _____\n | | | | ___| | | ___/ ___|\n | | | | |__ | | | |__ \\ `--.\n | | | | __|| | | __| `--. \\\n \\ \\_/ / |___| |___| |___/\\__/ /\n \\___/\\____/\\_____|____/\\____/\n\nCreated on Jun 9, 2014\n\nโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ\n\nLicensed to the Apache Software Foundation (ASF) under one\nor more contributor license agreements. See the NOTICE file\ndistributed with this work for additional information\nregarding copyright ownership. The ASF licenses this file\nto you under the Apache License, Version 2.0 (the\n\"License\"); you may not use this file except in compliance\nwith the License. You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing,\nsoftware distributed under the License is distributed on an\n\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, either express or implied. See the License for the\nspecific language governing permissions and limitations\nunder the License.\n\nโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ\n\"\"\"\n\n\nimport numpy\nimport os\nimport struct\nimport sys\nimport tempfile\nimport unittest\n\nfrom veles.__main__ import Main\nimport veles.prng as rnd\nfrom veles.workflow import Workflow\n\n\nclass Test(unittest.TestCase):\n def setUp(self):\n self.main = Main(True, \"workflow\", \"config\")\n\n def testSeeding(self):\n _, fname = tempfile.mkstemp(prefix=\"veles-test-seed-\")\n with open(fname, 'wb') as fw:\n for i in range(100):\n fw.write(struct.pack('i', i))\n self.main._seed_random(fname + \":100\")\n state1 = numpy.random.get_state()\n arr1 = numpy.empty(100)\n rnd.get().fill(arr1)\n self.main._seed_random(fname + \":100\")\n state2 = numpy.random.get_state()\n try:\n self.assertTrue((state1[1] == state2[1]).all())\n arr2 = numpy.empty(100)\n rnd.get().fill(arr2)\n self.assertTrue((arr1 == arr2).all())\n except AssertionError:\n os.remove(fname)\n raise\n\n def testRun(self):\n argv = sys.argv\n sys.argv = [argv[0], \"-s\", \"-p\", \"\", \"-v\", \"debug\", __file__, __file__]\n self.main = Main()\n self.main.run()\n self.assertTrue(Workflow.run_was_called)\n\n def test_format_decimal(self):\n fd = Main.format_decimal\n res = fd(1047151)\n self.assertEqual(res, \"1 047 151\")\n res = fd(45)\n self.assertEqual(res, \"45\")\n res = fd(145)\n self.assertEqual(res, \"145\")\n res = fd(1145)\n self.assertEqual(res, \"1 145\")\n res = fd(12345)\n self.assertEqual(res, \"12 345\")\n\n def testSetupLogging(self):\n # Multiple calls test\n self.main.setup_logging(\"debug\")\n self.main.setup_logging(\"debug\")\n\n\ndef run(load, main):\n wf, _ = load(Workflow)\n wf.end_point.link_from(wf.start_point)\n main()\n Workflow.run_was_called = True\n\nif __name__ == \"__main__\":\n # import sys;sys.argv = ['', 'Test.testSeeding']\n unittest.main()\n"
] | [
[
"numpy.empty",
"numpy.random.get_state"
]
] |
Xia-Sam/pandas | [
"74748b9967d102e8c91ad2ef96733c0c1dc98821"
] | [
"pandas/core/indexes/category.py"
] | [
"import operator\nimport warnings\n\nimport numpy as np\n\nfrom pandas._libs import index as libindex\nimport pandas.compat as compat\nfrom pandas.compat.numpy import function as nv\nfrom pandas.util._decorators import Appender, cache_readonly\n\nfrom pandas.core.dtypes.common import (\n ensure_platform_int, is_categorical_dtype, is_interval_dtype, is_list_like,\n is_scalar)\nfrom pandas.core.dtypes.dtypes import CategoricalDtype\nfrom pandas.core.dtypes.generic import ABCCategorical, ABCSeries\nfrom pandas.core.dtypes.missing import isna\n\nfrom pandas.core import accessor\nfrom pandas.core.algorithms import take_1d\nfrom pandas.core.arrays.categorical import Categorical, contains\nimport pandas.core.common as com\nfrom pandas.core.config import get_option\nimport pandas.core.indexes.base as ibase\nfrom pandas.core.indexes.base import Index, _index_shared_docs\nimport pandas.core.missing as missing\nfrom pandas.core.ops import get_op_result_name\n\n_index_doc_kwargs = dict(ibase._index_doc_kwargs)\n_index_doc_kwargs.update(dict(target_klass='CategoricalIndex'))\n\n\[email protected]_names(\n delegate=Categorical,\n accessors=[\"rename_categories\",\n \"reorder_categories\",\n \"add_categories\",\n \"remove_categories\",\n \"remove_unused_categories\",\n \"set_categories\",\n \"as_ordered\", \"as_unordered\",\n \"min\", \"max\"],\n typ='method', overwrite=True)\nclass CategoricalIndex(Index, accessor.PandasDelegate):\n \"\"\"\n Immutable Index implementing an ordered, sliceable set. CategoricalIndex\n represents a sparsely populated Index with an underlying Categorical.\n\n Parameters\n ----------\n data : array-like or Categorical, (1-dimensional)\n categories : optional, array-like\n categories for the CategoricalIndex\n ordered : boolean,\n designating if the categories are ordered\n copy : bool\n Make a copy of input ndarray\n name : object\n Name to be stored in the index\n\n Attributes\n ----------\n codes\n categories\n ordered\n\n Methods\n -------\n rename_categories\n reorder_categories\n add_categories\n remove_categories\n remove_unused_categories\n set_categories\n as_ordered\n as_unordered\n map\n\n See Also\n --------\n Categorical, Index\n \"\"\"\n\n _typ = 'categoricalindex'\n\n @property\n def _engine_type(self):\n # self.codes can have dtype int8, int16, int32 or int64, so we need\n # to return the corresponding engine type (libindex.Int8Engine, etc.).\n return {np.int8: libindex.Int8Engine,\n np.int16: libindex.Int16Engine,\n np.int32: libindex.Int32Engine,\n np.int64: libindex.Int64Engine,\n }[self.codes.dtype.type]\n\n _attributes = ['name']\n\n # --------------------------------------------------------------------\n # Constructors\n\n def __new__(cls, data=None, categories=None, ordered=None, dtype=None,\n copy=False, name=None, fastpath=None):\n\n if fastpath is not None:\n warnings.warn(\"The 'fastpath' keyword is deprecated, and will be \"\n \"removed in a future version.\",\n FutureWarning, stacklevel=2)\n if fastpath:\n return cls._simple_new(data, name=name, dtype=dtype)\n\n dtype = CategoricalDtype._from_values_or_dtype(data, categories,\n ordered, dtype)\n\n if name is None and hasattr(data, 'name'):\n name = data.name\n\n if not is_categorical_dtype(data):\n # don't allow scalars\n # if data is None, then categories must be provided\n if is_scalar(data):\n if data is not None or categories is None:\n cls._scalar_data_error(data)\n data = []\n\n data = cls._create_categorical(data, dtype=dtype)\n\n data = data.copy() if copy else data\n\n return cls._simple_new(data, name=name)\n\n def _create_from_codes(self, codes, dtype=None, name=None):\n \"\"\"\n *this is an internal non-public method*\n\n create the correct categorical from codes\n\n Parameters\n ----------\n codes : new codes\n dtype: CategoricalDtype, defaults to existing\n name : optional name attribute, defaults to existing\n\n Returns\n -------\n CategoricalIndex\n \"\"\"\n\n if dtype is None:\n dtype = self.dtype\n if name is None:\n name = self.name\n cat = Categorical.from_codes(codes, categories=dtype.categories,\n ordered=dtype.ordered)\n return CategoricalIndex(cat, name=name)\n\n @classmethod\n def _create_categorical(cls, data, dtype=None):\n \"\"\"\n *this is an internal non-public method*\n\n create the correct categorical from data and the properties\n\n Parameters\n ----------\n data : data for new Categorical\n dtype : CategoricalDtype, defaults to existing\n\n Returns\n -------\n Categorical\n \"\"\"\n if (isinstance(data, (cls, ABCSeries)) and\n is_categorical_dtype(data)):\n data = data.values\n\n if not isinstance(data, ABCCategorical):\n return Categorical(data, dtype=dtype)\n\n if isinstance(dtype, CategoricalDtype) and dtype != data.dtype:\n # we want to silently ignore dtype='category'\n data = data._set_dtype(dtype)\n return data\n\n @classmethod\n def _simple_new(cls, values, name=None, dtype=None, **kwargs):\n result = object.__new__(cls)\n\n values = cls._create_categorical(values, dtype=dtype)\n result._data = values\n result.name = name\n for k, v in compat.iteritems(kwargs):\n setattr(result, k, v)\n\n result._reset_identity()\n return result\n\n # --------------------------------------------------------------------\n\n @Appender(_index_shared_docs['_shallow_copy'])\n def _shallow_copy(self, values=None, dtype=None, **kwargs):\n if dtype is None:\n dtype = self.dtype\n return super(CategoricalIndex, self)._shallow_copy(\n values=values, dtype=dtype, **kwargs)\n\n def _is_dtype_compat(self, other):\n \"\"\"\n *this is an internal non-public method*\n\n provide a comparison between the dtype of self and other (coercing if\n needed)\n\n Raises\n ------\n TypeError if the dtypes are not compatible\n \"\"\"\n if is_categorical_dtype(other):\n if isinstance(other, CategoricalIndex):\n other = other._values\n if not other.is_dtype_equal(self):\n raise TypeError(\"categories must match existing categories \"\n \"when appending\")\n else:\n values = other\n if not is_list_like(values):\n values = [values]\n other = CategoricalIndex(self._create_categorical(\n other, dtype=self.dtype))\n if not other.isin(values).all():\n raise TypeError(\"cannot append a non-category item to a \"\n \"CategoricalIndex\")\n\n return other\n\n def equals(self, other):\n \"\"\"\n Determines if two CategorialIndex objects contain the same elements.\n \"\"\"\n if self.is_(other):\n return True\n\n if not isinstance(other, Index):\n return False\n\n try:\n other = self._is_dtype_compat(other)\n if isinstance(other, type(self)):\n other = other._data\n return self._data.equals(other)\n except (TypeError, ValueError):\n pass\n\n return False\n\n # --------------------------------------------------------------------\n # Rendering Methods\n\n @property\n def _formatter_func(self):\n return self.categories._formatter_func\n\n def _format_attrs(self):\n \"\"\"\n Return a list of tuples of the (attr,formatted_value)\n \"\"\"\n max_categories = (10 if get_option(\"display.max_categories\") == 0 else\n get_option(\"display.max_categories\"))\n attrs = [\n ('categories',\n ibase.default_pprint(self.categories,\n max_seq_items=max_categories)),\n ('ordered', self.ordered)]\n if self.name is not None:\n attrs.append(('name', ibase.default_pprint(self.name)))\n attrs.append(('dtype', \"'%s'\" % self.dtype.name))\n max_seq_items = get_option('display.max_seq_items') or len(self)\n if len(self) > max_seq_items:\n attrs.append(('length', len(self)))\n return attrs\n\n # --------------------------------------------------------------------\n\n @property\n def inferred_type(self):\n return 'categorical'\n\n @property\n def values(self):\n \"\"\" return the underlying data, which is a Categorical \"\"\"\n return self._data\n\n @property\n def itemsize(self):\n # Size of the items in categories, not codes.\n return self.values.itemsize\n\n def _wrap_setop_result(self, other, result):\n name = get_op_result_name(self, other)\n return self._shallow_copy(result, name=name)\n\n def get_values(self):\n \"\"\" return the underlying data as an ndarray \"\"\"\n return self._data.get_values()\n\n def tolist(self):\n return self._data.tolist()\n\n @property\n def codes(self):\n return self._data.codes\n\n @property\n def categories(self):\n return self._data.categories\n\n @property\n def ordered(self):\n return self._data.ordered\n\n def _reverse_indexer(self):\n return self._data._reverse_indexer()\n\n @Appender(_index_shared_docs['contains'] % _index_doc_kwargs)\n def __contains__(self, key):\n # if key is a NaN, check if any NaN is in self.\n if isna(key):\n return self.hasnans\n\n return contains(self, key, container=self._engine)\n\n @Appender(_index_shared_docs['contains'] % _index_doc_kwargs)\n def contains(self, key):\n return key in self\n\n def __array__(self, dtype=None):\n \"\"\" the array interface, return my values \"\"\"\n return np.array(self._data, dtype=dtype)\n\n @Appender(_index_shared_docs['astype'])\n def astype(self, dtype, copy=True):\n if is_interval_dtype(dtype):\n from pandas import IntervalIndex\n return IntervalIndex(np.array(self))\n elif is_categorical_dtype(dtype):\n # GH 18630\n dtype = self.dtype.update_dtype(dtype)\n if dtype == self.dtype:\n return self.copy() if copy else self\n\n return super(CategoricalIndex, self).astype(dtype=dtype, copy=copy)\n\n @cache_readonly\n def _isnan(self):\n \"\"\" return if each value is nan\"\"\"\n return self._data.codes == -1\n\n @Appender(ibase._index_shared_docs['fillna'])\n def fillna(self, value, downcast=None):\n self._assert_can_do_op(value)\n return CategoricalIndex(self._data.fillna(value), name=self.name)\n\n def argsort(self, *args, **kwargs):\n return self.values.argsort(*args, **kwargs)\n\n @cache_readonly\n def _engine(self):\n\n # we are going to look things up with the codes themselves\n return self._engine_type(lambda: self.codes, len(self))\n\n # introspection\n @cache_readonly\n def is_unique(self):\n return self._engine.is_unique\n\n @property\n def is_monotonic_increasing(self):\n return self._engine.is_monotonic_increasing\n\n @property\n def is_monotonic_decreasing(self):\n return self._engine.is_monotonic_decreasing\n\n @Appender(_index_shared_docs['index_unique'] % _index_doc_kwargs)\n def unique(self, level=None):\n if level is not None:\n self._validate_index_level(level)\n result = self.values.unique()\n # CategoricalIndex._shallow_copy keeps original dtype\n # if not otherwise specified\n return self._shallow_copy(result, dtype=result.dtype)\n\n @Appender(Index.duplicated.__doc__)\n def duplicated(self, keep='first'):\n from pandas._libs.hashtable import duplicated_int64\n codes = self.codes.astype('i8')\n return duplicated_int64(codes, keep)\n\n def _to_safe_for_reshape(self):\n \"\"\" convert to object if we are a categorical \"\"\"\n return self.astype('object')\n\n def get_loc(self, key, method=None):\n \"\"\"\n Get integer location, slice or boolean mask for requested label.\n\n Parameters\n ----------\n key : label\n method : {None}\n * default: exact matches only.\n\n Returns\n -------\n loc : int if unique index, slice if monotonic index, else mask\n\n Raises\n ------\n KeyError : if the key is not in the index\n\n Examples\n ---------\n >>> unique_index = pd.CategoricalIndex(list('abc'))\n >>> unique_index.get_loc('b')\n 1\n\n >>> monotonic_index = pd.CategoricalIndex(list('abbc'))\n >>> monotonic_index.get_loc('b')\n slice(1, 3, None)\n\n >>> non_monotonic_index = pd.CategoricalIndex(list('abcb'))\n >>> non_monotonic_index.get_loc('b')\n array([False, True, False, True], dtype=bool)\n \"\"\"\n code = self.categories.get_loc(key)\n code = self.codes.dtype.type(code)\n try:\n return self._engine.get_loc(code)\n except KeyError:\n raise KeyError(key)\n\n def get_value(self, series, key):\n \"\"\"\n Fast lookup of value from 1-dimensional ndarray. Only use this if you\n know what you're doing\n \"\"\"\n try:\n k = com.values_from_object(key)\n k = self._convert_scalar_indexer(k, kind='getitem')\n indexer = self.get_loc(k)\n return series.iloc[indexer]\n except (KeyError, TypeError):\n pass\n\n # we might be a positional inexer\n return super(CategoricalIndex, self).get_value(series, key)\n\n def _can_reindex(self, indexer):\n \"\"\" always allow reindexing \"\"\"\n pass\n\n @Appender(_index_shared_docs['where'])\n def where(self, cond, other=None):\n # TODO: Investigate an alternative implementation with\n # 1. copy the underyling Categorical\n # 2. setitem with `cond` and `other`\n # 3. Rebuild CategoricalIndex.\n if other is None:\n other = self._na_value\n values = np.where(cond, self.values, other)\n cat = Categorical(values, dtype=self.dtype)\n return self._shallow_copy(cat, **self._get_attributes_dict())\n\n def reindex(self, target, method=None, level=None, limit=None,\n tolerance=None):\n \"\"\"\n Create index with target's values (move/add/delete values as necessary)\n\n Returns\n -------\n new_index : pd.Index\n Resulting index\n indexer : np.ndarray or None\n Indices of output values in original index\n\n \"\"\"\n\n if method is not None:\n raise NotImplementedError(\"argument method is not implemented for \"\n \"CategoricalIndex.reindex\")\n if level is not None:\n raise NotImplementedError(\"argument level is not implemented for \"\n \"CategoricalIndex.reindex\")\n if limit is not None:\n raise NotImplementedError(\"argument limit is not implemented for \"\n \"CategoricalIndex.reindex\")\n\n target = ibase.ensure_index(target)\n\n if self.equals(target):\n indexer = None\n missing = []\n else:\n if not target.is_unique:\n raise ValueError(\"cannot reindex with a non-unique indexer\")\n\n indexer, missing = self.get_indexer_non_unique(np.array(target))\n\n if len(self.codes) and indexer is not None:\n new_target = self.take(indexer)\n else:\n new_target = target\n\n # filling in missing if needed\n if len(missing):\n cats = self.categories.get_indexer(target)\n\n if (cats == -1).any():\n # coerce to a regular index here!\n result = Index(np.array(self), name=self.name)\n new_target, indexer, _ = result._reindex_non_unique(\n np.array(target))\n else:\n\n codes = new_target.codes.copy()\n codes[indexer == -1] = cats[missing]\n new_target = self._create_from_codes(codes)\n\n # we always want to return an Index type here\n # to be consistent with .reindex for other index types (e.g. they don't\n # coerce based on the actual values, only on the dtype)\n # unless we had an initial Categorical to begin with\n # in which case we are going to conform to the passed Categorical\n new_target = np.asarray(new_target)\n if is_categorical_dtype(target):\n new_target = target._shallow_copy(new_target, name=self.name)\n else:\n new_target = Index(new_target, name=self.name)\n\n return new_target, indexer\n\n def _reindex_non_unique(self, target):\n \"\"\" reindex from a non-unique; which CategoricalIndex's are almost\n always\n \"\"\"\n new_target, indexer = self.reindex(target)\n new_indexer = None\n\n check = indexer == -1\n if check.any():\n new_indexer = np.arange(len(self.take(indexer)))\n new_indexer[check] = -1\n\n cats = self.categories.get_indexer(target)\n if not (cats == -1).any():\n # .reindex returns normal Index. Revert to CategoricalIndex if\n # all targets are included in my categories\n new_target = self._shallow_copy(new_target)\n\n return new_target, indexer, new_indexer\n\n @Appender(_index_shared_docs['get_indexer'] % _index_doc_kwargs)\n def get_indexer(self, target, method=None, limit=None, tolerance=None):\n from pandas.core.arrays.categorical import _recode_for_categories\n\n method = missing.clean_reindex_fill_method(method)\n target = ibase.ensure_index(target)\n\n if self.is_unique and self.equals(target):\n return np.arange(len(self), dtype='intp')\n\n if method == 'pad' or method == 'backfill':\n raise NotImplementedError(\"method='pad' and method='backfill' not \"\n \"implemented yet for CategoricalIndex\")\n elif method == 'nearest':\n raise NotImplementedError(\"method='nearest' not implemented yet \"\n 'for CategoricalIndex')\n\n if (isinstance(target, CategoricalIndex) and\n self.values.is_dtype_equal(target)):\n if self.values.equals(target.values):\n # we have the same codes\n codes = target.codes\n else:\n codes = _recode_for_categories(target.codes,\n target.categories,\n self.values.categories)\n else:\n if isinstance(target, CategoricalIndex):\n code_indexer = self.categories.get_indexer(target.categories)\n codes = take_1d(code_indexer, target.codes, fill_value=-1)\n else:\n codes = self.categories.get_indexer(target)\n\n indexer, _ = self._engine.get_indexer_non_unique(codes)\n return ensure_platform_int(indexer)\n\n @Appender(_index_shared_docs['get_indexer_non_unique'] % _index_doc_kwargs)\n def get_indexer_non_unique(self, target):\n target = ibase.ensure_index(target)\n\n if isinstance(target, CategoricalIndex):\n # Indexing on codes is more efficient if categories are the same:\n if target.categories is self.categories:\n target = target.codes\n indexer, missing = self._engine.get_indexer_non_unique(target)\n return ensure_platform_int(indexer), missing\n target = target.values\n\n codes = self.categories.get_indexer(target)\n indexer, missing = self._engine.get_indexer_non_unique(codes)\n return ensure_platform_int(indexer), missing\n\n @Appender(_index_shared_docs['_convert_scalar_indexer'])\n def _convert_scalar_indexer(self, key, kind=None):\n if self.categories._defer_to_indexing:\n return self.categories._convert_scalar_indexer(key, kind=kind)\n\n return super(CategoricalIndex, self)._convert_scalar_indexer(\n key, kind=kind)\n\n @Appender(_index_shared_docs['_convert_list_indexer'])\n def _convert_list_indexer(self, keyarr, kind=None):\n # Return our indexer or raise if all of the values are not included in\n # the categories\n\n if self.categories._defer_to_indexing:\n indexer = self.categories._convert_list_indexer(keyarr, kind=kind)\n return Index(self.codes).get_indexer_for(indexer)\n\n indexer = self.categories.get_indexer(np.asarray(keyarr))\n if (indexer == -1).any():\n raise KeyError(\n \"a list-indexer must only \"\n \"include values that are \"\n \"in the categories\")\n\n return self.get_indexer(keyarr)\n\n @Appender(_index_shared_docs['_convert_arr_indexer'])\n def _convert_arr_indexer(self, keyarr):\n keyarr = com.asarray_tuplesafe(keyarr)\n\n if self.categories._defer_to_indexing:\n return keyarr\n\n return self._shallow_copy(keyarr)\n\n @Appender(_index_shared_docs['_convert_index_indexer'])\n def _convert_index_indexer(self, keyarr):\n return self._shallow_copy(keyarr)\n\n @Appender(_index_shared_docs['take'] % _index_doc_kwargs)\n def take(self, indices, axis=0, allow_fill=True,\n fill_value=None, **kwargs):\n nv.validate_take(tuple(), kwargs)\n indices = ensure_platform_int(indices)\n taken = self._assert_take_fillable(self.codes, indices,\n allow_fill=allow_fill,\n fill_value=fill_value,\n na_value=-1)\n return self._create_from_codes(taken)\n\n def is_dtype_equal(self, other):\n return self._data.is_dtype_equal(other)\n\n take_nd = take\n\n def map(self, mapper):\n \"\"\"\n Map values using input correspondence (a dict, Series, or function).\n\n Maps the values (their categories, not the codes) of the index to new\n categories. If the mapping correspondence is one-to-one the result is a\n :class:`~pandas.CategoricalIndex` which has the same order property as\n the original, otherwise an :class:`~pandas.Index` is returned.\n\n If a `dict` or :class:`~pandas.Series` is used any unmapped category is\n mapped to `NaN`. Note that if this happens an :class:`~pandas.Index`\n will be returned.\n\n Parameters\n ----------\n mapper : function, dict, or Series\n Mapping correspondence.\n\n Returns\n -------\n pandas.CategoricalIndex or pandas.Index\n Mapped index.\n\n See Also\n --------\n Index.map : Apply a mapping correspondence on an\n :class:`~pandas.Index`.\n Series.map : Apply a mapping correspondence on a\n :class:`~pandas.Series`.\n Series.apply : Apply more complex functions on a\n :class:`~pandas.Series`.\n\n Examples\n --------\n >>> idx = pd.CategoricalIndex(['a', 'b', 'c'])\n >>> idx\n CategoricalIndex(['a', 'b', 'c'], categories=['a', 'b', 'c'],\n ordered=False, dtype='category')\n >>> idx.map(lambda x: x.upper())\n CategoricalIndex(['A', 'B', 'C'], categories=['A', 'B', 'C'],\n ordered=False, dtype='category')\n >>> idx.map({'a': 'first', 'b': 'second', 'c': 'third'})\n CategoricalIndex(['first', 'second', 'third'], categories=['first',\n 'second', 'third'], ordered=False, dtype='category')\n\n If the mapping is one-to-one the ordering of the categories is\n preserved:\n\n >>> idx = pd.CategoricalIndex(['a', 'b', 'c'], ordered=True)\n >>> idx\n CategoricalIndex(['a', 'b', 'c'], categories=['a', 'b', 'c'],\n ordered=True, dtype='category')\n >>> idx.map({'a': 3, 'b': 2, 'c': 1})\n CategoricalIndex([3, 2, 1], categories=[3, 2, 1], ordered=True,\n dtype='category')\n\n If the mapping is not one-to-one an :class:`~pandas.Index` is returned:\n\n >>> idx.map({'a': 'first', 'b': 'second', 'c': 'first'})\n Index(['first', 'second', 'first'], dtype='object')\n\n If a `dict` is used, all unmapped categories are mapped to `NaN` and\n the result is an :class:`~pandas.Index`:\n\n >>> idx.map({'a': 'first', 'b': 'second'})\n Index(['first', 'second', nan], dtype='object')\n \"\"\"\n return self._shallow_copy_with_infer(self.values.map(mapper))\n\n def delete(self, loc):\n \"\"\"\n Make new Index with passed location(-s) deleted\n\n Returns\n -------\n new_index : Index\n \"\"\"\n return self._create_from_codes(np.delete(self.codes, loc))\n\n def insert(self, loc, item):\n \"\"\"\n Make new Index inserting new item at location. Follows\n Python list.append semantics for negative values\n\n Parameters\n ----------\n loc : int\n item : object\n\n Returns\n -------\n new_index : Index\n\n Raises\n ------\n ValueError if the item is not in the categories\n\n \"\"\"\n code = self.categories.get_indexer([item])\n if (code == -1) and not (is_scalar(item) and isna(item)):\n raise TypeError(\"cannot insert an item into a CategoricalIndex \"\n \"that is not already an existing category\")\n\n codes = self.codes\n codes = np.concatenate((codes[:loc], code, codes[loc:]))\n return self._create_from_codes(codes)\n\n def _concat(self, to_concat, name):\n # if calling index is category, don't check dtype of others\n return CategoricalIndex._concat_same_dtype(self, to_concat, name)\n\n def _concat_same_dtype(self, to_concat, name):\n \"\"\"\n Concatenate to_concat which has the same class\n ValueError if other is not in the categories\n \"\"\"\n to_concat = [self._is_dtype_compat(c) for c in to_concat]\n codes = np.concatenate([c.codes for c in to_concat])\n result = self._create_from_codes(codes, name=name)\n # if name is None, _create_from_codes sets self.name\n result.name = name\n return result\n\n def _codes_for_groupby(self, sort, observed):\n \"\"\" Return a Categorical adjusted for groupby \"\"\"\n return self.values._codes_for_groupby(sort, observed)\n\n @classmethod\n def _add_comparison_methods(cls):\n \"\"\" add in comparison methods \"\"\"\n\n def _make_compare(op):\n opname = '__{op}__'.format(op=op.__name__)\n\n def _evaluate_compare(self, other):\n\n # if we have a Categorical type, then must have the same\n # categories\n if isinstance(other, CategoricalIndex):\n other = other._values\n elif isinstance(other, Index):\n other = self._create_categorical(\n other._values, dtype=self.dtype)\n\n if isinstance(other, (ABCCategorical, np.ndarray,\n ABCSeries)):\n if len(self.values) != len(other):\n raise ValueError(\"Lengths must match to compare\")\n\n if isinstance(other, ABCCategorical):\n if not self.values.is_dtype_equal(other):\n raise TypeError(\"categorical index comparisons must \"\n \"have the same categories and ordered \"\n \"attributes\")\n\n result = op(self.values, other)\n if isinstance(result, ABCSeries):\n # Dispatch to pd.Categorical returned NotImplemented\n # and we got a Series back; down-cast to ndarray\n result = result.values\n return result\n\n return compat.set_function_name(_evaluate_compare, opname, cls)\n\n cls.__eq__ = _make_compare(operator.eq)\n cls.__ne__ = _make_compare(operator.ne)\n cls.__lt__ = _make_compare(operator.lt)\n cls.__gt__ = _make_compare(operator.gt)\n cls.__le__ = _make_compare(operator.le)\n cls.__ge__ = _make_compare(operator.ge)\n\n def _delegate_method(self, name, *args, **kwargs):\n \"\"\" method delegation to the ._values \"\"\"\n method = getattr(self._values, name)\n if 'inplace' in kwargs:\n raise ValueError(\"cannot use inplace with CategoricalIndex\")\n res = method(*args, **kwargs)\n if is_scalar(res):\n return res\n return CategoricalIndex(res, name=self.name)\n\n\nCategoricalIndex._add_numeric_methods_add_sub_disabled()\nCategoricalIndex._add_numeric_methods_disabled()\nCategoricalIndex._add_logical_methods_disabled()\nCategoricalIndex._add_comparison_methods()\n"
] | [
[
"pandas.core.common.values_from_object",
"pandas.compat.iteritems",
"pandas.core.indexes.base.default_pprint",
"numpy.asarray",
"pandas.core.dtypes.common.is_list_like",
"pandas.core.config.get_option",
"pandas.core.dtypes.common.is_categorical_dtype",
"pandas.core.algorithms.take_1d",
"pandas.core.indexes.base.ensure_index",
"numpy.delete",
"pandas.core.dtypes.dtypes.CategoricalDtype._from_values_or_dtype",
"numpy.where",
"pandas.core.arrays.categorical.Categorical.from_codes",
"pandas.core.indexes.base.Index",
"pandas.compat.set_function_name",
"pandas.core.common.asarray_tuplesafe",
"pandas._libs.hashtable.duplicated_int64",
"pandas.core.accessor.delegate_names",
"pandas.core.dtypes.common.is_interval_dtype",
"pandas.core.arrays.categorical.contains",
"pandas.core.dtypes.common.ensure_platform_int",
"pandas.core.dtypes.missing.isna",
"pandas.core.dtypes.common.is_scalar",
"pandas.core.ops.get_op_result_name",
"pandas.util._decorators.Appender",
"pandas.core.missing.clean_reindex_fill_method",
"pandas.core.arrays.categorical.Categorical",
"pandas.core.arrays.categorical._recode_for_categories",
"numpy.array",
"numpy.concatenate"
]
] |
pection/packnet-sfm | [
"d5673567b649e6bfda292c894cacdeb06aa80913"
] | [
"scripts/deploy_model2.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport argparse\nimport numpy as np\nimport torch\nimport os\nimport sys\n\nsys.path.append(os.getcwd())\n\nfrom packnet_sfm.models.SelfSupModel import SelfSupModel\n\nmodel = SelfSupModel()\n\nPATH = '/home/ai/work/data/experiments/default_config-train_kitti-2022.03.14-09h57m43s/epoch=49_KITTI_raw-eigen_val_files-velodyne-abs_rel_pp_gt=0.089.ckpt'\n\n # model = Net()\n# optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)\n\ncheckpoint = torch.load(PATH)\nprint(checkpoint)\nprint(type(checkpoint))\n# model.load_state_dict(checkpoint['model_state_dict'])\n# optimizer.load_state_dict(checkpoint['optimizer_state_dict'])\nepoch = checkpoint['epoch']\n# loss = checkpoint['loss']\n\nmodel.eval()\noutput = model()\n# print(epoch,loss)\n#\n# model.eval()\n# # - or -\n# model.train()\n"
] | [
[
"torch.load"
]
] |
dubreuia/magenta | [
"acd6dedc315ea159c6f15750dd09aabdadc47515"
] | [
"magenta/music/performance_lib.py"
] | [
"# Copyright 2019 The Magenta Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Utility functions for working with polyphonic performances.\"\"\"\n\nfrom __future__ import division\n\nimport abc\nimport collections\nimport math\n\nfrom magenta.music import constants\nfrom magenta.music import events_lib\nfrom magenta.music import sequences_lib\nfrom magenta.music.protobuf import music_pb2\nimport tensorflow as tf\n\nMAX_MIDI_PITCH = constants.MAX_MIDI_PITCH\nMIN_MIDI_PITCH = constants.MIN_MIDI_PITCH\n\nMAX_MIDI_VELOCITY = constants.MAX_MIDI_VELOCITY\nMIN_MIDI_VELOCITY = constants.MIN_MIDI_VELOCITY\nMAX_NUM_VELOCITY_BINS = MAX_MIDI_VELOCITY - MIN_MIDI_VELOCITY + 1\n\nSTANDARD_PPQ = constants.STANDARD_PPQ\n\nDEFAULT_MAX_SHIFT_STEPS = 100\nDEFAULT_MAX_SHIFT_QUARTERS = 4\n\nDEFAULT_PROGRAM = 0\n\n\nclass PerformanceEvent(object):\n \"\"\"Class for storing events in a performance.\"\"\"\n\n # Start of a new note.\n NOTE_ON = 1\n # End of a note.\n NOTE_OFF = 2\n # Shift time forward.\n TIME_SHIFT = 3\n # Change current velocity.\n VELOCITY = 4\n # Duration of preceding NOTE_ON.\n # For Note-based encoding, used instead of NOTE_OFF events.\n DURATION = 5\n\n def __init__(self, event_type, event_value):\n if event_type in (PerformanceEvent.NOTE_ON, PerformanceEvent.NOTE_OFF):\n if not MIN_MIDI_PITCH <= event_value <= MAX_MIDI_PITCH:\n raise ValueError('Invalid pitch value: %s' % event_value)\n elif event_type == PerformanceEvent.TIME_SHIFT:\n if not 0 <= event_value:\n raise ValueError('Invalid time shift value: %s' % event_value)\n elif event_type == PerformanceEvent.DURATION:\n if not 1 <= event_value:\n raise ValueError('Invalid duration value: %s' % event_value)\n elif event_type == PerformanceEvent.VELOCITY:\n if not 1 <= event_value <= MAX_NUM_VELOCITY_BINS:\n raise ValueError('Invalid velocity value: %s' % event_value)\n else:\n raise ValueError('Invalid event type: %s' % event_type)\n\n self.event_type = event_type\n self.event_value = event_value\n\n def __repr__(self):\n return 'PerformanceEvent(%r, %r)' % (self.event_type, self.event_value)\n\n def __eq__(self, other):\n if not isinstance(other, PerformanceEvent):\n return False\n return (self.event_type == other.event_type and\n self.event_value == other.event_value)\n\n\ndef _velocity_bin_size(num_velocity_bins):\n return int(math.ceil(\n (MAX_MIDI_VELOCITY - MIN_MIDI_VELOCITY + 1) / num_velocity_bins))\n\n\ndef velocity_to_bin(velocity, num_velocity_bins):\n return ((velocity - MIN_MIDI_VELOCITY) //\n _velocity_bin_size(num_velocity_bins) + 1)\n\n\ndef velocity_bin_to_velocity(velocity_bin, num_velocity_bins):\n return (\n MIN_MIDI_VELOCITY + (velocity_bin - 1) *\n _velocity_bin_size(num_velocity_bins))\n\n\ndef _program_and_is_drum_from_sequence(sequence, instrument=None):\n \"\"\"Get MIDI program and is_drum from sequence and (optional) instrument.\n\n Args:\n sequence: The NoteSequence from which MIDI program and is_drum will be\n extracted.\n instrument: The instrument in `sequence` from which MIDI program and\n is_drum will be extracted, or None to consider all instruments.\n\n Returns:\n A tuple containing program and is_drum for the sequence and optional\n instrument. If multiple programs are found (or if is_drum is True),\n program will be None. If multiple values of is_drum are found, is_drum\n will be None.\n \"\"\"\n notes = [note for note in sequence.notes\n if instrument is None or note.instrument == instrument]\n # Only set program for non-drum tracks.\n if all(note.is_drum for note in notes):\n is_drum = True\n program = None\n elif all(not note.is_drum for note in notes):\n is_drum = False\n programs = set(note.program for note in notes)\n program = programs.pop() if len(programs) == 1 else None\n else:\n is_drum = None\n program = None\n return program, is_drum\n\n\nclass BasePerformance(events_lib.EventSequence):\n \"\"\"Stores a polyphonic sequence as a stream of performance events.\n\n Events are PerformanceEvent objects that encode event type and value.\n \"\"\"\n __metaclass__ = abc.ABCMeta\n\n def __init__(self, start_step, num_velocity_bins, max_shift_steps,\n program=None, is_drum=None):\n \"\"\"Construct a BasePerformance.\n\n Args:\n start_step: The offset of this sequence relative to the beginning of the\n source sequence.\n num_velocity_bins: Number of velocity bins to use.\n max_shift_steps: Maximum number of steps for a single time-shift event.\n program: MIDI program used for this performance, or None if not specified.\n is_drum: Whether or not this performance consists of drums, or None if not\n specified.\n\n Raises:\n ValueError: If `num_velocity_bins` is larger than the number of MIDI\n velocity values.\n \"\"\"\n if num_velocity_bins > MAX_MIDI_VELOCITY - MIN_MIDI_VELOCITY + 1:\n raise ValueError(\n 'Number of velocity bins is too large: %d' % num_velocity_bins)\n\n self._start_step = start_step\n self._num_velocity_bins = num_velocity_bins\n self._max_shift_steps = max_shift_steps\n self._program = program\n self._is_drum = is_drum\n\n @property\n def start_step(self):\n return self._start_step\n\n @property\n def max_shift_steps(self):\n return self._max_shift_steps\n\n @property\n def program(self):\n return self._program\n\n @property\n def is_drum(self):\n return self._is_drum\n\n def _append_steps(self, num_steps):\n \"\"\"Adds steps to the end of the sequence.\"\"\"\n if (self._events and\n self._events[-1].event_type == PerformanceEvent.TIME_SHIFT and\n self._events[-1].event_value < self._max_shift_steps):\n # Last event is already non-maximal time shift. Increase its duration.\n added_steps = min(num_steps,\n self._max_shift_steps - self._events[-1].event_value)\n self._events[-1] = PerformanceEvent(\n PerformanceEvent.TIME_SHIFT,\n self._events[-1].event_value + added_steps)\n num_steps -= added_steps\n\n while num_steps >= self._max_shift_steps:\n self._events.append(\n PerformanceEvent(event_type=PerformanceEvent.TIME_SHIFT,\n event_value=self._max_shift_steps))\n num_steps -= self._max_shift_steps\n\n if num_steps > 0:\n self._events.append(\n PerformanceEvent(event_type=PerformanceEvent.TIME_SHIFT,\n event_value=num_steps))\n\n def _trim_steps(self, num_steps):\n \"\"\"Trims a given number of steps from the end of the sequence.\"\"\"\n steps_trimmed = 0\n while self._events and steps_trimmed < num_steps:\n if self._events[-1].event_type == PerformanceEvent.TIME_SHIFT:\n if steps_trimmed + self._events[-1].event_value > num_steps:\n self._events[-1] = PerformanceEvent(\n event_type=PerformanceEvent.TIME_SHIFT,\n event_value=(self._events[-1].event_value -\n num_steps + steps_trimmed))\n steps_trimmed = num_steps\n else:\n steps_trimmed += self._events[-1].event_value\n self._events.pop()\n else:\n self._events.pop()\n\n def set_length(self, steps, from_left=False):\n \"\"\"Sets the length of the sequence to the specified number of steps.\n\n If the event sequence is not long enough, pads with time shifts to make the\n sequence the specified length. If it is too long, it will be truncated to\n the requested length.\n\n Args:\n steps: How many quantized steps long the event sequence should be.\n from_left: Whether to add/remove from the left instead of right.\n \"\"\"\n if from_left:\n raise NotImplementedError('from_left is not supported')\n\n if self.num_steps < steps:\n self._append_steps(steps - self.num_steps)\n elif self.num_steps > steps:\n self._trim_steps(self.num_steps - steps)\n\n assert self.num_steps == steps\n\n def append(self, event):\n \"\"\"Appends the event to the end of the sequence.\n\n Args:\n event: The performance event to append to the end.\n\n Raises:\n ValueError: If `event` is not a valid performance event.\n \"\"\"\n if not isinstance(event, PerformanceEvent):\n raise ValueError('Invalid performance event: %s' % event)\n self._events.append(event)\n\n def truncate(self, num_events):\n \"\"\"Truncates this Performance to the specified number of events.\n\n Args:\n num_events: The number of events to which this performance will be\n truncated.\n \"\"\"\n self._events = self._events[:num_events]\n\n def __len__(self):\n \"\"\"How many events are in this sequence.\n\n Returns:\n Number of events as an integer.\n \"\"\"\n return len(self._events)\n\n def __getitem__(self, i):\n \"\"\"Returns the event at the given index.\"\"\"\n return self._events[i]\n\n def __iter__(self):\n \"\"\"Return an iterator over the events in this sequence.\"\"\"\n return iter(self._events)\n\n def __str__(self):\n strs = []\n for event in self:\n if event.event_type == PerformanceEvent.NOTE_ON:\n strs.append('(%s, ON)' % event.event_value)\n elif event.event_type == PerformanceEvent.NOTE_OFF:\n strs.append('(%s, OFF)' % event.event_value)\n elif event.event_type == PerformanceEvent.TIME_SHIFT:\n strs.append('(%s, SHIFT)' % event.event_value)\n elif event.event_type == PerformanceEvent.VELOCITY:\n strs.append('(%s, VELOCITY)' % event.event_value)\n else:\n raise ValueError('Unknown event type: %s' % event.event_type)\n return '\\n'.join(strs)\n\n @property\n def end_step(self):\n return self.start_step + self.num_steps\n\n @property\n def num_steps(self):\n \"\"\"Returns how many steps long this sequence is.\n\n Returns:\n Length of the sequence in quantized steps.\n \"\"\"\n steps = 0\n for event in self:\n if event.event_type == PerformanceEvent.TIME_SHIFT:\n steps += event.event_value\n return steps\n\n @property\n def steps(self):\n \"\"\"Return a Python list of the time step at each event in this sequence.\"\"\"\n step = self.start_step\n result = []\n for event in self:\n result.append(step)\n if event.event_type == PerformanceEvent.TIME_SHIFT:\n step += event.event_value\n return result\n\n @staticmethod\n def _from_quantized_sequence(quantized_sequence, start_step,\n num_velocity_bins, max_shift_steps,\n instrument=None):\n \"\"\"Extract a list of events from the given quantized NoteSequence object.\n\n Within a step, new pitches are started with NOTE_ON and existing pitches are\n ended with NOTE_OFF. TIME_SHIFT shifts the current step forward in time.\n VELOCITY changes the current velocity value that will be applied to all\n NOTE_ON events.\n\n Args:\n quantized_sequence: A quantized NoteSequence instance.\n start_step: Start converting the sequence at this time step.\n num_velocity_bins: Number of velocity bins to use. If 0, velocity events\n will not be included at all.\n max_shift_steps: Maximum number of steps for a single time-shift event.\n instrument: If not None, extract only the specified instrument. Otherwise,\n extract all instruments into a single event list.\n\n Returns:\n A list of events.\n \"\"\"\n notes = [note for note in quantized_sequence.notes\n if note.quantized_start_step >= start_step\n and (instrument is None or note.instrument == instrument)]\n sorted_notes = sorted(notes, key=lambda note: (note.start_time, note.pitch))\n\n # Sort all note start and end events.\n onsets = [(note.quantized_start_step, idx, False)\n for idx, note in enumerate(sorted_notes)]\n offsets = [(note.quantized_end_step, idx, True)\n for idx, note in enumerate(sorted_notes)]\n note_events = sorted(onsets + offsets)\n\n current_step = start_step\n current_velocity_bin = 0\n performance_events = []\n\n for step, idx, is_offset in note_events:\n if step > current_step:\n # Shift time forward from the current step to this event.\n while step > current_step + max_shift_steps:\n # We need to move further than the maximum shift size.\n performance_events.append(\n PerformanceEvent(event_type=PerformanceEvent.TIME_SHIFT,\n event_value=max_shift_steps))\n current_step += max_shift_steps\n performance_events.append(\n PerformanceEvent(event_type=PerformanceEvent.TIME_SHIFT,\n event_value=int(step - current_step)))\n current_step = step\n\n # If we're using velocity and this note's velocity is different from the\n # current velocity, change the current velocity.\n if num_velocity_bins:\n velocity_bin = velocity_to_bin(\n sorted_notes[idx].velocity, num_velocity_bins)\n if not is_offset and velocity_bin != current_velocity_bin:\n current_velocity_bin = velocity_bin\n performance_events.append(\n PerformanceEvent(event_type=PerformanceEvent.VELOCITY,\n event_value=current_velocity_bin))\n\n # Add a performance event for this note on/off.\n event_type = (\n PerformanceEvent.NOTE_OFF if is_offset else PerformanceEvent.NOTE_ON)\n performance_events.append(\n PerformanceEvent(event_type=event_type,\n event_value=sorted_notes[idx].pitch))\n\n return performance_events\n\n @abc.abstractmethod\n def to_sequence(self, velocity, instrument, program, max_note_duration=None):\n \"\"\"Converts the Performance to NoteSequence proto.\n\n Args:\n velocity: MIDI velocity to give each note. Between 1 and 127 (inclusive).\n If the performance contains velocity events, those will be used\n instead.\n instrument: MIDI instrument to give each note.\n program: MIDI program to give each note, or None to use the program\n associated with the Performance (or the default program if none\n exists).\n max_note_duration: Maximum note duration in seconds to allow. Notes longer\n than this will be truncated. If None, notes can be any length.\n\n Returns:\n A NoteSequence proto.\n \"\"\"\n pass\n\n def _to_sequence(self, seconds_per_step, velocity, instrument, program,\n max_note_duration=None):\n sequence_start_time = self.start_step * seconds_per_step\n\n sequence = music_pb2.NoteSequence()\n sequence.ticks_per_quarter = STANDARD_PPQ\n\n step = 0\n\n if program is None:\n # Use program associated with the performance (or default program).\n program = self.program if self.program is not None else DEFAULT_PROGRAM\n is_drum = self.is_drum if self.is_drum is not None else False\n\n # Map pitch to list because one pitch may be active multiple times.\n pitch_start_steps_and_velocities = collections.defaultdict(list)\n for i, event in enumerate(self):\n if event.event_type == PerformanceEvent.NOTE_ON:\n pitch_start_steps_and_velocities[event.event_value].append(\n (step, velocity))\n elif event.event_type == PerformanceEvent.NOTE_OFF:\n if not pitch_start_steps_and_velocities[event.event_value]:\n tf.logging.debug(\n 'Ignoring NOTE_OFF at position %d with no previous NOTE_ON' % i)\n else:\n # Create a note for the pitch that is now ending.\n pitch_start_step, pitch_velocity = pitch_start_steps_and_velocities[\n event.event_value][0]\n pitch_start_steps_and_velocities[event.event_value] = (\n pitch_start_steps_and_velocities[event.event_value][1:])\n if step == pitch_start_step:\n tf.logging.debug(\n 'Ignoring note with zero duration at step %d' % step)\n continue\n note = sequence.notes.add()\n note.start_time = (pitch_start_step * seconds_per_step +\n sequence_start_time)\n note.end_time = step * seconds_per_step + sequence_start_time\n if (max_note_duration and\n note.end_time - note.start_time > max_note_duration):\n note.end_time = note.start_time + max_note_duration\n note.pitch = event.event_value\n note.velocity = pitch_velocity\n note.instrument = instrument\n note.program = program\n note.is_drum = is_drum\n if note.end_time > sequence.total_time:\n sequence.total_time = note.end_time\n elif event.event_type == PerformanceEvent.TIME_SHIFT:\n step += event.event_value\n elif event.event_type == PerformanceEvent.VELOCITY:\n assert self._num_velocity_bins\n velocity = velocity_bin_to_velocity(\n event.event_value, self._num_velocity_bins)\n else:\n raise ValueError('Unknown event type: %s' % event.event_type)\n\n # There could be remaining pitches that were never ended. End them now\n # and create notes.\n for pitch in pitch_start_steps_and_velocities:\n for pitch_start_step, pitch_velocity in pitch_start_steps_and_velocities[\n pitch]:\n if step == pitch_start_step:\n tf.logging.debug(\n 'Ignoring note with zero duration at step %d' % step)\n continue\n note = sequence.notes.add()\n note.start_time = (pitch_start_step * seconds_per_step +\n sequence_start_time)\n note.end_time = step * seconds_per_step + sequence_start_time\n if (max_note_duration and\n note.end_time - note.start_time > max_note_duration):\n note.end_time = note.start_time + max_note_duration\n note.pitch = pitch\n note.velocity = pitch_velocity\n note.instrument = instrument\n note.program = program\n note.is_drum = is_drum\n if note.end_time > sequence.total_time:\n sequence.total_time = note.end_time\n\n return sequence\n\n\nclass Performance(BasePerformance):\n \"\"\"Performance with absolute timing and unknown meter.\"\"\"\n\n def __init__(self, quantized_sequence=None, steps_per_second=None,\n start_step=0, num_velocity_bins=0,\n max_shift_steps=DEFAULT_MAX_SHIFT_STEPS, instrument=None,\n program=None, is_drum=None):\n \"\"\"Construct a Performance.\n\n Either quantized_sequence or steps_per_second should be supplied.\n\n Args:\n quantized_sequence: A quantized NoteSequence proto.\n steps_per_second: Number of quantized time steps per second, if using\n absolute quantization.\n start_step: The offset of this sequence relative to the\n beginning of the source sequence. If a quantized sequence is used as\n input, only notes starting after this step will be considered.\n num_velocity_bins: Number of velocity bins to use. If 0, velocity events\n will not be included at all.\n max_shift_steps: Maximum number of steps for a single time-shift event.\n instrument: If not None, extract only the specified instrument from\n `quantized_sequence`. Otherwise, extract all instruments.\n program: MIDI program used for this performance, or None if not specified.\n Ignored if `quantized_sequence` is provided.\n is_drum: Whether or not this performance consists of drums, or None if not\n specified. Ignored if `quantized_sequence` is provided.\n\n Raises:\n ValueError: If both or neither of `quantized_sequence` or\n `steps_per_second` is specified.\n \"\"\"\n if (quantized_sequence, steps_per_second).count(None) != 1:\n raise ValueError(\n 'Must specify exactly one of quantized_sequence or steps_per_second')\n\n if quantized_sequence:\n sequences_lib.assert_is_absolute_quantized_sequence(quantized_sequence)\n self._steps_per_second = (\n quantized_sequence.quantization_info.steps_per_second)\n self._events = self._from_quantized_sequence(\n quantized_sequence, start_step, num_velocity_bins,\n max_shift_steps=max_shift_steps, instrument=instrument)\n program, is_drum = _program_and_is_drum_from_sequence(\n quantized_sequence, instrument)\n\n else:\n self._steps_per_second = steps_per_second\n self._events = []\n\n super(Performance, self).__init__(\n start_step=start_step,\n num_velocity_bins=num_velocity_bins,\n max_shift_steps=max_shift_steps,\n program=program,\n is_drum=is_drum)\n\n @property\n def steps_per_second(self):\n return self._steps_per_second\n\n def to_sequence(self,\n velocity=100,\n instrument=0,\n program=None,\n max_note_duration=None):\n \"\"\"Converts the Performance to NoteSequence proto.\n\n Args:\n velocity: MIDI velocity to give each note. Between 1 and 127 (inclusive).\n If the performance contains velocity events, those will be used\n instead.\n instrument: MIDI instrument to give each note.\n program: MIDI program to give each note, or None to use the program\n associated with the Performance (or the default program if none\n exists).\n max_note_duration: Maximum note duration in seconds to allow. Notes longer\n than this will be truncated. If None, notes can be any length.\n\n Returns:\n A NoteSequence proto.\n \"\"\"\n seconds_per_step = 1.0 / self.steps_per_second\n return self._to_sequence(\n seconds_per_step=seconds_per_step,\n velocity=velocity,\n instrument=instrument,\n program=program,\n max_note_duration=max_note_duration)\n\n\nclass MetricPerformance(BasePerformance):\n \"\"\"Performance with quarter-note relative timing.\"\"\"\n\n def __init__(self, quantized_sequence=None, steps_per_quarter=None,\n start_step=0, num_velocity_bins=0,\n max_shift_quarters=DEFAULT_MAX_SHIFT_QUARTERS, instrument=None,\n program=None, is_drum=None):\n \"\"\"Construct a MetricPerformance.\n\n Either quantized_sequence or steps_per_quarter should be supplied.\n\n Args:\n quantized_sequence: A quantized NoteSequence proto.\n steps_per_quarter: Number of quantized time steps per quarter note, if\n using metric quantization.\n start_step: The offset of this sequence relative to the\n beginning of the source sequence. If a quantized sequence is used as\n input, only notes starting after this step will be considered.\n num_velocity_bins: Number of velocity bins to use. If 0, velocity events\n will not be included at all.\n max_shift_quarters: Maximum number of quarter notes for a single time-\n shift event.\n instrument: If not None, extract only the specified instrument from\n `quantized_sequence`. Otherwise, extract all instruments.\n program: MIDI program used for this performance, or None if not specified.\n Ignored if `quantized_sequence` is provided.\n is_drum: Whether or not this performance consists of drums, or None if not\n specified. Ignored if `quantized_sequence` is provided.\n\n Raises:\n ValueError: If both or neither of `quantized_sequence` or\n `steps_per_quarter` is specified.\n \"\"\"\n if (quantized_sequence, steps_per_quarter).count(None) != 1:\n raise ValueError(\n 'Must specify exactly one of quantized_sequence or steps_per_quarter')\n\n if quantized_sequence:\n sequences_lib.assert_is_relative_quantized_sequence(quantized_sequence)\n self._steps_per_quarter = (\n quantized_sequence.quantization_info.steps_per_quarter)\n self._events = self._from_quantized_sequence(\n quantized_sequence, start_step, num_velocity_bins,\n max_shift_steps=self._steps_per_quarter * max_shift_quarters,\n instrument=instrument)\n program, is_drum = _program_and_is_drum_from_sequence(\n quantized_sequence, instrument)\n\n else:\n self._steps_per_quarter = steps_per_quarter\n self._events = []\n\n super(MetricPerformance, self).__init__(\n start_step=start_step,\n num_velocity_bins=num_velocity_bins,\n max_shift_steps=self._steps_per_quarter * max_shift_quarters,\n program=program,\n is_drum=is_drum)\n\n @property\n def steps_per_quarter(self):\n return self._steps_per_quarter\n\n def to_sequence(self,\n velocity=100,\n instrument=0,\n program=None,\n max_note_duration=None,\n qpm=120.0):\n \"\"\"Converts the Performance to NoteSequence proto.\n\n Args:\n velocity: MIDI velocity to give each note. Between 1 and 127 (inclusive).\n If the performance contains velocity events, those will be used\n instead.\n instrument: MIDI instrument to give each note.\n program: MIDI program to give each note, or None to use the program\n associated with the Performance (or the default program if none\n exists).\n max_note_duration: Maximum note duration in seconds to allow. Notes longer\n than this will be truncated. If None, notes can be any length.\n qpm: The tempo to use, in quarter notes per minute.\n\n Returns:\n A NoteSequence proto.\n \"\"\"\n seconds_per_step = 60.0 / (self.steps_per_quarter * qpm)\n sequence = self._to_sequence(\n seconds_per_step=seconds_per_step,\n velocity=velocity,\n instrument=instrument,\n program=program,\n max_note_duration=max_note_duration)\n sequence.tempos.add(qpm=qpm)\n return sequence\n\n\nclass NotePerformanceError(Exception):\n pass\n\n\nclass TooManyTimeShiftStepsError(NotePerformanceError):\n pass\n\n\nclass TooManyDurationStepsError(NotePerformanceError):\n pass\n\n\nclass NotePerformance(BasePerformance):\n \"\"\"Stores a polyphonic sequence as a stream of performance events.\n\n Events are PerformanceEvent objects that encode event type and value.\n In this version, the performance is encoded in 4-event tuples:\n TIME_SHIFT, NOTE_ON, VELOCITY, DURATION.\n \"\"\"\n\n def __init__(self, quantized_sequence, num_velocity_bins, instrument=0,\n start_step=0, max_shift_steps=1000, max_duration_steps=1000):\n \"\"\"Construct a NotePerformance.\n\n Args:\n quantized_sequence: A quantized NoteSequence proto.\n num_velocity_bins: Number of velocity bins to use.\n instrument: If not None, extract only the specified instrument from\n `quantized_sequence`. Otherwise, extract all instruments.\n start_step: The offset of this sequence relative to the beginning of the\n source sequence.\n max_shift_steps: Maximum number of steps for a time-shift event.\n max_duration_steps: Maximum number of steps for a duration event.\n\n Raises:\n ValueError: If `num_velocity_bins` is larger than the number of MIDI\n velocity values.\n \"\"\"\n program, is_drum = _program_and_is_drum_from_sequence(\n quantized_sequence, instrument)\n\n super(NotePerformance, self).__init__(\n start_step=start_step,\n num_velocity_bins=num_velocity_bins,\n max_shift_steps=max_shift_steps,\n program=program,\n is_drum=is_drum)\n\n self._max_duration_steps = max_duration_steps\n\n sequences_lib.assert_is_absolute_quantized_sequence(quantized_sequence)\n self._steps_per_second = (\n quantized_sequence.quantization_info.steps_per_second)\n self._events = self._from_quantized_sequence(\n quantized_sequence, instrument)\n\n @property\n def steps_per_second(self):\n return self._steps_per_second\n\n def set_length(self, steps, from_left=False):\n # This is not actually implemented, but to avoid raising exceptions during\n # generation just return instead of raising NotImplementedError.\n # TODO(fjord): Implement this.\n return\n\n def append(self, event):\n \"\"\"Appends the event to the end of the sequence.\n\n Args:\n event: The performance event tuple to append to the end.\n\n Raises:\n ValueError: If `event` is not a valid performance event tuple.\n \"\"\"\n if not isinstance(event, tuple):\n raise ValueError('Invalid performance event tuple: %s' % event)\n self._events.append(event)\n\n def __str__(self):\n strs = []\n for event in self:\n strs.append('TIME_SHIFT<%s>, NOTE_ON<%s>, VELOCITY<%s>, DURATION<%s>' % (\n event[0].event_value, event[1].event_value, event[2].event_value,\n event[3].event_value))\n return '\\n'.join(strs)\n\n @property\n def num_steps(self):\n \"\"\"Returns how many steps long this sequence is.\n\n Returns:\n Length of the sequence in quantized steps.\n \"\"\"\n steps = 0\n for event in self._events:\n steps += event[0].event_value\n if self._events:\n steps += self._events[-1][3].event_value\n return steps\n\n @property\n def steps(self):\n \"\"\"Return a Python list of the time step at each event in this sequence.\"\"\"\n step = self.start_step\n result = []\n for event in self:\n step += event[0].event_value\n result.append(step)\n return result\n\n def _from_quantized_sequence(self, quantized_sequence, instrument):\n \"\"\"Extract a list of events from the given quantized NoteSequence object.\n\n Within a step, new pitches are started with NOTE_ON and existing pitches are\n ended with NOTE_OFF. TIME_SHIFT shifts the current step forward in time.\n VELOCITY changes the current velocity value that will be applied to all\n NOTE_ON events.\n\n Args:\n quantized_sequence: A quantized NoteSequence instance.\n instrument: If not None, extract only the specified instrument. Otherwise,\n extract all instruments into a single event list.\n\n Returns:\n A list of events.\n\n Raises:\n TooManyTimeShiftStepsError: If the maximum number of time\n shift steps is exceeded.\n TooManyDurationStepsError: If the maximum number of duration\n shift steps is exceeded.\n \"\"\"\n notes = [note for note in quantized_sequence.notes\n if note.quantized_start_step >= self.start_step\n and (instrument is None or note.instrument == instrument)]\n sorted_notes = sorted(notes, key=lambda note: (note.start_time, note.pitch))\n\n current_step = self.start_step\n performance_events = []\n\n for note in sorted_notes:\n sub_events = []\n\n # TIME_SHIFT\n time_shift_steps = note.quantized_start_step - current_step\n if time_shift_steps > self._max_shift_steps:\n raise TooManyTimeShiftStepsError(\n 'Too many steps for timeshift: %d' % time_shift_steps)\n else:\n sub_events.append(\n PerformanceEvent(event_type=PerformanceEvent.TIME_SHIFT,\n event_value=time_shift_steps))\n current_step = note.quantized_start_step\n\n # NOTE_ON\n sub_events.append(\n PerformanceEvent(event_type=PerformanceEvent.NOTE_ON,\n event_value=note.pitch))\n\n # VELOCITY\n velocity_bin = velocity_to_bin(note.velocity, self._num_velocity_bins)\n sub_events.append(\n PerformanceEvent(event_type=PerformanceEvent.VELOCITY,\n event_value=velocity_bin))\n\n # DURATION\n duration_steps = note.quantized_end_step - note.quantized_start_step\n if duration_steps > self._max_duration_steps:\n raise TooManyDurationStepsError(\n 'Too many steps for duration: %s' % note)\n sub_events.append(\n PerformanceEvent(event_type=PerformanceEvent.DURATION,\n event_value=duration_steps))\n\n performance_events.append(tuple(sub_events))\n\n return performance_events\n\n def to_sequence(self, instrument=0, program=None, max_note_duration=None):\n \"\"\"Converts the Performance to NoteSequence proto.\n\n Args:\n instrument: MIDI instrument to give each note.\n program: MIDI program to give each note, or None to use the program\n associated with the Performance (or the default program if none\n exists).\n max_note_duration: Not used in this implementation.\n\n Returns:\n A NoteSequence proto.\n \"\"\"\n seconds_per_step = 1.0 / self.steps_per_second\n sequence_start_time = self.start_step * seconds_per_step\n\n sequence = music_pb2.NoteSequence()\n sequence.ticks_per_quarter = STANDARD_PPQ\n\n step = 0\n\n if program is None:\n # Use program associated with the performance (or default program).\n program = self.program if self.program is not None else DEFAULT_PROGRAM\n is_drum = self.is_drum if self.is_drum is not None else False\n\n for event in self:\n step += event[0].event_value\n\n note = sequence.notes.add()\n note.start_time = step * seconds_per_step + sequence_start_time\n note.end_time = ((step + event[3].event_value) * seconds_per_step +\n sequence_start_time)\n note.pitch = event[1].event_value\n note.velocity = velocity_bin_to_velocity(\n event[2].event_value, self._num_velocity_bins)\n note.instrument = instrument\n note.program = program\n note.is_drum = is_drum\n\n if note.end_time > sequence.total_time:\n sequence.total_time = note.end_time\n\n return sequence\n"
] | [
[
"tensorflow.logging.debug"
]
] |
leliyliu/Fixed-Point-Training | [
"0f31512abbbab9216bd852c27be5c3774663d62e"
] | [
"models/modules/cptconv.py"
] | [
"from collections import namedtuple\nimport math\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd.function import InplaceFunction, Function\n\n__all__ = ['CPTConv2d']\n\nQParams = namedtuple('QParams', ['range', 'zero_point', 'num_bits']) # ็ฑไธไธช้จๅ็ปๆ็่กจ็คบ\n\n_DEFAULT_FLATTEN = (1, -1)\n_DEFAULT_FLATTEN_GRAD = (0, -1)\n\ndef _deflatten_as(x, x_full):\n shape = list(x.shape) + [1] * (x_full.dim() - x.dim())\n return x.view(*shape)\n\n\ndef calculate_qparams(x, num_bits, flatten_dims=_DEFAULT_FLATTEN, reduce_dim=0, reduce_type='mean', keepdim=False,\n true_zero=False):\n with torch.no_grad():\n x_flat = x.flatten(*flatten_dims)\n if x_flat.dim() == 1: # ๅฆๆๅๆไธไธชไธ็ปด็ๆฐๆฎ็ปๆ๏ผๅฐๆฐๆฎๆๅผ็็ปดๅบฆๆฐ็ฎ\n min_values = _deflatten_as(x_flat.min(), x)\n max_values = _deflatten_as(x_flat.max(), x)\n else:\n min_values = _deflatten_as(x_flat.min(-1)[0], x)\n max_values = _deflatten_as(x_flat.max(-1)[0], x)\n\n if reduce_dim is not None: # ๅฆๆreduce_dim ไธๆฏNone๏ผ้ฃไน่ฟ่ก็ธๅบ็ๅค็๏ผ็ผฉๅ็ธๅบ็็ปดๅบฆ๏ผ๏ผไฝๆฏkeepdim \n if reduce_type == 'mean':\n min_values = min_values.mean(reduce_dim, keepdim=keepdim)\n max_values = max_values.mean(reduce_dim, keepdim=keepdim)\n else:\n min_values = min_values.min(reduce_dim, keepdim=keepdim)[0]\n max_values = max_values.max(reduce_dim, keepdim=keepdim)[0]\n\n range_values = max_values - min_values # ๅพๅฐๆๅคงๆๅฐๅผไน้ด็่ๅด็ปๆ๏ผไนๅๆณจๅไธไธชQParams็็ฑป\n return QParams(range=range_values, zero_point=min_values,\n num_bits=num_bits)\n\n\n# ่ฟไธช็ฑปๅฎไนไบไธไธชๅๅ้ๅ็ๅบๆฌๅค็๏ผๅ
ๆฌไบๅๅๅๅๅ็่ฟ็จ\nclass UniformQuantize(InplaceFunction):\n\n @staticmethod\n def forward(ctx, input, num_bits=None, qparams=None, flatten_dims=_DEFAULT_FLATTEN,\n reduce_dim=0, dequantize=True, signed=False, stochastic=False, inplace=False):\n\n ctx.inplace = inplace\n\n if ctx.inplace:\n ctx.mark_dirty(input)\n output = input\n else:\n output = input.clone()\n\n if qparams is None:\n assert num_bits is not None, \"either provide qparams of num_bits to quantize\"\n qparams = calculate_qparams(\n input, num_bits=num_bits, flatten_dims=flatten_dims, reduce_dim=reduce_dim) \n # ๅฆๆๆฒกๆ็ดๆฅ็ปๅบqparams๏ผ้ฃไนๅฐฑ้่ฟ่ฎก็ฎๆฅๅพๅฐ็ธๅบ็็ปๆ\n\n zero_point = qparams.zero_point\n num_bits = qparams.num_bits\n qmin = -(2. ** (num_bits - 1)) if signed else 0. # ๆฏ่ฟ่กๆ็ฌฆๅท่ฟๆฏๆ ็ฌฆๅท็้ๅ\n qmax = qmin + 2. ** num_bits - 1.\n scale = qparams.range / (qmax - qmin) # ้ฃไนๅฏไปฅๅพๅฐ็ธๅบ็scale๏ผไนๅฐฑๆฏ็ดๆฅ้่ฟrangeๆฅๅพๅฐ\n\n min_scale = torch.tensor(1e-8).expand_as(scale).cuda() # ๆๅฐ็scale \n scale = torch.max(scale, min_scale) # ็ถๅ่ฎพ็ฝฎไธไธชscale ็ ๆฏ่พ\n\n with torch.no_grad():\n output.add_(qmin * scale - zero_point).div_(scale)\n if stochastic:\n noise = output.new(output.shape).uniform_(-0.5, 0.5)\n output.add_(noise)\n # quantize\n output.clamp_(qmin, qmax).round_()\n\n if dequantize:\n output.mul_(scale).add_(\n zero_point - qmin * scale) # dequantize\n return output\n\n @staticmethod\n def backward(ctx, grad_output):\n # straight-through estimator\n grad_input = grad_output # STE ๆนๆณ๏ผ ้ๅ้จๅไธๆนๅๅฎ้
็ๆ้็ๆขฏๅบฆ\n return grad_input, None, None, None, None, None, None, None, None\n\n\nclass UniformQuantizeGrad(InplaceFunction):\n\n @staticmethod\n def forward(ctx, input, num_bits=None, qparams=None, flatten_dims=_DEFAULT_FLATTEN_GRAD,\n reduce_dim=0, dequantize=True, signed=False, stochastic=True):\n ctx.num_bits = num_bits\n ctx.qparams = qparams\n ctx.flatten_dims = flatten_dims\n ctx.stochastic = stochastic\n ctx.signed = signed\n ctx.dequantize = dequantize\n ctx.reduce_dim = reduce_dim\n ctx.inplace = False\n return input\n\n @staticmethod\n def backward(ctx, grad_output):\n qparams = ctx.qparams\n with torch.no_grad():\n if qparams is None:\n assert ctx.num_bits is not None, \"either provide qparams of num_bits to quantize\"\n qparams = calculate_qparams(\n grad_output, num_bits=ctx.num_bits, flatten_dims=ctx.flatten_dims, reduce_dim=ctx.reduce_dim,\n reduce_type='extreme')\n\n grad_input = quantize(grad_output, num_bits=None,\n qparams=qparams, flatten_dims=ctx.flatten_dims, reduce_dim=ctx.reduce_dim,\n dequantize=True, signed=ctx.signed, stochastic=ctx.stochastic, inplace=False)\n return grad_input, None, None, None, None, None, None, None\n\n\ndef conv2d_biprec(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1, num_bits_grad=None):\n out1 = F.conv2d(input.detach(), weight, bias,\n stride, padding, dilation, groups)\n out2 = F.conv2d(input, weight.detach(), bias.detach() if bias is not None else None,\n stride, padding, dilation, groups)\n out2 = quantize_grad(out2, num_bits=num_bits_grad, flatten_dims=(1, -1))\n return out1 + out2 - out1.detach()\n\n\ndef linear_biprec(input, weight, bias=None, num_bits_grad=None):\n out1 = F.linear(input.detach(), weight, bias)\n out2 = F.linear(input, weight.detach(), bias.detach()\n if bias is not None else None)\n out2 = quantize_grad(out2, num_bits=num_bits_grad)\n return out1 + out2 - out1.detach()\n\n\ndef quantize(x, num_bits=None, qparams=None, flatten_dims=_DEFAULT_FLATTEN, reduce_dim=0, dequantize=True, signed=False,\n stochastic=False, inplace=False):\n # ่ฟ้ๆไธค็ง้ๅๆนๅผ๏ผไธ็งๆฏ้่ฟqparams ๆฅ่ฟ่กๆงๅถ๏ผ่ๅฆไธ็งๆฏ้่ฟnum_bits ๆฅ่ฟ่กๆงๅถ\n if qparams: # ๅฝๆ็ธๅบ็่ๅดๅๆฐ็ๆถๅ\n if qparams.num_bits: # ๅฆๆ่ฎพ็ฝฎไบ็ธๅบ็num_bits\n return UniformQuantize().apply(x, num_bits, qparams, flatten_dims, reduce_dim, dequantize, signed,\n stochastic, inplace)\n elif num_bits:\n return UniformQuantize().apply(x, num_bits, qparams, flatten_dims, reduce_dim, dequantize, signed, stochastic,\n inplace)\n\n return x\n\n\ndef quantize_grad(x, num_bits=None, qparams=None, flatten_dims=_DEFAULT_FLATTEN_GRAD, reduce_dim=0, dequantize=True,\n signed=False, stochastic=True):\n if qparams:\n if qparams.num_bits:\n return UniformQuantizeGrad().apply(x, num_bits, qparams, flatten_dims, reduce_dim, dequantize, signed,\n stochastic)\n elif num_bits:\n return UniformQuantizeGrad().apply(x, num_bits, qparams, flatten_dims, reduce_dim, dequantize, signed,\n stochastic)\n\n return x\n\n\nclass QuantMeasure(nn.Module):\n \"\"\"docstring for QuantMeasure.\"\"\"\n\n def __init__(self, shape_measure=(1,), flatten_dims=_DEFAULT_FLATTEN,\n inplace=False, dequantize=True, stochastic=False, momentum=0.9, measure=False):\n super(QuantMeasure, self).__init__()\n self.register_buffer('running_zero_point', torch.zeros(*shape_measure))\n self.register_buffer('running_range', torch.zeros(*shape_measure))\n self.measure = measure\n if self.measure:\n self.register_buffer('num_measured', torch.zeros(1))\n self.flatten_dims = flatten_dims\n self.momentum = momentum\n self.dequantize = dequantize\n self.stochastic = stochastic\n self.inplace = inplace\n\n def forward(self, input, num_bits, qparams=None):\n\n if self.training or self.measure:\n if qparams is None:\n qparams = calculate_qparams(\n input, num_bits=num_bits, flatten_dims=self.flatten_dims, reduce_dim=0, reduce_type='extreme')\n with torch.no_grad():\n if self.measure:\n momentum = self.num_measured / (self.num_measured + 1)\n self.num_measured += 1\n else:\n momentum = self.momentum\n self.running_zero_point.mul_(momentum).add_(\n qparams.zero_point * (1 - momentum))\n self.running_range.mul_(momentum).add_(\n qparams.range * (1 - momentum))\n else:\n qparams = QParams(range=self.running_range,\n zero_point=self.running_zero_point, num_bits=num_bits)\n if self.measure:\n return input\n else:\n q_input = quantize(input, qparams=qparams, dequantize=self.dequantize,\n stochastic=self.stochastic, inplace=self.inplace)\n return q_input\n\n\nclass CPTConv2d(nn.Conv2d):\n \"\"\"docstring for QConv2d.\"\"\"\n\n def __init__(self, in_channels, out_channels, kernel_size,\n stride=1, padding=0, dilation=1, groups=1, bias=True):\n super(CPTConv2d, self).__init__(in_channels, out_channels, kernel_size,\n stride, padding, dilation, groups, bias)\n\n self.quantize_input = QuantMeasure(shape_measure=(1, 1, 1, 1), flatten_dims=(1, -1))\n self.stride = stride\n\n def forward(self, input, actbits, wbits, gbits):\n if actbits == 0 and wbits==0:\n output = F.conv2d(input, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups)\n return output\n\n if self.bias is not None:\n qbias = quantize(\n self.bias, num_bits=wbits,\n flatten_dims=(0, -1))\n else:\n qbias = None\n\n weight_qparams = calculate_qparams(self.weight, num_bits=wbits, flatten_dims=(1, -1),\n reduce_dim=None)\n qweight = quantize(self.weight, qparams=weight_qparams)\n\n qinput = self.quantize_input(input, actbits)\n output = F.conv2d(qinput, qweight, qbias, self.stride, self.padding, self.dilation, self.groups)\n output = quantize_grad(output, num_bits=gbits, flatten_dims=(1, -1))\n\n return output\n \n\n def conv2d_quant_act(self, input_fw, input_bw, weight, bias=None, stride=1, padding=0, dilation=1, groups=1,\n error_bits=0, gc_bits=0):\n out1 = F.conv2d(input_fw, weight.detach(), bias.detach() if bias is not None else None,\n stride, padding, dilation, groups)\n out2 = F.conv2d(input_bw.detach(), weight, bias,\n stride, padding, dilation, groups)\n out1 = quantize_grad(out1, num_bits=error_bits)\n out2 = quantize_grad(out2, num_bits=gc_bits)\n return out1 + out2 - out2.detach()\n\n\n\nif __name__ == '__main__':\n x = torch.rand(2, 3)\n x_q = quantize(x, flatten_dims=(-1), num_bits=8, dequantize=True)\n print(x)\n print(x_q)"
] | [
[
"torch.nn.functional.conv2d",
"torch.rand",
"torch.no_grad",
"torch.tensor",
"torch.max",
"torch.zeros"
]
] |
kyunghoon-jung/MacaronRL | [
"b95be35fc95be7eb5aede2315a714984b282587a"
] | [
"Value_Based/Rainbow/agent.py"
] | [
"import gym\nimport numpy as np\nimport time\nimport os\nimport cv2\nimport matplotlib.pyplot as plt\nfrom collections import deque\nfrom IPython.display import clear_output\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim \nimport torch.nn.functional as F \nfrom torch.nn.utils import clip_grad_norm_\n\nfrom qnetwork import QNetwork \nfrom replay_buffer import PrioritizedReplayBuffer\n\nimport wandb\n\nclass Agent:\n def __init__(self, \n env: 'Environment',\n input_frame: ('int: the number of channels of input image'),\n input_dim: ('int: the width and height of pre-processed input image'),\n initial_std: ('float: the standard deviation of noise'), # Variables for NoisyNet\n tot_train_frames: ('int: Total number of frames to be trained'),\n skipped_frame: ('int: The number of skipped frames'),\n gamma: ('float: Discount Factor'),\n alpha: ('float: PER hyperparameter'), # Increasing alpha means emphasizing the priority \n beta: ('float: PER hyperparameter'), # Increasing beta means more strong correction.\n epsilon_for_priority: ('float: PER hyperparameter'), # Preventing too small priority.\n n_step: ('int: n-step size for Multi-step TD learning'), # Variables for multi-step TD\n Vmax: ('int: The maximum Q value')=10, # Variables for Categprocal\n Vmin: ('int: The minimum Q value')=-10, # Variables for Categprocal\n n_atoms: ('int: The number of atoms')=51, # Variables for Categprocal \n target_update_freq: ('int: Target Update Frequency (unit: frames)')=8000, # Defalut value is choosen as in the paper. (skipped frames=4)\n behave_update_freq: ('int: Behavioral Network Update Frequency (unit: frames')=4,\n grad_clip: ('float: The value bounding gradient norm.')=10,\n update_type: ('str: Update type for target network. Hard or Soft')='hard',\n soft_update_tau: ('float: Soft update ratio')=None,\n batch_size: ('int: Update batch size')=32,\n buffer_size: ('int: Replay buffer size')=1000000,\n update_start_buffer_size: ('int: Update starting buffer size')=50000,\n learning_rate: ('float: Learning rate')=0.0004,\n device_num: ('int: GPU device number')=0,\n rand_seed: ('int: Random seed')=None,\n plot_option: ('str: Plotting option')=False,\n model_path: ('str: Model saving path')='./', \n trained_model_path: ('str: Trained model path')='',\n is_render: ('bool: Whether rendering is on or off')=False,\n vis_env_id: ('str: The environment name of visdom.')='main',\n ): \n \n self.action_dim = env.action_space.n\n self.device = torch.device(f'cuda:{device_num}' if torch.cuda.is_available() else 'cpu')\n self.model_path = model_path\n self.scores = [-10000]\n self.avg_scores = [-10000]\n\n self.env = env\n self.input_frames = input_frame\n self.input_dim = input_dim\n self.tot_train_frames = tot_train_frames\n self.skipped_frame = skipped_frame\n self.gamma = gamma\n self.target_update_freq = target_update_freq\n self.behave_update_freq = behave_update_freq\n self.update_type = update_type\n self.tau = soft_update_tau\n self.batch_size = batch_size\n self.buffer_size = buffer_size\n self.update_start = update_start_buffer_size\n self.seed = rand_seed\n self.plot_option = plot_option\n self.is_render = is_render\n self.initial_std = initial_std # NoisyNet Variable\n self.epi_max_frame = 108000 # same as the Rainbow paper\n self.grad_clip = grad_clip\n\n # hyper parameters and varibles for C51\n self.n_atoms = n_atoms \n self.Vmin = Vmin \n self.Vmax = Vmax \n self.dz = (Vmax - Vmin) / (n_atoms - 1) \n self.support = torch.linspace(Vmin, Vmax, n_atoms).to(self.device) \n self.expanded_support = self.support.expand((batch_size, self.action_dim, n_atoms)).to(self.device)\n\n # hyper parameters for PER\n self.alpha = alpha\n self.beta = beta\n self.beta_step = (1.0 - beta) / tot_train_frames\n self.epsilon_for_priority = epsilon_for_priority\n\n self.q_behave = QNetwork((self.input_frames, self.input_dim, self.input_dim), self.action_dim, initial_std, n_atoms=self.n_atoms).to(self.device)\n self.q_target = QNetwork((self.input_frames, self.input_dim, self.input_dim), self.action_dim, initial_std, n_atoms=self.n_atoms).to(self.device)\n # Load trained model\n if trained_model_path:\n self.q_behave.load_state_dict(torch.load(trained_model_path))\n print(\"Trained model is loaded successfully.\")\n self.q_target.load_state_dict(self.q_behave.state_dict())\n self.q_target.eval()\n self.optimizer = optim.Adam(self.q_behave.parameters(), lr=learning_rate, eps=1e-4) # Epsilon value in the Rainbow paper \n\n # PER replay buffer\n self.memory = PrioritizedReplayBuffer(self.buffer_size, (self.input_frames, self.input_dim, self.input_dim), self.batch_size, self.alpha)\n\n # Variables for multi-step TD\n self.n_step = n_step\n self.n_step_state_buffer = deque(maxlen=n_step)\n self.n_step_action_buffer = deque(maxlen=n_step)\n self.n_step_reward_buffer = deque(maxlen=n_step)\n self.gamma_list = [gamma**i for i in range(n_step)]\n\n if self.plot_option == 'wandb':\n wandb.watch(self.q_behave)\n\n if self.is_render:\n import visdom\n print(\"Rendering mode is on.\")\n self.action_list = {i:name for i, name in enumerate(env.unwrapped.get_action_meanings())}\n self.vis = visdom.Visdom(env=vis_env_id)\n self.vis.close()\n self.state_plots_dic = {}\n # Set plotting frames for each time step. (the number of time steps == n_stacked)\n self.state_plot = self.vis.heatmap(np.zeros((self.input_dim, self.input_dim)))\n self.state_meta = self.vis.text(\"Q_values.\")\n\n def processing_resize_and_gray(self, frame):\n frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) # Pure\n # frame = cv2.cvtColor(frame[:177, 32:128, :], cv2.COLOR_RGB2GRAY) # Boxing\n # frame = cv2.cvtColor(frame[2:198, 7:-7, :], cv2.COLOR_RGB2GRAY) # Breakout\n frame = cv2.resize(frame, dsize=(self.input_dim, self.input_dim)).reshape(self.input_dim, self.input_dim).astype(np.uint8)\n return frame \n\n def get_init_state(self, is_eval=False):\n\n init_state = np.zeros((self.input_frames, self.input_dim, self.input_dim))\n\n init_frame = self.env.reset()\n init_state[0] = self.processing_resize_and_gray(init_frame)\n \n for i in range(1, self.input_frames): \n action = self.env.action_space.sample()\n for j in range(self.skipped_frame):\n state, _, _, _ = self.env.step(action) \n state, _, _, _ = self.env.step(action) \n init_state[i] = self.processing_resize_and_gray(state) \n return init_state\n\n def get_state(self, state, action, skipped_frame=0):\n '''\n input_frames: how many frames to be merged\n input_size: hight and width of input resized image\n skipped_frame: how many frames to be skipped\n '''\n next_state = np.zeros((self.input_frames, self.input_dim, self.input_dim))\n for i in range(len(state)-1):\n next_state[i] = state[i+1]\n\n rewards = 0\n dones = 0\n for _ in range(skipped_frame-1):\n state, reward, done, _ = self.env.step(action) \n rewards += reward \n dones += int(done) \n state, reward, done, _ = self.env.step(action) \n next_state[-1] = self.processing_resize_and_gray(state) \n rewards += reward \n dones += int(done) \n return rewards, next_state, dones\n\n def select_action(self, state: 'Must be pre-processed in the same way while updating current Q network. See def _compute_loss'):\n with torch.no_grad():\n state = torch.FloatTensor(state).to(self.device).unsqueeze(0)/255\n \n # Categorical RL\n Expected_Qs = (self.q_behave(state)*self.expanded_support[0]).sum(2)\n action = Expected_Qs.argmax(1)\n return Expected_Qs.detach().cpu().numpy(), action.detach().item()\n\n def n_step_store(self, state, action, reward):\n '''method for n-step_TD'''\n self.n_step_state_buffer.append(state)\n self.n_step_action_buffer.append(action)\n self.n_step_reward_buffer.append(reward)\n\n def get_first_transitions(self, n_step=1):\n '''method for n-step_TD'''\n state = self.get_init_state()\n for _ in range(n_step):\n _, action = self.select_action(state)\n reward, next_state, done = self.get_state(state, action)\n self.n_step_store(state, action, reward)\n state = next_state\n rewards = sum([gamma*reward for gamma, reward in zip(self.gamma_list, self.n_step_reward_buffer)])\n self.memory.store(self.n_step_state_buffer[0], self.n_step_action_buffer[0], rewards, next_state, done)\n return next_state\n\n def update_current_q_net(self):\n batch = self.memory.batch_load(self.beta)\n loss, sample_wise_loss = self._compute_loss(batch)\n\n self.optimizer.zero_grad()\n loss.backward()\n clip_grad_norm_(self.q_behave.parameters(), self.grad_clip) # Gradient clipping mentioned in Dueling paper.\n self.optimizer.step()\n\n # For PER: update priorities of the samples. \n sample_wise_loss = sample_wise_loss.detach().cpu().numpy()\n batch_priorities = sample_wise_loss + self.epsilon_for_priority\n self.memory.update_priorities(batch['indices'], batch_priorities)\n return loss.item()\n\n def target_soft_update(self):\n for target_param, current_param in zip(self.q_target.parameters(), self.q_behave.parameters()):\n target_param.data.copy_(self.tau*current_param.data + (1.0-self.tau)*target_param.data)\n\n def target_hard_update(self):\n self.q_target.load_state_dict(self.q_behave.state_dict())\n\n def train(self):\n tic = time.time()\n losses = []\n score = 0\n\n print(\"Storing initial buffer..\")\n state = self.get_first_transitions(self.n_step)\n init_store_cnt = 0 # For restoring multi-step TD transitions until the agent reaches done state.\n epi_frame_count = 0\n while 1:\n init_store_cnt += 1\n _, action = self.select_action(state)\n reward, next_state, done = self.get_state(state, action)\n self.n_step_store(state, action, np.clip(reward, -1, 1))\n rewards = sum([gamma*reward for gamma, reward in zip(self.gamma_list, self.n_step_reward_buffer)])\n self.memory.store(self.n_step_state_buffer[0], self.n_step_action_buffer[0], rewards, next_state, done)\n state = next_state\n epi_frame_count += 1\n if done or (epi_frame_count==self.epi_max_frame): \n state = self.get_first_transitions(self.n_step)\n epi_frame_count = 0\n if init_store_cnt>self.update_start: break\n\n print(\"Done. Start learning..\")\n epi_Qs=[]\n history_store = []\n behave_update_cnt = 0\n target_update_cnt = 0\n for frame_idx in range(1, self.tot_train_frames+1):\n Qs, action = self.select_action(state)\n reward, next_state, done = self.get_state(state, action, skipped_frame=self.skipped_frame)\n self.n_step_store(state, action, np.clip(reward, -1, 1)) \n rewards = sum([gamma*reward for gamma, reward in zip(self.gamma_list, self.n_step_reward_buffer)])\n self.memory.store(self.n_step_state_buffer[0], self.n_step_action_buffer[0], rewards, next_state, done)\n history_store.append([self.n_step_state_buffer[0][0], Qs, self.n_step_action_buffer[0], reward, next_state[0], done])\n # print(f\"(F:{frame_idx}, R:{rewards}, A:{action}), Qs: {np.round(Qs, 2)}\", end='\\r')\n \n behave_update_cnt = (behave_update_cnt+1) % self.behave_update_freq \n target_update_cnt = (target_update_cnt+1) % self.target_update_freq\n if behave_update_cnt == 0:\n loss = self.update_current_q_net()\n losses.append(loss)\n if self.update_type=='soft': self.target_soft_update()\n elif target_update_cnt==0: self.target_hard_update()\n self.q_behave.init_noise()\n self.q_target.init_noise()\n score += reward\n epi_Qs.append(Qs)\n epi_frame_count += 1\n self.beta = min(self.beta+self.beta_step, 1.0) # for PER. beta is increased linearly up to 1.0 until the end of training\n if done or (epi_frame_count==self.epi_max_frame): # As in the paper, check if reaching the maximum steps per episode.\n self.model_save(frame_idx, score, self.scores, self.avg_scores, history_store, tic)\n self.plot_status(frame_idx, score, epi_Qs, losses)\n state = self.get_first_transitions(self.n_step)\n score = 0\n losses = []\n epi_Qs = []\n history_store = []\n epi_frame_count = 0\n else: state = next_state\n if self.is_render and (frame_idx % 5 == 0):\n self.render(state[0], action, Qs, frame_idx)\n print(\"Total training time: {}(hrs)\".format((time.time()-tic)/3600))\n\n def model_save(self, frame_idx, score, scores, avg_scores, history_store, tic):\n '''model save when condition is satisfied'''\n if score > max(self.scores):\n torch.save(self.q_behave.state_dict(), self.model_path+'{}_Highest_Score_{}.pt'.format(frame_idx, score))\n training_time = round((time.time()-tic)/3600, 1)\n np.save(self.model_path+'{}_history_Highest_Score_{}_{}hrs.npy'.format(frame_idx, score, training_time), np.array(history_store, dtype=object))\n print(\" | Model saved. Highest score: {}, Training time: {}hrs\".format(score, training_time), ' /'.join(os.getcwd().split('/')[-3:]))\n self.scores.append(score)\n if np.mean(self.scores[-10:]) > max(self.avg_scores):\n torch.save(self.q_behave.state_dict(), self.model_path+'{}_Avg_Score_{}.pt'.format(frame_idx, np.mean(self.scores[-10:])))\n training_time = round((time.time()-tic)/3600, 1)\n np.save(self.model_path+'{}_history_Score_{}_{}hrs.npy'.format(frame_idx, score, training_time), np.array(history_store, dtype=object))\n print(\" | Model saved. Recent scores: {}, Training time: {}hrs\".format(self.scores[-10:], training_time), ' /'.join(os.getcwd().split('/')[-3:]))\n self.avg_scores.append(np.mean(self.scores[-10:]))\n\n def plot_status(self, frame_idx, score, epi_Qs, losses):\n if self.plot_option=='inline': \n self._plot(frame_idx, self.scores, losses)\n elif self.plot_option=='wandb': \n wandb.log({'Score': score, \n 'Episodic accumulated frames': len(epi_Qs), \n 'Episode Count': len(self.scores)-1, \n 'loss(10 frames avg)': np.mean(losses[-10:]),\n 'Q(max_avg)': np.array(epi_Qs).max(1).mean(),\n 'Q(min_avg)': np.array(epi_Qs).min(1).mean(),\n 'Q(mean)': np.array(epi_Qs).flatten().mean(),\n 'Q(max)': np.array(epi_Qs).flatten().max(),\n 'Q(min)': np.array(epi_Qs).flatten().min()}, step=frame_idx)\n print(score, end='\\r')\n else: \n print(score, end='\\r')\n\n def _compute_loss(self, batch: \"Dictionary (S, A, R', S', Dones)\"):\n # If normalization is used, it must be applied to 'state' and 'next_state' here. ex) state/255\n states = torch.FloatTensor(batch['states']).to(self.device) / 255\n next_states = torch.FloatTensor(batch['next_states']).to(self.device) / 255\n actions = torch.LongTensor(batch['actions']).to(self.device)\n weights = torch.FloatTensor(batch['weights'].reshape(-1, 1)).to(self.device)\n rewards = torch.FloatTensor(batch['rewards'].reshape(-1, 1)).to(self.device)\n dones = torch.FloatTensor(batch['dones'].reshape(-1, 1)).to(self.device)\n \n log_behave_Q_dist = self.q_behave(states)[range(self.batch_size), actions].log()\n with torch.no_grad():\n # Compuating projected distribution for a categorical loss\n behave_next_Q_dist = self.q_behave(next_states)\n next_actions = torch.sum(behave_next_Q_dist*self.expanded_support, 2).argmax(1)\n target_next_Q_dist = self.q_target(next_states)[range(self.batch_size), next_actions] # Double DQN.\n\n Tz = rewards + (self.gamma**self.n_step)*(1 - dones)*self.expanded_support[:,0]\n Tz.clamp_(self.Vmin, self.Vmax)\n b = (Tz - self.Vmin) / self.dz\n l = b.floor().long()\n u = b.ceil().long()\n\n l[(l==u) & (u>0)] -= 1\n u[(u==0) & (l==0)] += 1\n\n batch_init_indices = torch.linspace(0, (self.batch_size-1)*self.n_atoms, self.batch_size).long().unsqueeze(1).expand(self.batch_size, self.n_atoms).to(self.device)\n\n proj_dist = torch.zeros(self.batch_size, self.n_atoms).to(self.device)\n proj_dist.view(-1).index_add_(0, (l+batch_init_indices).view(-1), (target_next_Q_dist*(u-b)).view(-1))\n proj_dist.view(-1).index_add_(0, (u+batch_init_indices).view(-1), (target_next_Q_dist*(b-l)).view(-1))\n\n sample_wise_loss = torch.sum(-proj_dist*log_behave_Q_dist, 1)\n loss = (weights * sample_wise_loss).mean()\n return loss, sample_wise_loss\n\n def test(self):\n ''' Return an episodic history when the episode is done. '''\n episode_history = []\n epi_frame_count = 0\n state = self.get_first_transitions(self.n_step)\n while 1:\n _, action = self.select_action(state)\n reward, next_state, done = self.get_state(state, action)\n state = next_state\n epi_frame_count += 1\n episode_history.append(state[0], reward, next_state[0], done)\n if done or (epi_frame_count==self.epi_max_frame): \n break\n return episode_history\n\n def render(self, state, action, Qs, frame_idx):\n self.vis.text(f'Frame:{frame_idx}, Q_current_value: {np.round(Qs, 3)}<br>Argmax: {Qs.argmax()}<br>', win=self.state_meta)\n self.vis.heatmap(\n state[::-1,:],\n opts={'title': f'Action: {self.action_list[action]}'},\n win=self.state_plot\n )\n\n def _plot(self, frame_idx, scores, losses):\n clear_output(True) \n plt.figure(figsize=(20, 5), facecolor='w') \n plt.subplot(121) \n plt.title('frame %s. score: %s' % (frame_idx, np.mean(scores[-10:])))\n plt.plot(scores) \n plt.subplot(122) \n plt.title('loss') \n plt.plot(losses) \n plt.show() \n"
] | [
[
"torch.sum",
"torch.FloatTensor",
"torch.load",
"numpy.zeros",
"matplotlib.pyplot.figure",
"torch.linspace",
"torch.no_grad",
"torch.zeros",
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"torch.cuda.is_available",
"numpy.clip",
"numpy.array",
"matplotlib.pyplot.plot",
"torch.LongTensor",
"numpy.round",
"numpy.mean"
]
] |
BlockchainClimateInstitute/price_microservice | [
"33c62abe6d107d1da2f54e9e44a90f18aaf916a9"
] | [
"evalml/tests/pipeline_tests/classification_pipeline_tests/test_classification.py"
] | [
"from itertools import product\n\nimport pandas as pd\nimport pytest\nfrom pandas.testing import assert_series_equal\n\nfrom evalml.demos import load_breast_cancer, load_wine\n\n\[email protected](\"problem_type\", [\"binary\", \"multi\"])\ndef test_new_unique_targets_in_score(X_y_binary, logistic_regression_binary_pipeline_class,\n X_y_multi, logistic_regression_multiclass_pipeline_class, problem_type):\n if problem_type == \"binary\":\n X, y = X_y_binary\n pipeline = logistic_regression_binary_pipeline_class(parameters={\"Logistic Regression Classifier\": {\"n_jobs\": 1}})\n objective = 'Log Loss Binary'\n elif problem_type == \"multi\":\n X, y = X_y_multi\n pipeline = logistic_regression_multiclass_pipeline_class(parameters={\"Logistic Regression Classifier\": {\"n_jobs\": 1}})\n objective = 'Log Loss Multiclass'\n pipeline.fit(X, y)\n with pytest.raises(ValueError, match=\"y contains previously unseen labels\"):\n pipeline.score(X, pd.Series([4] * len(y)), [objective])\n\n\[email protected](\"problem_type,use_ints\", product([\"binary\", \"multi\"], [True, False]))\ndef test_pipeline_has_classes_property(logistic_regression_binary_pipeline_class,\n logistic_regression_multiclass_pipeline_class, problem_type, use_ints):\n if problem_type == \"binary\":\n X, y = load_breast_cancer(return_pandas=True)\n pipeline = logistic_regression_binary_pipeline_class(parameters={\"Logistic Regression Classifier\": {\"n_jobs\": 1}})\n if use_ints:\n y = y.map({'malignant': 0, 'benign': 1})\n answer = [0, 1]\n else:\n answer = [\"benign\", \"malignant\"]\n elif problem_type == \"multi\":\n X, y = load_wine(return_pandas=True)\n pipeline = logistic_regression_multiclass_pipeline_class(parameters={\"Logistic Regression Classifier\": {\"n_jobs\": 1}})\n if use_ints:\n y = y.map({\"class_0\": 0, \"class_1\": 1, \"class_2\": 2})\n answer = [0, 1, 2]\n else:\n answer = [\"class_0\", \"class_1\", \"class_2\"]\n\n with pytest.raises(AttributeError, match=\"Cannot access class names before fitting the pipeline.\"):\n pipeline.classes_\n\n pipeline.fit(X, y)\n assert_series_equal(pd.Series(pipeline.classes_), pd.Series(answer))\n\n\ndef test_woodwork_classification_pipeline(logistic_regression_binary_pipeline_class):\n X, y = load_breast_cancer()\n mock_pipeline = logistic_regression_binary_pipeline_class(parameters={\"Logistic Regression Classifier\": {\"n_jobs\": 1}})\n mock_pipeline.fit(X, y)\n assert not pd.isnull(mock_pipeline.predict(X).to_series()).any()\n assert not pd.isnull(mock_pipeline.predict_proba(X).to_dataframe()).any().any()\n"
] | [
[
"pandas.Series"
]
] |
XiaoYaoNet/MPIRF | [
"45c6559fc2eeb51c52905fcc6dabe2075e7ffb2b"
] | [
"src/DataClass/Scanner/MScanner.py"
] | [
"# coding=UTF-8\nimport numpy as np\n\nfrom DataClass.BassClass.ScannerBase import *\n\n\nclass MScannerClass(ScannerBaseClass):\n\n def __init__(self,\n VirtualPhantom,\n SelectGradietX=2.0,\n SelectGradietY=2.0,\n DriveFrequencyX=2500000.0 / 102.0,\n DriveFrequencyY=2500000.0 / 96.0,\n DriveAmplitudeX=12e-3,\n DriveAmplitudeY=12e-3,\n RepetitionTime=6.528e-4,\n SampleFrequency=2.5e6,\n DeltaConcentration=50e-3):\n\n super().__init__(VirtualPhantom,\n SelectGradietX,\n SelectGradietY,\n DriveFrequencyX,\n DriveFrequencyY,\n DriveAmplitudeX,\n DriveAmplitudeY,\n RepetitionTime,\n SampleFrequency)\n\n self.__DeltaConcentration=DeltaConcentration\n self._init_Message(1)\n self.__reset_Voltage()\n\n # The measurement signal is Fourier transformed.\n def __reset_Voltage(self):\n self.Message[MEASUREMENT][MEASIGNAL] = np.transpose(self.Message[MEASUREMENT][MEASIGNAL])\n temp = np.fft.fft(np.transpose(self.Message[MEASUREMENT][MEASIGNAL]) * 1000)\n temp = np.transpose(temp)\n self.Message[MEASUREMENT][MEASIGNAL] = np.add(temp[:, 0], temp[:, 1])\n return True\n\n #Calculate the system matrix of MPI scanner.\n def _get_AuxSignal(self):\n\n C = np.ones((self._Xn, self._Yn,2))\n C = C * self.__DeltaConcentration\n AuxSignal=np.zeros((self._Fn,self._Xn,self._Yn,2))\n DLF = np.zeros((self._Xn, self._Yn, 2))\n for i in range(self._Fn):\n Coeff = self._CoilSensitivity * self._Phantom._Mm * self._Phantom._Bcoeff * self._DeriDH[:, i]\n DLFTemp = (1 / ((self._Phantom._Bcoeff * self._HFieldStrength[:, :, i]) ** 2)) - (\n 1 / ((np.sinh(self._Phantom._Bcoeff * self._HFieldStrength[:, :, i])) ** 2))\n DLF[:, :, 0] = DLFTemp\n DLF[:, :, 1] = DLFTemp\n s = C * Coeff\n AuxSignal[i, :, :, :] = s * DLF\n\n AuxSignal = np.reshape(AuxSignal, (self._Fn,self._Xn*self._Yn,2))\n AuxSignal = AuxSignal / self.__DeltaConcentration\n tempx = AuxSignal[:, :, 0]\n tempy = AuxSignal[:, :, 1]\n\n tempx = np.fft.fft(np.transpose(tempx) * 1000)\n tempy = np.fft.fft(np.transpose(tempy) * 1000)\n AuxSignal = np.transpose(np.add(tempx, tempy))\n return AuxSignal"
] | [
[
"numpy.ones",
"numpy.transpose",
"numpy.zeros",
"numpy.reshape",
"numpy.sinh",
"numpy.add"
]
] |
Abezzam10/Recommender | [
"af72672b22a2c716706afb3e8fc120b5d498ecc3"
] | [
"Recommender_sys.py"
] | [
"import pandas as pd\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.metrics.pairwise import pairwise_distances\r\nimport numpy as np\r\n\r\n# pass in column names for each CSV as the column name is not given in the file and read them using pandas.\r\n# You can check the column names from the readme file\r\n\r\n#Reading users file:\r\nu_cols = ['user_id', 'age', 'sex', 'occupation', 'zip_code']\r\nusers = pd.read_csv('ml-100k/u.user', sep='|', names=u_cols,encoding='latin-1')\r\n\r\n#Reading ratings file:\r\nr_cols = ['user_id', 'movie_id', 'rating', 'unix_timestamp']\r\nratings = pd.read_csv('ml-100k/u.data', sep='\\t', names=r_cols,encoding='latin-1')\r\n\r\n#Reading items file:\r\ni_cols = ['movie id', 'movie title' ,'release date','video release date', 'IMDb URL', 'unknown', 'Action', 'Adventure',\r\n'Animation', 'Children\\'s', 'Comedy', 'Crime', 'Documentary', 'Drama', 'Fantasy',\r\n'Film-Noir', 'Horror', 'Musical', 'Mystery', 'Romance', 'Sci-Fi', 'Thriller', 'War', 'Western']\r\nitems = pd.read_csv('ml-100k/u.item', sep='|', names=i_cols,\r\nencoding='latin-1')\r\n\r\nprint(users.shape)\r\nusers.head()\r\n\r\nitems.head()\r\n\r\nr_cols = ['user_id', 'movie_id', 'rating', 'unix_timestamp']\r\nratings_train = pd.read_csv('ml-100k/ua.base', sep='\\t', names=r_cols, encoding='latin-1')\r\nratings_test = pd.read_csv('ml-100k/ua.test', sep='\\t', names=r_cols, encoding='latin-1')\r\nprint(ratings_train.shape, ratings_test.shape)\r\n\r\nn_users = ratings.user_id.unique().shape[0]\r\nn_items = ratings.movie_id.unique().shape[0]\r\n\r\n#Create Matrices:\r\ndata_matrix = np.zeros((n_users, n_items))\r\nfor line in ratings.itertuples():\r\n data_matrix[line[1]-1, line[2]-1] = line[3]\r\n\r\n#pairwise distance function:\r\nuser_similarity = pairwise_distances(data_matrix, metric='cosine')\r\nitem_similarity = pairwise_distances(data_matrix.T, metric='cosine')\r\n\r\ndef predict(ratings, similarity, type='user'):\r\n if type == 'user':\r\n mean_user_rating = ratings.mean(axis=1)\r\n #We use np.newaxis so that mean_user_rating has same format as ratings\r\n ratings_diff = (ratings - mean_user_rating[:, np.newaxis])\r\n pred = mean_user_rating[:, np.newaxis] + similarity.dot(ratings_diff) / np.array([np.abs(similarity).sum(axis=1)]).T\r\n elif type == 'item':\r\n pred = ratings.dot(similarity) / np.array([np.abs(similarity).sum(axis=1)])\r\n return pred\r\n\r\nuser_prediction = predict(data_matrix, user_similarity, type='user')\r\nitem_prediction = predict(data_matrix, item_similarity, type='item')"
] | [
[
"pandas.read_csv",
"numpy.abs",
"numpy.zeros",
"sklearn.metrics.pairwise.pairwise_distances"
]
] |
eashanadhikarla/kibana-data-retrieval | [
"167c1595f2fbb622e4549f598b272a0fe2163089"
] | [
"pacing/model.py"
] | [
"from __future__ import absolute_import, print_function\n\n# --- System ---\nimport os\nimport sys\nimport time\nimport warnings\n\n# --- Utility ---\nimport pandas as pd\nimport numpy as np\nimport math\nimport random\nimport logging\nimport pickle\nimport warnings\nwarnings.filterwarnings('ignore')\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import preprocessing\n\n# --- Plot ---\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nimport seaborn as sns\n\n# --- Pytorch ---\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.backends.cudnn as cudnn\n\nfrom torch.utils.data import Dataset, DataLoader, TensorDataset\nfrom tqdm import tqdm\nfrom datetime import datetime\nfrom torch.utils.data import random_split\n\n# -----------------------------------------------------------\n# random weight initialization\ndef seed_everything(seed=42):\n random.seed(seed)\n os.environ['PYTHONHASHSEED'] = str(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.benchmark = False\n\nseed_everything()\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nroot_dir = os.getcwd()\n\n# -----------------------------------------------------------\n# data loading and preprocessing\ndataPath = \"data/statistics (pacing).csv\"\ndf = pd.read_csv(dataPath)\n\n# Dropping columns that are not required at the moment\ndf = df.drop(columns=[ 'Unnamed: 0', 'UUID', 'HOSTNAME', 'ALIAS', 'TIMESTAMP',\n 'THROUGHPUT (Receiver)', 'LATENCY (min.)', 'LATENCY (max.)', \n 'CONGESTION (Receiver)', 'BYTES (Receiver)'\n ])\n\n# Pre-processing\npacing = df['PACING'].values\nfor i, p in enumerate(pacing):\n v, _ = p.split(\"gbit\")\n pacing[i] = int(v)\n\ndf['PACING'] = pacing\ndf['CONGESTION (Sender)'] = (df['CONGESTION (Sender)'] == 'cubic').astype(int)\n\nX = df[['THROUGHPUT (Sender)', 'LATENCY (mean)', 'RETRANSMITS', 'STREAMS', 'CONGESTION (Sender)']].values\ny = df['PACING'].values\ny = y.astype('int')\n\n# Normalization\nminmax_scale = preprocessing.MinMaxScaler().fit(df[['THROUGHPUT (Sender)', 'LATENCY (mean)', 'RETRANSMITS', 'STREAMS', 'CONGESTION (Sender)']])\ndf_minmax = minmax_scale.transform(df[['THROUGHPUT (Sender)', 'LATENCY (mean)', 'RETRANSMITS', 'STREAMS', 'CONGESTION (Sender)']])\n\nfinal_df = pd.DataFrame(df_minmax, columns=['THROUGHPUT (Sender)', 'LATENCY (mean)', 'RETRANSMITS', 'STREAMS', 'CONGESTION (Sender)'])\nX = final_df[['THROUGHPUT (Sender)', 'LATENCY (mean)', 'RETRANSMITS', 'STREAMS', 'CONGESTION (Sender)']].values\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, \n test_size=0.25,\n random_state=1)\n\nX_train = torch.tensor(X_train)\ny_train = torch.tensor(y_train)\nX_test = torch.tensor(X_test)\ny_test = torch.tensor(y_test) \n\n# -----------------------------------------------------------\n\n# Custom data loader for ELK stack dataset\nclass PacingDataset(Dataset):\n \"\"\"\n TensorDataset with support of transforms.\n \"\"\"\n def __init__(self, tensors, transform=None):\n assert all(tensors[0].size(0) == tensor.size(0) for tensor in tensors)\n self.tensors = tensors\n self.transform = transform\n\n def __getitem__(self, index):\n x = self.tensors[0][index]\n\n if self.transform:\n x = self.transform(x)\n\n y = self.tensors[1][index]\n\n return x, y\n\n def __len__(self):\n return self.tensors[0].size(0)\n\n# -----------------------------------------------------------\n\n# accuracy computation\ndef accuracy(model, ds, pct):\n # assumes model.eval()\n # percent correct within pct of true pacing rate\n n_correct = 0; n_wrong = 0\n\n for i in range(len(ds)):\n (X, Y) = ds[i] # (predictors, target)\n X, Y = X.float(), Y.float()\n with torch.no_grad():\n output, _, _, _ = model(X) # computed price\n\n abs_delta = np.abs(output.item() - Y.item())\n max_allow = np.abs(pct * Y.item())\n if abs_delta < max_allow:\n n_correct +=1\n else:\n n_wrong += 1\n\n acc = (n_correct * 1.0) / (n_correct + n_wrong)\n return acc*100\n\n# -----------------------------------------------------------\n\ninput_feature = 5\nlatent_feature = 16\n\nclass VAERegressor(nn.Module):\n def __init__(self):\n super(VAERegressor, self).__init__()\n \n # encoder\n self.enc1 = nn.Linear(in_features=input_feature, out_features=128)\n self.enc2 = nn.Linear(in_features=128, out_features=latent_feature*2)\n # decoder\n self.dec1 = nn.Linear(in_features=latent_feature, out_features=128)\n self.dec2 = nn.Linear(in_features=128, out_features=5)\n # Regressor\n self.fc1 = torch.nn.Linear (5, 32)\n self.fc2 = torch.nn.Linear (32, 1)\n\n torch.nn.init.xavier_uniform_(self.enc1.weight)\n torch.nn.init.zeros_(self.enc1.bias)\n torch.nn.init.xavier_uniform_(self.enc2.weight)\n torch.nn.init.zeros_(self.enc2.bias)\n torch.nn.init.xavier_uniform_(self.dec1.weight)\n torch.nn.init.zeros_(self.dec1.bias)\n torch.nn.init.xavier_uniform_(self.dec2.weight)\n torch.nn.init.zeros_(self.dec2.bias)\n torch.nn.init.xavier_uniform_(self.fc1.weight)\n torch.nn.init.zeros_(self.fc1.bias)\n torch.nn.init.xavier_uniform_(self.fc2.weight)\n torch.nn.init.zeros_(self.fc2.bias)\n\n def reparameterize(self, mu, log_var):\n \"\"\"\n :param mu: mean from the encoder's latent space\n :param log_var: log variance from the encoder's latent space\n \"\"\"\n std = torch.exp(0.5*log_var) # standard deviation\n eps = torch.randn_like(std) # `randn_like` as we need the same size\n sample = mu + (eps * std) # sampling as if coming from the input space\n return sample\n \n def forward(self, x):\n \n # encoding\n x = self.enc1(x)\n x = F.relu(x)\n x = self.enc2(x).view(-1, 2, latent_feature)\n\n # get `mu` and `log_var`\n mu = x[:, 0, :] # the first feature values as mean\n log_var = x[:, 1, :] # the other feature values as variance\n\n # get the latent vector through reparameterization\n z = self.reparameterize(mu, log_var)\n \n # decoding\n x = self.dec1(z)\n x = F.relu(x)\n x = self.dec2(x)\n recon = torch.sigmoid(x)\n\n # regressor\n x = self.fc1(recon)\n x = F.relu(x)\n x = self.fc2(x)\n\n return x, recon, mu, log_var\n\n\n# model definition\nclass PacingOptimizer(nn.Module):\n # https://visualstudiomagazine.com/Articles/2021/02/11/pytorch-define.aspx?Page=2\n def __init__(self):\n super(PacingOptimizer, self).__init__()\n self.hid1 = torch.nn.Linear(5, 32)\n self.drop1 = torch.nn.Dropout(0.25)\n self.hid2 = torch.nn.Linear(32, 64)\n self.drop2 = torch.nn.Dropout(0.50)\n self.hid3 = torch.nn.Linear(64, 32)\n self.oupt = torch.nn.Linear(32, 1)\n\n torch.nn.init.xavier_uniform_(self.hid1.weight)\n torch.nn.init.zeros_(self.hid1.bias)\n torch.nn.init.xavier_uniform_(self.hid2.weight)\n torch.nn.init.zeros_(self.hid2.bias)\n torch.nn.init.xavier_uniform_(self.hid3.weight)\n torch.nn.init.zeros_(self.hid3.bias)\n torch.nn.init.xavier_uniform_(self.oupt.weight)\n torch.nn.init.zeros_(self.oupt.bias)\n\n def forward(self, x):\n z = self.drop1(torch.relu(self.hid1(x)))\n z = self.drop2(torch.relu(self.hid2(z)))\n z = torch.relu(self.hid3(z))\n z = self.oupt(z) # no activation\n return z\n\n# -----------------------------------------------------------\nmodel = VAERegressor()\n# model = PacingOptimizer()\n\n# Hyperparameters\nEPOCH = 100\nBATCH = 64\nLEARNING_RATE = 0.005\n\nINTERVAL = 50\nSAVE = False\nBESTLOSS = 10\n\nCE = nn.CrossEntropyLoss()\nBCE = nn.BCELoss(reduction='mean')\nMSE = nn.MSELoss(reduction='mean') # 'mean', 'sum'. 'none'\n\ndef criterion(bce_loss, mu, logvar):\n \"\"\"\n This function will add the reconstruction loss (BCELoss) and the \n KL-Divergence.\n KL-Divergence = 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)\n :param bce_loss: recontruction loss\n :param mu: the mean from the latent vector\n :param logvar: log variance from the latent vector\n \"\"\"\n BCE = bce_loss \n KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())\n return BCE + KLD\n\n# optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)\noptimizer = optim.SGD(model.parameters(), lr=LEARNING_RATE, momentum=0.9)\n\nprint(\"\\nBatch Size = %3d \" % BATCH)\nprint(\"Loss = \" + str(criterion))\nprint(\"Pptimizer = Adam\")\nprint(\"Max Epochs = %3d \" % EPOCH)\nprint(\"Learning Rate = %0.3f \" % LEARNING_RATE)\n\n# Dataset w/o any tranformations\ntraindata = PacingDataset(tensors=(X_train, y_train), transform=None)\ntrainloader = torch.utils.data.DataLoader(traindata, batch_size=BATCH)\n\ntestdata = PacingDataset(tensors=(X_test, y_test), transform=None)\ntestloader = torch.utils.data.DataLoader(testdata, batch_size=BATCH)\n\nprint(\"\\nStarting training with saved checkpoints\")\n\nmodel.train()\nfor epoch in range(0, EPOCH):\n torch.manual_seed(epoch+1) # recovery reproducibility\n epoch_loss = 0 # for one full epoch\n\n for (batch_idx, batch) in enumerate(trainloader):\n (xs, ys) = batch # (predictors, targets)\n xs, ys = xs.float(), ys.float()\n optimizer.zero_grad() # prepare gradients\n\n # output = model(xs) # predicted pacing rate\n # loss = criterion(ys, output) # avg per item in batch\n output, recon, mu, log_var = model(xs)\n mse_loss = MSE(ys, output)\n bce_loss = BCE(recon, xs)\n loss = criterion(bce_loss, mu, log_var) + mse_loss\n\n epoch_loss += loss.item() # accumulate averages\n loss.backward() # compute gradients\n optimizer.step() # update weights\n\n if epoch % INTERVAL == 0:\n print(\"Epoch = %4d Loss = %0.4f\" % (epoch, epoch_loss))\n\n # save checkpoint\n dt = time.strftime(\"%Y_%m_%d-%H_%M_%S\")\n fn = str(dt) + str(\"-\") + str(epoch) + \"_ckpt.pt\"\n\n info_dict = {\n 'epoch' : epoch,\n 'model_state' : model.state_dict(),\n 'optimizer_state' : optimizer.state_dict()\n }\n if SAVE:\n torch.save(info_dict, fn)\n\nprint(\"\\nDone\")\n\n# evaluate model accuracy\nmodel.eval()\n\ngap = 0.50\nacc_train = accuracy(model, traindata, gap)\nprint(f\"Accuracy (within {gap:.2f}) on train data = {acc_train:.2f}%\")\n\n\n# make prediction on a random sample from test data\npivot = random.randint(0, len(testdata))\nprint(\"Pivot: \", pivot)\nx, y = testdata[pivot]\ntput, lat, loss, streams, cong = x.detach().numpy()\n# tput, lat, loss, streams, cong = 0.149677, 0.577766, 1.00000, 0.0, 1.0\nprint(f\"\\nPredicting pacing rate for:\\n\\\n (norm. values)\\n\\\n throughput = {tput}\\n\\\n latency = {lat}\\n\\\n loss = {loss}\\n\\\n congestion = {cong}\\n\\\n streams = {streams}\\n\\\n pacing = {y}\")\n\n# converting the sample to tensor array\nukn = np.array([[tput, lat, loss, streams, cong]], dtype=np.float32)\nsample = torch.tensor(ukn, dtype=torch.float32).to(device)\n\n# testing the sample\nwith torch.no_grad():\n pred, _, _, _ = model(sample)\npred = pred.item()\nprint(f\"\\nPredicted Pacing rate: {pred:.4f}\\nGround-truth Pacing rate: {y:.4f}\\n\")\n"
] | [
[
"torch.utils.data.DataLoader",
"torch.nn.init.xavier_uniform_",
"torch.no_grad",
"numpy.random.seed",
"torch.cuda.is_available",
"torch.nn.init.zeros_",
"torch.nn.Dropout",
"torch.save",
"torch.sigmoid",
"pandas.read_csv",
"sklearn.preprocessing.MinMaxScaler",
"torch.manual_seed",
"torch.tensor",
"sklearn.model_selection.train_test_split",
"torch.nn.Linear",
"torch.nn.MSELoss",
"torch.randn_like",
"pandas.DataFrame",
"torch.nn.CrossEntropyLoss",
"torch.exp",
"torch.nn.functional.relu",
"numpy.array",
"torch.nn.BCELoss"
]
] |
HubukiNinten/imgaug | [
"2570c5651ed1c90addbaffc0f8be226646c55334"
] | [
"imgaug/augmentables/batches.py"
] | [
"from __future__ import print_function, division, absolute_import\n\nimport copy\nimport collections\n\nimport numpy as np\n\nfrom .. import imgaug as ia\nfrom . import normalization as nlib\nfrom . import utils as utils\n\nDEFAULT = \"DEFAULT\"\n\n_AUGMENTABLE_NAMES = [\n \"images\", \"heatmaps\", \"segmentation_maps\", \"keypoints\",\n \"bounding_boxes\", \"polygons\", \"line_strings\"]\n\n_AugmentableColumn = collections.namedtuple(\n \"_AugmentableColumn\",\n [\"name\", \"value\", \"attr_name\"])\n\n\ndef _get_column_names(batch, postfix):\n return [column.name\n for column\n in _get_columns(batch, postfix)]\n\n\ndef _get_columns(batch, postfix):\n result = []\n for name in _AUGMENTABLE_NAMES:\n attr_name = name + postfix\n value = getattr(batch, name + postfix)\n # Every data item is either an array or a list. If there are no\n # items in the array/list, there are also no shapes to change\n # as shape-changes are imagewise. Hence, we can afford to check\n # len() here.\n if value is not None and len(value) > 0:\n result.append(_AugmentableColumn(name, value, attr_name))\n return result\n\n\n# TODO also support (H,W,C) for heatmaps of len(images) == 1\n# TODO also support (H,W) for segmaps of len(images) == 1\nclass UnnormalizedBatch(object):\n \"\"\"\n Class for batches of unnormalized data before and after augmentation.\n\n Parameters\n ----------\n images : None or (N,H,W,C) ndarray or (N,H,W) ndarray or iterable of (H,W,C) ndarray or iterable of (H,W) ndarray\n The images to augment.\n\n heatmaps : None or (N,H,W,C) ndarray or imgaug.augmentables.heatmaps.HeatmapsOnImage or iterable of (H,W,C) ndarray or iterable of imgaug.augmentables.heatmaps.HeatmapsOnImage\n The heatmaps to augment.\n If anything else than ``HeatmapsOnImage``, then the number of heatmaps\n must match the number of images provided via parameter `images`.\n The number is contained either in ``N`` or the first iterable's size.\n\n segmentation_maps : None or (N,H,W) ndarray or imgaug.augmentables.segmaps.SegmentationMapsOnImage or iterable of (H,W) ndarray or iterable of imgaug.augmentables.segmaps.SegmentationMapsOnImage\n The segmentation maps to augment.\n If anything else than ``SegmentationMapsOnImage``, then the number of\n segmaps must match the number of images provided via parameter\n `images`. The number is contained either in ``N`` or the first\n iterable's size.\n\n keypoints : None or list of (N,K,2) ndarray or tuple of number or imgaug.augmentables.kps.Keypoint or iterable of (K,2) ndarray or iterable of tuple of number or iterable of imgaug.augmentables.kps.Keypoint or iterable of imgaug.augmentables.kps.KeypointOnImage or iterable of iterable of tuple of number or iterable of iterable of imgaug.augmentables.kps.Keypoint\n The keypoints to augment.\n If a tuple (or iterable(s) of tuple), then iterpreted as (x,y)\n coordinates and must hence contain two numbers.\n A single tuple represents a single coordinate on one image, an\n iterable of tuples the coordinates on one image and an iterable of\n iterable of tuples the coordinates on several images. Analogous if\n ``Keypoint`` objects are used instead of tuples.\n If an ndarray, then ``N`` denotes the number of images and ``K`` the\n number of keypoints on each image.\n If anything else than ``KeypointsOnImage`` is provided, then the\n number of keypoint groups must match the number of images provided\n via parameter `images`. The number is contained e.g. in ``N`` or\n in case of \"iterable of iterable of tuples\" in the first iterable's\n size.\n\n bounding_boxes : None or (N,B,4) ndarray or tuple of number or imgaug.augmentables.bbs.BoundingBox or imgaug.augmentables.bbs.BoundingBoxesOnImage or iterable of (B,4) ndarray or iterable of tuple of number or iterable of imgaug.augmentables.bbs.BoundingBox or iterable of imgaug.augmentables.bbs.BoundingBoxesOnImage or iterable of iterable of tuple of number or iterable of iterable imgaug.augmentables.bbs.BoundingBox\n The bounding boxes to augment.\n This is analogous to the `keypoints` parameter. However, each\n tuple -- and also the last index in case of arrays -- has size 4,\n denoting the bounding box coordinates ``x1``, ``y1``, ``x2`` and ``y2``.\n\n polygons : None or (N,#polys,#points,2) ndarray or imgaug.augmentables.polys.Polygon or imgaug.augmentables.polys.PolygonsOnImage or iterable of (#polys,#points,2) ndarray or iterable of tuple of number or iterable of imgaug.augmentables.kps.Keypoint or iterable of imgaug.augmentables.polys.Polygon or iterable of imgaug.augmentables.polys.PolygonsOnImage or iterable of iterable of (#points,2) ndarray or iterable of iterable of tuple of number or iterable of iterable of imgaug.augmentables.kps.Keypoint or iterable of iterable of imgaug.augmentables.polys.Polygon or iterable of iterable of iterable of tuple of number or iterable of iterable of iterable of tuple of imgaug.augmentables.kps.Keypoint\n The polygons to augment.\n This is similar to the `keypoints` parameter. However, each polygon\n may be made up of several ``(x,y)`` coordinates (three or more are\n required for valid polygons).\n The following datatypes will be interpreted as a single polygon on a\n single image:\n\n * ``imgaug.augmentables.polys.Polygon``\n * ``iterable of tuple of number``\n * ``iterable of imgaug.augmentables.kps.Keypoint``\n\n The following datatypes will be interpreted as multiple polygons on a\n single image:\n\n * ``imgaug.augmentables.polys.PolygonsOnImage``\n * ``iterable of imgaug.augmentables.polys.Polygon``\n * ``iterable of iterable of tuple of number``\n * ``iterable of iterable of imgaug.augmentables.kps.Keypoint``\n * ``iterable of iterable of imgaug.augmentables.polys.Polygon``\n\n The following datatypes will be interpreted as multiple polygons on\n multiple images:\n\n * ``(N,#polys,#points,2) ndarray``\n * ``iterable of (#polys,#points,2) ndarray``\n * ``iterable of iterable of (#points,2) ndarray``\n * ``iterable of iterable of iterable of tuple of number``\n * ``iterable of iterable of iterable of tuple of imgaug.augmentables.kps.Keypoint``\n\n line_strings : None or (N,#lines,#points,2) ndarray or imgaug.augmentables.lines.LineString or imgaug.augmentables.lines.LineStringOnImage or iterable of (#lines,#points,2) ndarray or iterable of tuple of number or iterable of imgaug.augmentables.kps.Keypoint or iterable of imgaug.augmentables.lines.LineString or iterable of imgaug.augmentables.lines.LineStringOnImage or iterable of iterable of (#points,2) ndarray or iterable of iterable of tuple of number or iterable of iterable of imgaug.augmentables.kps.Keypoint or iterable of iterable of imgaug.augmentables.polys.LineString or iterable of iterable of iterable of tuple of number or iterable of iterable of iterable of tuple of imgaug.augmentables.kps.Keypoint\n The line strings to augment.\n See `polygons` for more details as polygons follow a similar\n structure to line strings.\n\n data\n Additional data that is saved in the batch and may be read out\n after augmentation. This could e.g. contain filepaths to each image\n in `images`. As this object is usually used for background\n augmentation with multiple processes, the augmented Batch objects might\n not be returned in the original order, making this information useful.\n\n \"\"\"\n\n def __init__(self, images=None, heatmaps=None, segmentation_maps=None,\n keypoints=None, bounding_boxes=None, polygons=None,\n line_strings=None, data=None):\n \"\"\"Construct a new :class:`UnnormalizedBatch` instance.\"\"\"\n self.images_unaug = images\n self.images_aug = None\n self.heatmaps_unaug = heatmaps\n self.heatmaps_aug = None\n self.segmentation_maps_unaug = segmentation_maps\n self.segmentation_maps_aug = None\n self.keypoints_unaug = keypoints\n self.keypoints_aug = None\n self.bounding_boxes_unaug = bounding_boxes\n self.bounding_boxes_aug = None\n self.polygons_unaug = polygons\n self.polygons_aug = None\n self.line_strings_unaug = line_strings\n self.line_strings_aug = None\n self.data = data\n\n def get_column_names(self):\n \"\"\"Get the names of types of augmentables that contain data.\n\n This method is intended for situations where one wants to know which\n data is contained in the batch that has to be augmented, visualized\n or something similar.\n\n Returns\n -------\n list of str\n Names of types of augmentables. E.g. ``[\"images\", \"polygons\"]``.\n\n \"\"\"\n return _get_column_names(self, \"_unaug\")\n\n def to_normalized_batch(self):\n \"\"\"Convert this unnormalized batch to an instance of Batch.\n\n As this method is intended to be called before augmentation, it\n assumes that none of the ``*_aug`` attributes is yet set.\n It will produce an AssertionError otherwise.\n\n The newly created Batch's ``*_unaug`` attributes will match the ones\n in this batch, just in normalized form.\n\n Returns\n -------\n imgaug.augmentables.batches.Batch\n The batch, with ``*_unaug`` attributes being normalized.\n\n \"\"\"\n contains_no_augmented_data_yet = all([\n attr is None\n for attr_name, attr\n in self.__dict__.items()\n if attr_name.endswith(\"_aug\")])\n assert contains_no_augmented_data_yet, (\n \"Expected UnnormalizedBatch to not contain any augmented data \"\n \"before normalization, but at least one '*_aug' attribute was \"\n \"already set.\")\n\n images_unaug = nlib.normalize_images(self.images_unaug)\n shapes = None\n if images_unaug is not None:\n shapes = [image.shape for image in images_unaug]\n\n return Batch(\n images=images_unaug,\n heatmaps=nlib.normalize_heatmaps(\n self.heatmaps_unaug, shapes),\n segmentation_maps=nlib.normalize_segmentation_maps(\n self.segmentation_maps_unaug, shapes),\n keypoints=nlib.normalize_keypoints(\n self.keypoints_unaug, shapes),\n bounding_boxes=nlib.normalize_bounding_boxes(\n self.bounding_boxes_unaug, shapes),\n polygons=nlib.normalize_polygons(\n self.polygons_unaug, shapes),\n line_strings=nlib.normalize_line_strings(\n self.line_strings_unaug, shapes),\n data=self.data\n )\n\n def fill_from_augmented_normalized_batch(self, batch_aug_norm):\n \"\"\"\n Fill this batch with (normalized) augmentation results.\n\n This method receives a (normalized) Batch instance, takes all\n ``*_aug`` attributes out if it and assigns them to this\n batch *in unnormalized form*. Hence, the datatypes of all ``*_aug``\n attributes will match the datatypes of the ``*_unaug`` attributes.\n\n Parameters\n ----------\n batch_aug_norm: imgaug.augmentables.batches.Batch\n Batch after normalization and augmentation.\n\n Returns\n -------\n imgaug.augmentables.batches.UnnormalizedBatch\n New UnnormalizedBatch instance. All ``*_unaug`` attributes are\n taken from the old UnnormalizedBatch (without deepcopying them)\n and all ``*_aug`` attributes are taken from `batch_normalized`\n converted to unnormalized form.\n\n \"\"\"\n # we take here the .data from the normalized batch instead of from\n # self for the rare case where one has decided to somehow change it\n # during augmentation\n batch = UnnormalizedBatch(\n images=self.images_unaug,\n heatmaps=self.heatmaps_unaug,\n segmentation_maps=self.segmentation_maps_unaug,\n keypoints=self.keypoints_unaug,\n bounding_boxes=self.bounding_boxes_unaug,\n polygons=self.polygons_unaug,\n line_strings=self.line_strings_unaug,\n data=batch_aug_norm.data\n )\n\n batch.images_aug = nlib.invert_normalize_images(\n batch_aug_norm.images_aug, self.images_unaug)\n batch.heatmaps_aug = nlib.invert_normalize_heatmaps(\n batch_aug_norm.heatmaps_aug, self.heatmaps_unaug)\n batch.segmentation_maps_aug = nlib.invert_normalize_segmentation_maps(\n batch_aug_norm.segmentation_maps_aug, self.segmentation_maps_unaug)\n batch.keypoints_aug = nlib.invert_normalize_keypoints(\n batch_aug_norm.keypoints_aug, self.keypoints_unaug)\n batch.bounding_boxes_aug = nlib.invert_normalize_bounding_boxes(\n batch_aug_norm.bounding_boxes_aug, self.bounding_boxes_unaug)\n batch.polygons_aug = nlib.invert_normalize_polygons(\n batch_aug_norm.polygons_aug, self.polygons_unaug)\n batch.line_strings_aug = nlib.invert_normalize_line_strings(\n batch_aug_norm.line_strings_aug, self.line_strings_unaug)\n\n return batch\n\n\nclass Batch(object):\n \"\"\"\n Class encapsulating a batch before and after augmentation.\n\n Parameters\n ----------\n images : None or (N,H,W,C) ndarray or list of (H,W,C) ndarray\n The images to augment.\n\n heatmaps : None or list of imgaug.augmentables.heatmaps.HeatmapsOnImage\n The heatmaps to augment.\n\n segmentation_maps : None or list of imgaug.augmentables.segmaps.SegmentationMapsOnImage\n The segmentation maps to augment.\n\n keypoints : None or list of imgaug.augmentables.kps.KeypointOnImage\n The keypoints to augment.\n\n bounding_boxes : None or list of imgaug.augmentables.bbs.BoundingBoxesOnImage\n The bounding boxes to augment.\n\n polygons : None or list of imgaug.augmentables.polys.PolygonsOnImage\n The polygons to augment.\n\n line_strings : None or list of imgaug.augmentables.lines.LineStringsOnImage\n The line strings to augment.\n\n data\n Additional data that is saved in the batch and may be read out\n after augmentation. This could e.g. contain filepaths to each image\n in `images`. As this object is usually used for background\n augmentation with multiple processes, the augmented Batch objects might\n not be returned in the original order, making this information useful.\n\n \"\"\"\n\n def __init__(self, images=None, heatmaps=None, segmentation_maps=None,\n keypoints=None, bounding_boxes=None, polygons=None,\n line_strings=None, data=None):\n \"\"\"Construct a new :class:`Batch` instance.\"\"\"\n self.images_unaug = images\n self.images_aug = None\n self.heatmaps_unaug = heatmaps\n self.heatmaps_aug = None\n self.segmentation_maps_unaug = segmentation_maps\n self.segmentation_maps_aug = None\n self.keypoints_unaug = keypoints\n self.keypoints_aug = None\n self.bounding_boxes_unaug = bounding_boxes\n self.bounding_boxes_aug = None\n self.polygons_unaug = polygons\n self.polygons_aug = None\n self.line_strings_unaug = line_strings\n self.line_strings_aug = None\n self.data = data\n\n @property\n @ia.deprecated(\"Batch.images_unaug\")\n def images(self):\n return self.images_unaug\n\n @property\n @ia.deprecated(\"Batch.heatmaps_unaug\")\n def heatmaps(self):\n return self.heatmaps_unaug\n\n @property\n @ia.deprecated(\"Batch.segmentation_maps_unaug\")\n def segmentation_maps(self):\n return self.segmentation_maps_unaug\n\n @property\n @ia.deprecated(\"Batch.keypoints_unaug\")\n def keypoints(self):\n return self.keypoints_unaug\n\n @property\n @ia.deprecated(\"Batch.bounding_boxes_unaug\")\n def bounding_boxes(self):\n return self.bounding_boxes_unaug\n\n def get_column_names(self):\n \"\"\"Get the names of types of augmentables that contain data.\n\n This method is intended for situations where one wants to know which\n data is contained in the batch that has to be augmented, visualized\n or something similar.\n\n Returns\n -------\n list of str\n Names of types of augmentables. E.g. ``[\"images\", \"polygons\"]``.\n\n \"\"\"\n return _get_column_names(self, \"_unaug\")\n\n def to_normalized_batch(self):\n \"\"\"Return this batch.\n\n This method does nothing and only exists to simplify interfaces\n that accept both :class:`UnnormalizedBatch` and :class:`Batch`.\n\n Returns\n -------\n imgaug.augmentables.batches.Batch\n This batch (not copied).\n\n \"\"\"\n return self\n\n def to_batch_in_augmentation(self):\n \"\"\"Convert this batch to a :class:`BatchInAugmentation` instance.\n\n Returns\n -------\n imgaug.augmentables.batches.BatchInAugmentation\n The converted batch.\n\n \"\"\"\n def _copy(var):\n # TODO first check here if _aug is set and if it is then use that?\n if var is not None:\n return utils.copy_augmentables(var)\n return var\n\n return BatchInAugmentation(\n images=_copy(self.images_unaug),\n heatmaps=_copy(self.heatmaps_unaug),\n segmentation_maps=_copy(self.segmentation_maps_unaug),\n keypoints=_copy(self.keypoints_unaug),\n bounding_boxes=_copy(self.bounding_boxes_unaug),\n polygons=_copy(self.polygons_unaug),\n line_strings=_copy(self.line_strings_unaug)\n )\n\n def fill_from_batch_in_augmentation_(self, batch_in_augmentation):\n \"\"\"Set the columns in this batch to the column values of another batch.\n\n This method works in-place.\n\n Parameters\n ----------\n batch_in_augmentation : BatchInAugmentation\n Batch of which to use the column values.\n The values are *not* copied. Only their references are used.\n\n Returns\n -------\n Batch\n The updated batch. (Modified in-place.)\n\n \"\"\"\n self.images_aug = batch_in_augmentation.images\n self.heatmaps_aug = batch_in_augmentation.heatmaps\n self.segmentation_maps_aug = batch_in_augmentation.segmentation_maps\n self.keypoints_aug = batch_in_augmentation.keypoints\n self.bounding_boxes_aug = batch_in_augmentation.bounding_boxes\n self.polygons_aug = batch_in_augmentation.polygons\n self.line_strings_aug = batch_in_augmentation.line_strings\n return self\n\n def deepcopy(self,\n images_unaug=DEFAULT,\n images_aug=DEFAULT,\n heatmaps_unaug=DEFAULT,\n heatmaps_aug=DEFAULT,\n segmentation_maps_unaug=DEFAULT,\n segmentation_maps_aug=DEFAULT,\n keypoints_unaug=DEFAULT,\n keypoints_aug=DEFAULT,\n bounding_boxes_unaug=DEFAULT,\n bounding_boxes_aug=DEFAULT,\n polygons_unaug=DEFAULT,\n polygons_aug=DEFAULT,\n line_strings_unaug=DEFAULT,\n line_strings_aug=DEFAULT):\n \"\"\"Copy this batch and all of its column values.\n\n Parameters\n ----------\n images_unaug : imgaug.augmentables.batches.DEFAULT or None or (N,H,W,C) ndarray or list of (H,W,C) ndarray\n Copies the current attribute value without changes if set to\n ``imgaug.augmentables.batches.DEFAULT``.\n Otherwise same as in :func:`Batch.__init__`.\n\n images_aug : imgaug.augmentables.batches.DEFAULT or None or (N,H,W,C) ndarray or list of (H,W,C) ndarray\n Copies the current attribute value without changes if set to\n ``imgaug.augmentables.batches.DEFAULT``.\n Otherwise same as in :func:`Batch.__init__`.\n\n heatmaps_unaug : imgaug.augmentables.batches.DEFAULT or None or list of imgaug.augmentables.heatmaps.HeatmapsOnImage\n Copies the current attribute value without changes if set to\n ``imgaug.augmentables.batches.DEFAULT``.\n Otherwise same as in :func:`Batch.__init__`.\n\n heatmaps_aug : imgaug.augmentables.batches.DEFAULT or None or list of imgaug.augmentables.heatmaps.HeatmapsOnImage\n Copies the current attribute value without changes if set to\n ``imgaug.augmentables.batches.DEFAULT``.\n Otherwise same as in :func:`Batch.__init__`.\n\n segmentation_maps_unaug : imgaug.augmentables.batches.DEFAULT or None or list of imgaug.augmentables.segmaps.SegmentationMapsOnImage\n Copies the current attribute value without changes if set to\n ``imgaug.augmentables.batches.DEFAULT``.\n Otherwise same as in :func:`Batch.__init__`.\n\n segmentation_maps_aug : imgaug.augmentables.batches.DEFAULT or None or list of imgaug.augmentables.segmaps.SegmentationMapsOnImage\n Copies the current attribute value without changes if set to\n ``imgaug.augmentables.batches.DEFAULT``.\n Otherwise same as in :func:`Batch.__init__`.\n\n keypoints_unaug : imgaug.augmentables.batches.DEFAULT or None or list of imgaug.augmentables.kps.KeypointOnImage\n Copies the current attribute value without changes if set to\n ``imgaug.augmentables.batches.DEFAULT``.\n Otherwise same as in :func:`Batch.__init__`.\n\n keypoints_aug : imgaug.augmentables.batches.DEFAULT or None or list of imgaug.augmentables.kps.KeypointOnImage\n Copies the current attribute value without changes if set to\n ``imgaug.augmentables.batches.DEFAULT``.\n Otherwise same as in :func:`Batch.__init__`.\n\n bounding_boxes_unaug : imgaug.augmentables.batches.DEFAULT or None or list of imgaug.augmentables.bbs.BoundingBoxesOnImage\n Copies the current attribute value without changes if set to\n ``imgaug.augmentables.batches.DEFAULT``.\n Otherwise same as in :func:`Batch.__init__`.\n\n bounding_boxes_aug : imgaug.augmentables.batches.DEFAULT or None or list of imgaug.augmentables.bbs.BoundingBoxesOnImage\n Copies the current attribute value without changes if set to\n ``imgaug.augmentables.batches.DEFAULT``.\n Otherwise same as in :func:`Batch.__init__`.\n\n polygons_unaug : imgaug.augmentables.batches.DEFAULT or None or list of imgaug.augmentables.polys.PolygonsOnImage\n Copies the current attribute value without changes if set to\n ``imgaug.augmentables.batches.DEFAULT``.\n Otherwise same as in :func:`Batch.__init__`.\n\n polygons_aug : imgaug.augmentables.batches.DEFAULT or None or list of imgaug.augmentables.polys.PolygonsOnImage\n Copies the current attribute value without changes if set to\n ``imgaug.augmentables.batches.DEFAULT``.\n Otherwise same as in :func:`Batch.__init__`.\n\n line_strings_unaug : imgaug.augmentables.batches.DEFAULT or None or list of imgaug.augmentables.lines.LineStringsOnImage\n Copies the current attribute value without changes if set to\n ``imgaug.augmentables.batches.DEFAULT``.\n Otherwise same as in :func:`Batch.__init__`.\n\n line_strings_aug : imgaug.augmentables.batches.DEFAULT or None or list of imgaug.augmentables.lines.LineStringsOnImage\n Copies the current attribute value without changes if set to\n ``imgaug.augmentables.batches.DEFAULT``.\n Otherwise same as in :func:`Batch.__init__`.\n\n Returns\n -------\n Batch\n Deep copy of the batch, optionally with new attributes.\n\n \"\"\"\n def _copy_optional(self_attr, arg):\n return utils.deepcopy_fast(arg if arg is not DEFAULT else self_attr)\n\n batch = Batch(\n images=_copy_optional(self.images_unaug, images_unaug),\n heatmaps=_copy_optional(self.heatmaps_unaug, heatmaps_unaug),\n segmentation_maps=_copy_optional(self.segmentation_maps_unaug,\n segmentation_maps_unaug),\n keypoints=_copy_optional(self.keypoints_unaug, keypoints_unaug),\n bounding_boxes=_copy_optional(self.bounding_boxes_unaug,\n bounding_boxes_unaug),\n polygons=_copy_optional(self.polygons_unaug, polygons_unaug),\n line_strings=_copy_optional(self.line_strings_unaug,\n line_strings_unaug),\n data=utils.deepcopy_fast(self.data)\n )\n batch.images_aug = _copy_optional(self.images_aug, images_aug)\n batch.heatmaps_aug = _copy_optional(self.heatmaps_aug, heatmaps_aug)\n batch.segmentation_maps_aug = _copy_optional(self.segmentation_maps_aug,\n segmentation_maps_aug)\n batch.keypoints_aug = _copy_optional(self.keypoints_aug, keypoints_aug)\n batch.bounding_boxes_aug = _copy_optional(self.bounding_boxes_aug,\n bounding_boxes_aug)\n batch.polygons_aug = _copy_optional(self.polygons_aug, polygons_aug)\n batch.line_strings_aug = _copy_optional(self.line_strings_aug,\n line_strings_aug)\n\n return batch\n\n\nclass _BatchInAugmentationPropagationContext(object):\n def __init__(self, batch, augmenter, hooks, parents):\n self.batch = batch\n self.augmenter = augmenter\n self.hooks = hooks\n self.parents = parents\n self.noned_info = None\n\n def __enter__(self):\n if self.hooks is not None:\n self.noned_info = self.batch.apply_propagation_hooks_(\n self.augmenter, self.hooks, self.parents)\n return self.batch\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n if self.noned_info is not None:\n self.batch = \\\n self.batch.invert_apply_propagation_hooks_(self.noned_info)\n\n\nclass BatchInAugmentation(object):\n \"\"\"\n Class encapsulating a batch during the augmentation process.\n\n Data within the batch is already verified and normalized, similar to\n :class:`Batch`. Data within the batch may be changed in-place. No initial\n copy is needed.\n\n Parameters\n ----------\n images : None or (N,H,W,C) ndarray or list of (H,W,C) ndarray\n The images to augment.\n\n heatmaps : None or list of imgaug.augmentables.heatmaps.HeatmapsOnImage\n The heatmaps to augment.\n\n segmentation_maps : None or list of imgaug.augmentables.segmaps.SegmentationMapsOnImage\n The segmentation maps to augment.\n\n keypoints : None or list of imgaug.augmentables.kps.KeypointOnImage\n The keypoints to augment.\n\n bounding_boxes : None or list of imgaug.augmentables.bbs.BoundingBoxesOnImage\n The bounding boxes to augment.\n\n polygons : None or list of imgaug.augmentables.polys.PolygonsOnImage\n The polygons to augment.\n\n line_strings : None or list of imgaug.augmentables.lines.LineStringsOnImage\n The line strings to augment.\n\n \"\"\"\n\n def __init__(self, images=None, heatmaps=None, segmentation_maps=None,\n keypoints=None, bounding_boxes=None, polygons=None,\n line_strings=None, data=None):\n \"\"\"Create a new :class:`BatchInAugmentation` instance.\"\"\"\n self.images = images\n self.heatmaps = heatmaps\n self.segmentation_maps = segmentation_maps\n self.keypoints = keypoints\n self.bounding_boxes = bounding_boxes\n self.polygons = polygons\n self.line_strings = line_strings\n self.data = data\n\n @property\n def empty(self):\n \"\"\"Estimate whether this batch is empty, i.e. contains no data.\n\n Returns\n -------\n bool\n ``True`` if the batch contains no data to augment.\n ``False`` otherwise.\n\n \"\"\"\n return self.nb_rows == 0\n\n @property\n def nb_rows(self):\n \"\"\"Get the number of rows (i.e. examples) in this batch.\n\n Note that this method assumes that all columns have the same number\n of rows.\n\n Returns\n -------\n int\n Number of rows or ``0`` if there is no data in the batch.\n\n \"\"\"\n for augm_name in _AUGMENTABLE_NAMES:\n value = getattr(self, augm_name)\n if value is not None:\n return len(value)\n return 0\n\n @property\n def columns(self):\n \"\"\"Get the columns of data to augment.\n\n Each column represents one datatype and its corresponding data,\n e.g. images or polygons.\n\n Returns\n -------\n list of _AugmentableColumn\n The columns to augment within this batch.\n\n \"\"\"\n return _get_columns(self, \"\")\n\n def get_column_names(self):\n \"\"\"Get the names of types of augmentables that contain data.\n\n This method is intended for situations where one wants to know which\n data is contained in the batch that has to be augmented, visualized\n or something similar.\n\n Returns\n -------\n list of str\n Names of types of augmentables. E.g. ``[\"images\", \"polygons\"]``.\n\n \"\"\"\n return _get_column_names(self, \"\")\n\n def get_rowwise_shapes(self):\n \"\"\"Get the shape of each row within this batch.\n\n Each row denotes the data of different types (e.g. image array,\n polygons) corresponding to a single example in the batch.\n\n This method assumes that all ``.shape`` attributes contain the same\n shape and that it is identical to the image's shape.\n It also assumes that there are no columns containing only ``None`` s.\n\n Returns\n -------\n list of tuple of int\n The shapes of each row.\n\n \"\"\"\n nb_rows = self.nb_rows\n columns = self.columns\n shapes = [None] * nb_rows\n found = np.zeros((nb_rows,), dtype=bool)\n for column in columns:\n if column.name == \"images\" and ia.is_np_array(column.value):\n shapes = [column.value.shape[1:]] * nb_rows\n else:\n for i, item in enumerate(column.value):\n if item is not None:\n shapes[i] = item.shape\n found[i] = True\n if np.all(found):\n return shapes\n return shapes\n\n def subselect_rows_by_indices(self, indices):\n \"\"\"Reduce this batch to a subset of rows based on their row indices.\n\n Parameters\n ----------\n indices : iterable of int\n Row indices to select.\n\n Returns\n -------\n BatchInAugmentation\n Batch containing only a subselection of rows.\n\n \"\"\"\n kwargs = {\"data\": self.data}\n for augm_name in _AUGMENTABLE_NAMES:\n rows = getattr(self, augm_name)\n if rows is not None:\n if augm_name == \"images\" and ia.is_np_array(rows):\n rows = rows[indices]\n else:\n rows = [rows[index] for index in indices]\n\n if len(rows) == 0:\n rows = None\n kwargs[augm_name] = rows\n\n return BatchInAugmentation(**kwargs)\n\n def invert_subselect_rows_by_indices_(self, indices, batch_subselected):\n \"\"\"Reverse the subselection of rows in-place.\n\n This is the inverse of\n :func:`BatchInAugmentation.subselect_rows_by_indices`.\n\n This method has to be executed on the batch *before* subselection.\n\n Parameters\n ----------\n indices : iterable of int\n Row indices that were selected. (This is the input to\n\n batch_subselected : BatchInAugmentation\n The batch after\n :func:`BatchInAugmentation.subselect_rows_by_indices` was called.\n\n Returns\n -------\n BatchInAugmentation\n The updated batch. (Modified in-place.)\n\n Examples\n --------\n >>> import numpy as np\n >>> from imgaug.augmentables.batches import BatchInAugmentation\n >>> images = np.zeros((2, 10, 20, 3), dtype=np.uint8)\n >>> batch = BatchInAugmentation(images=images)\n >>> batch_sub = batch.subselect_rows_by_indices([0])\n >>> batch_sub.images += 1\n >>> batch = batch.invert_subselect_rows_by_indices_([0], batch_sub)\n\n \"\"\"\n for augm_name in _AUGMENTABLE_NAMES:\n column = getattr(self, augm_name)\n if column is not None:\n column_sub = getattr(batch_subselected, augm_name)\n if column_sub is None:\n # list of indices was empty, resulting in the columns\n # in the subselected batch being empty and replaced\n # by Nones. We can just re-use the columns before\n # subselection.\n pass\n elif augm_name == \"images\" and ia.is_np_array(column):\n # An array does not have to stay an array after\n # augmentation. The shapes and/or dtypes of rows may\n # change, turning the array into a list.\n if ia.is_np_array(column_sub):\n shapes = {column.shape[1:], column_sub.shape[1:]}\n dtypes = {column.dtype.name, column_sub.dtype.name}\n else:\n shapes = set(\n [column.shape[1:]]\n + [image.shape for image in column_sub])\n dtypes = set(\n [column.dtype.name]\n + [image.dtype.name for image in column_sub])\n\n if len(shapes) == 1 and len(dtypes) == 1:\n column[indices] = column_sub\n else:\n self.images = list(column)\n for ith_index, index in enumerate(indices):\n self.images[index] = column_sub[ith_index]\n else:\n for ith_index, index in enumerate(indices):\n column[index] = column_sub[ith_index]\n\n return self\n\n def propagation_hooks_ctx(self, augmenter, hooks, parents):\n \"\"\"Start a context in which propagation hooks are applied.\n\n Parameters\n ----------\n augmenter : imgaug.augmenters.meta.Augmenter\n Augmenter to provide to the propagation hook function.\n\n hooks : imgaug.imgaug.HooksImages or imgaug.imgaug.HooksKeypoints\n The hooks that might contain a propagation hook function.\n\n parents : list of imgaug.augmenters.meta.Augmenter\n The list of parents to provide to the propagation hook function.\n\n Returns\n -------\n _BatchInAugmentationPropagationContext\n The progagation hook context.\n\n \"\"\"\n return _BatchInAugmentationPropagationContext(\n self, augmenter=augmenter, hooks=hooks, parents=parents)\n\n def apply_propagation_hooks_(self, augmenter, hooks, parents):\n \"\"\"Set columns in this batch to ``None`` based on a propagation hook.\n\n This method works in-place.\n\n Parameters\n ----------\n augmenter : imgaug.augmenters.meta.Augmenter\n Augmenter to provide to the propagation hook function.\n\n hooks : imgaug.imgaug.HooksImages or imgaug.imgaug.HooksKeypoints\n The hooks that might contain a propagation hook function.\n\n parents : list of imgaug.augmenters.meta.Augmenter\n The list of parents to provide to the propagation hook function.\n\n Returns\n -------\n list of tuple of str\n Information about which columns were set to ``None``.\n Each tuple contains\n ``(column attribute name, column value before setting it to None)``.\n This information is required when calling\n :func:`BatchInAugmentation.invert_apply_propagation_hooks_`.\n\n \"\"\"\n if hooks is None:\n return None\n\n noned_info = []\n for column in self.columns:\n is_prop = hooks.is_propagating(\n column.value, augmenter=augmenter, parents=parents,\n default=True)\n if not is_prop:\n setattr(self, column.attr_name, None)\n noned_info.append((column.attr_name, column.value))\n return noned_info\n\n def invert_apply_propagation_hooks_(self, noned_info):\n \"\"\"Set columns from ``None`` back to their original values.\n\n This is the inverse of\n :func:`BatchInAugmentation.apply_propagation_hooks_`.\n\n This method works in-place.\n\n Parameters\n ----------\n noned_info : list of tuple of str\n Information about which columns were set to ``None`` and their\n original values. This is the output of\n :func:`BatchInAugmentation.apply_propagation_hooks_`.\n\n Returns\n -------\n BatchInAugmentation\n The updated batch. (Modified in-place.)\n\n \"\"\"\n for attr_name, value in noned_info:\n setattr(self, attr_name, value)\n return self\n\n def to_batch_in_augmentation(self):\n \"\"\"Convert this batch to a :class:`BatchInAugmentation` instance.\n\n This method simply returns the batch itself. It exists for consistency\n with the other batch classes.\n\n Returns\n -------\n imgaug.augmentables.batches.BatchInAugmentation\n The batch itself. (Not copied.)\n\n \"\"\"\n return self\n\n def fill_from_batch_in_augmentation_(self, batch_in_augmentation):\n \"\"\"Set the columns in this batch to the column values of another batch.\n\n This method works in-place.\n\n Parameters\n ----------\n batch_in_augmentation : BatchInAugmentation\n Batch of which to use the column values.\n The values are *not* copied. Only their references are used.\n\n Returns\n -------\n BatchInAugmentation\n The updated batch. (Modified in-place.)\n\n \"\"\"\n if batch_in_augmentation is self:\n return self\n\n self.images = batch_in_augmentation.images\n self.heatmaps = batch_in_augmentation.heatmaps\n self.segmentation_maps = batch_in_augmentation.segmentation_maps\n self.keypoints = batch_in_augmentation.keypoints\n self.bounding_boxes = batch_in_augmentation.bounding_boxes\n self.polygons = batch_in_augmentation.polygons\n self.line_strings = batch_in_augmentation.line_strings\n\n return self\n\n def to_batch(self, batch_before_aug):\n \"\"\"Convert this batch into a :class:`Batch` instance.\n\n Parameters\n ----------\n batch_before_aug : imgaug.augmentables.batches.Batch\n The batch before augmentation. It is required to set the input\n data of the :class:`Batch` instance, e.g. ``images_unaug``\n or ``data``.\n\n Returns\n -------\n imgaug.augmentables.batches.Batch\n Batch, with original unaugmented inputs from `batch_before_aug`\n and augmented outputs from this :class:`BatchInAugmentation`\n instance.\n\n \"\"\"\n batch = Batch(\n images=batch_before_aug.images_unaug,\n heatmaps=batch_before_aug.heatmaps_unaug,\n segmentation_maps=batch_before_aug.segmentation_maps_unaug,\n keypoints=batch_before_aug.keypoints_unaug,\n bounding_boxes=batch_before_aug.bounding_boxes_unaug,\n polygons=batch_before_aug.polygons_unaug,\n line_strings=batch_before_aug.line_strings_unaug,\n data=batch_before_aug.data\n )\n batch.images_aug = self.images\n batch.heatmaps_aug = self.heatmaps\n batch.segmentation_maps_aug = self.segmentation_maps\n batch.keypoints_aug = self.keypoints\n batch.bounding_boxes_aug = self.bounding_boxes\n batch.polygons_aug = self.polygons\n batch.line_strings_aug = self.line_strings\n return batch\n\n def deepcopy(self):\n \"\"\"Copy this batch and all of its column values.\n\n Returns\n -------\n BatchInAugmentation\n Deep copy of this batch.\n\n \"\"\"\n batch = BatchInAugmentation(data=utils.deepcopy_fast(self.data))\n\n for augm_name in _AUGMENTABLE_NAMES:\n value = getattr(self, augm_name)\n if value is not None:\n setattr(batch, augm_name, utils.copy_augmentables(value))\n\n return batch\n\n\n"
] | [
[
"numpy.all",
"numpy.zeros"
]
] |
MichaelLee-ceo/FedSAUC | [
"8c00008772213562ff6a07bf9fa92c3831713118"
] | [
"fedml_api/distributed/fedavg/MyModelTrainer.py"
] | [
"import logging\nimport colorama\n\nimport torch\nfrom torch import nn\n\ntry:\n from fedml_core.trainer.model_trainer import ModelTrainer\nexcept ImportError:\n from FedML.fedml_core.trainer.model_trainer import ModelTrainer\n\ncolorama.init()\n\nclass MyModelTrainer(ModelTrainer):\n\n def get_model_params(self):\n return self.model.cpu().state_dict(keep_vars=True)\n\n def set_model_params(self, model_parameters):\n self.model.load_state_dict(model_parameters)\n\n def get_model_gradients(self):\n grads = []\n for param in self.model.parameters():\n g = param.grad.view(-1).tolist()\n grads.append(g)\n print(\"Getting model's gradient:\", torch.Tensor(g).shape)\n\n return grads\n\n def train(self, train_data, device, args, train_label):\n model = self.model\n\n model.to(device)\n model.train()\n\n criterion = nn.CrossEntropyLoss().to(device)\n if args.client_optimizer == \"sgd\":\n optimizer = torch.optim.SGD(model.parameters(), lr=args.lr)\n else:\n # optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr, weight_decay=args.wd, amsgrad=True)\n optimizer = torch.optim.Adam(model.parameters(), amsgrad=True)\n print('using Adam without learning rate decay')\n\n # print(\"= = = = = = = = = = training data = = = = = = = = = =\")\n epoch_loss = []\n for epoch in range(args.epochs):\n batch_loss = []\n for batch_idx, (x, labels) in enumerate(train_data):\n # xx, llabels = x[0].view(1, -1), labels[0].view(-1,)\n # for i in range(1, len(labels)):\n # if labels[i] == train_label:\n # xx = torch.cat((xx, x[i].view(1, -1)), 0)\n # # print('before cat:', llabels, 'label:', labels[i].view(-1,))\n # llabels = torch.cat((llabels, labels[i].view(-1,)), 0)\n\n\n # if labels[0] != train_label:\n # xx = xx[1:]\n # llabels = llabels[1:]\n\n if epoch == 0:\n print(labels, labels.shape)\n\n x, labels = x.to(device), labels.to(device)\n\n optimizer.zero_grad()\n log_probs = model(x)\n loss = criterion(log_probs, labels)\n loss.backward()\n optimizer.step()\n batch_loss.append(loss.item())\n\n if len(batch_loss) > 0:\n epoch_loss.append(sum(batch_loss) / len(batch_loss))\n logging.info('(Trainer_ID {}. Local Training Epoch: {} \\tLoss: {:.6f}'.format(self.id,\n epoch,\n sum(epoch_loss) / len(\n epoch_loss)))\n #print('Gradient shape(weight):', self.get_model_w_gradients().shape)\n #print('Gradient shape(bias):', self.get_model_b_gradients().shape)\n\n def test(self, test_data, device, args, test_label):\n model = self.model\n\n model.eval()\n model.to(device)\n\n metrics = {\n 'test_correct': 0,\n 'test_loss': 0,\n 'test_precision': 0,\n 'test_recall': 0,\n 'test_total': 0\n }\n\n criterion = nn.CrossEntropyLoss().to(device)\n with torch.no_grad():\n for batch_idx, (x, target) in enumerate(test_data):\n # xx, ttarget = x[0].view(1, -1), target[0].view(-1,)\n # for i in range(1, len(target)):\n # if target[i] == test_label:\n # xx = torch.cat((xx, x[i].view(1, -1)), 0)\n # ttarget = torch.cat((ttarget, target[i].view(-1,)), 0)\n\n # if target[0] != test_label:\n # xx = xx[1:]\n # ttarget = ttarget[1:]\n\n # if len(ttarget) == 0:\n # continue\n\n x, target = x.to(device), target.to(device)\n #print(ttarget, target, ttarget.shape, target.shape)\n\n\n pred = model(x)\n loss = criterion(pred, target)\n if args.dataset == \"stackoverflow_lr\":\n predicted = (pred > .5).int()\n correct = predicted.eq(target).sum(axis=-1).eq(target.size(1)).sum()\n true_positive = ((target * predicted) > .1).int().sum(axis=-1)\n precision = true_positive / (predicted.sum(axis=-1) + 1e-13)\n recall = true_positive / (target.sum(axis=-1) + 1e-13)\n metrics['test_precision'] += precision.sum().item()\n metrics['test_recall'] += recall.sum().item()\n else:\n # print('pred:', pred)\n _, predicted = torch.max(pred, -1)\n correct = predicted.eq(target).sum()\n # if batch_idx <= 10:\n # print('Predicted:', predicted, 'Target:', target)\n\n metrics['test_correct'] += correct.item()\n metrics['test_loss'] += loss.item() * target.size(0)\n metrics['test_total'] += target.size(0)\n\n return metrics\n\n def test_on_the_server(self, train_data_local_dict, test_data_local_dict, device, args=None) -> bool:\n return False\n"
] | [
[
"torch.no_grad",
"torch.Tensor",
"torch.nn.CrossEntropyLoss",
"torch.max"
]
] |
nobu-g/cohesion-analysis | [
"bf2e22c1aff51f96fd2aaef6359839646548c3be"
] | [
"src/scorer.py"
] | [
"import argparse\nimport io\nimport logging\nimport sys\nfrom collections import OrderedDict\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import List, Dict, Set, Union, Optional, TextIO\n\nimport pandas as pd\nfrom jinja2 import Template, Environment, FileSystemLoader\nfrom kyoto_reader import KyotoReader, Document, Argument, SpecialArgument, BaseArgument, Predicate, Mention, BasePhrase\nfrom pyknp import BList\n\nfrom utils.constants import CASE2YOMI\nfrom utils.util import is_pas_target, is_bridging_target, is_coreference_target\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.WARNING)\n\n\nclass Scorer:\n \"\"\"A class to evaluate system output.\n\n To evaluate system output with this class, you have to prepare gold data and system prediction data as instances of\n :class:`kyoto_reader.Document`\n\n Args:\n documents_pred (List[Document]): ใทในใใ ไบๆธฌๆๆธ้ๅ\n documents_gold (List[Document]): ๆญฃ่งฃๆๆธ้ๅ\n target_cases (List[str]): ่ฉไพกใฎๅฏพ่ฑกใจใใๆ ผ (kyoto_reader.ALL_CASES ใๅ็
ง)\n target_exophors (List[str]): ่ฉไพกใฎๅฏพ่ฑกใจใใๅค็็
งๅฟใฎ็
งๅฟๅ
(kyoto_reader.ALL_EXOPHORS ใๅ็
ง)\n bridging (bool): ๆฉๆธกใ็
งๅฟใฎ่ฉไพกใ่กใใใฉใใ (default: False)\n coreference (bool): ๅ
ฑๅ็
งใฎ่ฉไพกใ่กใใใฉใใ (default: False)\n pas_target (str): ่ฟฐ่ช้
ๆง้ ่งฃๆใซใใใฆ่ฟฐ่ชใจใใฆๆฑใๅฏพ่ฑก ('pred': ็จ่จ, 'noun': ไฝ่จ, 'all': ไธกๆน, '': ่ฟฐ่ชใชใ (default: pred))\n\n Attributes:\n cases (List[str]): ่ฉไพกใฎๅฏพ่ฑกใจใชใๆ ผ\n doc_ids: (List[str]): ่ฉไพกใฎๅฏพ่ฑกใจใชใๆๆธใฎๆๆธID้ๅ\n did2document_pred (Dict[str, Document]): ๆๆธIDใใใทในใใ ไบๆธฌๆๆธใๅผใใใใฎ่พๆธ\n did2document_gold (Dict[str, Document]): ๆๆธIDใใๆญฃ่งฃๆๆธใๅผใใใใฎ่พๆธ\n bridging (bool): ๆฉๆธกใ็
งๅฟใฎ่ฉไพกใ่กใใใฉใใ\n coreference (bool): ๅ
ฑๅ็
งใฎ่ฉไพกใ่กใใใฉใใ\n pas_target (str): ่ฟฐ่ช้
ๆง้ ่งฃๆใซใใใฆ่ฟฐ่ชใจใใฆๆฑใๅฏพ่ฑก\n comp_result (Dict[tuple, str]): ๆญฃ่งฃใจไบๆธฌใๆฏ่ผใใ็ตๆใๆ ผ็ดใใใใใฎ่พๆธ\n sub_scorers (List[SubScorer]): ๆๆธใใจใฎ่ฉไพกใ่กใใชใใธใงใฏใใฎใชในใ\n relax_exophors (Dict[str, str]): ใไธ็นๅฎ:ไบบ๏ผใใชใฉใใไธ็นๅฎ:ไบบใใจใใฆ่ฉไพกใใใใใฎใใใ\n \"\"\"\n DEPTYPE2ANALYSIS = OrderedDict([('overt', 'overt'),\n ('dep', 'dep'),\n ('intra', 'zero_intra'),\n ('inter', 'zero_inter'),\n ('exo', 'zero_exophora')])\n\n def __init__(self,\n documents_pred: List[Document],\n documents_gold: List[Document],\n target_cases: List[str],\n target_exophors: List[str],\n bridging: bool = False,\n coreference: bool = False,\n pas_target: str = 'pred'):\n # long document may have been ignored\n assert set(doc.doc_id for doc in documents_pred) <= set(doc.doc_id for doc in documents_gold)\n self.cases: List[str] = target_cases if pas_target != '' else []\n self.doc_ids: List[str] = [doc.doc_id for doc in documents_pred]\n self.did2document_pred: Dict[str, Document] = {doc.doc_id: doc for doc in documents_pred}\n self.did2document_gold: Dict[str, Document] = {doc.doc_id: doc for doc in documents_gold}\n self.bridging: bool = bridging\n self.coreference: bool = coreference\n self.pas_target: str = pas_target\n\n self.comp_result: Dict[tuple, str] = {}\n self.sub_scorers: List[SubScorer] = []\n self.relax_exophors: Dict[str, str] = {}\n for exophor in target_exophors:\n self.relax_exophors[exophor] = exophor\n if exophor in ('ไธ็นๅฎ:ไบบ', 'ไธ็นๅฎ:็ฉ', 'ไธ็นๅฎ:็ถๆณ'):\n for n in ('๏ผ', '๏ผ', '๏ผ', '๏ผ', '๏ผ', '๏ผ', '๏ผ', '๏ผ', '๏ผ', '๏ผ๏ผ', '๏ผ๏ผ'):\n self.relax_exophors[exophor + n] = exophor\n\n def run(self) -> 'ScoreResult':\n \"\"\"่ชญใฟ่พผใใ ๆญฃ่งฃๆๆธ้ๅใจใทในใใ ไบๆธฌๆๆธ้ๅใซๅฏพใใฆ่ฉไพกใ่กใ\n\n Returns:\n ScoreResult: ่ฉไพก็ตๆใฎในใณใข\n \"\"\"\n self.comp_result = {}\n self.sub_scorers = []\n all_result = None\n for doc_id in self.doc_ids:\n sub_scorer = SubScorer(self.did2document_pred[doc_id], self.did2document_gold[doc_id],\n cases=self.cases,\n bridging=self.bridging,\n coreference=self.coreference,\n relax_exophors=self.relax_exophors,\n pas_target=self.pas_target)\n if all_result is None:\n all_result = sub_scorer.run()\n else:\n all_result += sub_scorer.run()\n self.sub_scorers.append(sub_scorer)\n self.comp_result.update({(doc_id, *key): val for key, val in sub_scorer.comp_result.items()})\n return all_result\n\n def write_html(self, output_file: Union[str, Path]) -> None:\n \"\"\"ๆญฃ่งฃใใผใฟใจใทในใใ ไบๆธฌใฎๆฏ่ผใHTMLๅฝขๅผใงๆธใๅบใ\n\n Args:\n output_file (Union[str, Path]): ๅบๅๅ
ใใกใคใซ\n \"\"\"\n data: List[tuple] = []\n for sub_scorer in self.sub_scorers:\n gold_tree = ''\n for sid in sub_scorer.document_gold.sid2sentence.keys():\n with io.StringIO() as string:\n self._draw_tree(sid,\n sub_scorer.predicates_gold,\n sub_scorer.mentions_gold,\n sub_scorer.bridgings_gold,\n sub_scorer.document_gold,\n fh=string)\n gold_tree += string.getvalue()\n\n pred_tree = ''\n for sid in sub_scorer.document_pred.sid2sentence.keys():\n with io.StringIO() as string:\n self._draw_tree(sid,\n sub_scorer.predicates_pred,\n sub_scorer.mentions_pred,\n sub_scorer.bridgings_pred,\n sub_scorer.document_pred,\n fh=string)\n pred_tree += string.getvalue()\n data.append((sub_scorer.document_gold.sentences, gold_tree, pred_tree))\n\n env = Environment(loader=FileSystemLoader(str(Path(__file__).parent)))\n template: Template = env.get_template('template.html')\n\n with Path(output_file).open('wt') as f:\n f.write(template.render({'data': data}))\n\n def _draw_tree(self,\n sid: str,\n predicates: List[BasePhrase],\n mentions: List[BasePhrase],\n anaphors: List[BasePhrase],\n document: Document,\n fh: Optional[TextIO] = None,\n html: bool = True\n ) -> None:\n \"\"\"Write the predicate-argument structures, coreference relations, and bridging anaphora relations of the\n specified sentence in tree format.\n\n Args:\n sid (str): ๅบๅๅฏพ่ฑกใฎๆID\n predicates (List[BasePhrase]): documentใซๅซใพใใๅ
จใฆใฎ่ฟฐ่ช\n mentions (List[BasePhrase]): documentใซๅซใพใใๅ
จใฆใฎใกใณใทใงใณ\n anaphors (List[BasePhrase]): documentใซๅซใพใใๅ
จใฆใฎๆฉๆธกใ็
งๅฟ่ฉ\n document (Document): ๅบๅๅฏพ่ฑกใฎๆใๅซใพใใๆๆธ\n fh (Optional[TextIO]): ๅบๅในใใชใผใ \n html (bool): HTMLๅฝขๅผใงๅบๅใใใใฉใใ\n \"\"\"\n result2color = {anal: 'blue' for anal in Scorer.DEPTYPE2ANALYSIS.values()}\n result2color.update({'overt': 'green', 'wrong': 'red', None: 'gray'})\n result2color_coref = {'correct': 'blue', 'wrong': 'red', None: 'gray'}\n blist: BList = document.sid2sentence[sid].blist\n with io.StringIO() as string:\n blist.draw_tag_tree(fh=string, show_pos=False)\n tree_strings = string.getvalue().rstrip('\\n').split('\\n')\n assert len(tree_strings) == len(blist.tag_list())\n all_targets = [m.core for m in document.mentions.values()]\n tid2predicate: Dict[int, BasePhrase] = {predicate.tid: predicate for predicate in predicates\n if predicate.sid == sid}\n tid2mention: Dict[int, BasePhrase] = {mention.tid: mention for mention in mentions if mention.sid == sid}\n tid2bridging: Dict[int, BasePhrase] = {anaphor.tid: anaphor for anaphor in anaphors if anaphor.sid == sid}\n for tid in range(len(tree_strings)):\n tree_strings[tid] += ' '\n if tid in tid2predicate:\n predicate = tid2predicate[tid]\n arguments = document.get_arguments(predicate)\n for case in self.cases:\n args = arguments[case]\n if case == 'ใฌ':\n args += arguments['ๅคใฌ']\n targets = set()\n for arg in args:\n target = str(arg)\n if all_targets.count(str(arg)) > 1 and isinstance(arg, Argument):\n target += str(arg.dtid)\n targets.add(target)\n result = self.comp_result.get((document.doc_id, predicate.dtid, case), None)\n if html:\n tree_strings[tid] += f'<font color=\"{result2color[result]}\">{case}:{\",\".join(targets)}</font> '\n else:\n tree_strings[tid] += f'{case}:{\",\".join(targets)} '\n\n if self.bridging and tid in tid2bridging:\n anaphor = tid2bridging[tid]\n arguments = document.get_arguments(anaphor)\n args = arguments['ใ'] + arguments['ใ๏ผ']\n targets = set()\n for arg in args:\n target = str(arg)\n if all_targets.count(str(arg)) > 1 and isinstance(arg, Argument):\n target += str(arg.dtid)\n targets.add(target)\n result = self.comp_result.get((document.doc_id, anaphor.dtid, 'ใ'), None)\n if html:\n tree_strings[tid] += f'<font color=\"{result2color[result]}\">ใ:{\",\".join(targets)}</font> '\n else:\n tree_strings[tid] += f'ใ:{\",\".join(targets)} '\n\n if self.coreference and tid in tid2mention:\n targets = set()\n src_dtid = tid2mention[tid].dtid\n if src_dtid in document.mentions:\n src_mention = document.mentions[src_dtid]\n tgt_mentions_relaxed = SubScorer.filter_mentions(\n document.get_siblings(src_mention, relax=True), src_mention)\n for tgt_mention in tgt_mentions_relaxed:\n target: str = tgt_mention.core\n if all_targets.count(target) > 1:\n target += str(tgt_mention.dtid)\n targets.add(target)\n for eid in src_mention.eids:\n entity = document.entities[eid]\n if entity.exophor in self.relax_exophors:\n targets.add(entity.exophor)\n result = self.comp_result.get((document.doc_id, src_dtid, '='), None)\n if html:\n tree_strings[tid] += f'<font color=\"{result2color_coref[result]}\">๏ผ:{\",\".join(targets)}</font>'\n else:\n tree_strings[tid] += '๏ผ:' + ','.join(targets)\n\n print('\\n'.join(tree_strings), file=fh)\n\n\nclass SubScorer:\n \"\"\"Scorer for single document pair.\n\n Args:\n document_pred (Document): ใทในใใ ไบๆธฌๆๆธ\n document_gold (Document): ๆญฃ่งฃๆๆธ\n cases (List[str]): ่ฉไพกใฎๅฏพ่ฑกใจใใๆ ผ\n bridging (bool): ๆฉๆธกใ็
งๅฟใฎ่ฉไพกใ่กใใใฉใใ (default: False)\n coreference (bool): ๅ
ฑๅ็
งใฎ่ฉไพกใ่กใใใฉใใ (default: False)\n relax_exophors (Dict[str, str]): ใไธ็นๅฎ:ไบบ๏ผใใชใฉใใไธ็นๅฎ:ไบบใใจใใฆ่ฉไพกใใใใใฎใใใ\n pas_target (str): ่ฟฐ่ช้
ๆง้ ่งฃๆใซใใใฆ่ฟฐ่ชใจใใฆๆฑใๅฏพ่ฑก\n\n Attributes:\n doc_id (str): ๅฏพ่ฑกใฎๆๆธID\n document_pred (Document): ใทในใใ ไบๆธฌๆๆธ\n document_gold (Document): ๆญฃ่งฃๆๆธ\n cases (List[str]): ่ฉไพกใฎๅฏพ่ฑกใจใชใๆ ผ\n pas (bool): ่ฟฐ่ช้
ๆง้ ใฎ่ฉไพกใ่กใใใฉใใ\n bridging (bool): ๆฉๆธกใ็
งๅฟใฎ่ฉไพกใ่กใใใฉใใ\n coreference (bool): ๅ
ฑๅ็
งใฎ่ฉไพกใ่กใใใฉใใ\n comp_result (Dict[tuple, str]): ๆญฃ่งฃใจไบๆธฌใๆฏ่ผใใ็ตๆใๆ ผ็ดใใใใใฎ่พๆธ\n relax_exophors (Dict[str, str]): ใไธ็นๅฎ:ไบบ๏ผใใชใฉใใไธ็นๅฎ:ไบบใใจใใฆ่ฉไพกใใใใใฎใใใ\n predicates_pred: (List[BasePhrase]): ใทในใใ ไบๆธฌๆๆธใซๅซใพใใ่ฟฐ่ช\n bridgings_pred: (List[BasePhrase]): ใทในใใ ไบๆธฌๆๆธใซๅซใพใใๆฉๆธกใ็
งๅฟ่ฉ\n mentions_pred: (List[BasePhrase]): ใทในใใ ไบๆธฌๆๆธใซๅซใพใใใกใณใทใงใณ\n predicates_gold: (List[BasePhrase]): ๆญฃ่งฃๆๆธใซๅซใพใใ่ฟฐ่ช\n bridgings_gold: (List[BasePhrase]): ๆญฃ่งฃๆๆธใซๅซใพใใๆฉๆธกใ็
งๅฟ่ฉ\n mentions_gold: (List[BasePhrase]): ๆญฃ่งฃๆๆธใซๅซใพใใใกใณใทใงใณ\n \"\"\"\n\n def __init__(self,\n document_pred: Document,\n document_gold: Document,\n cases: List[str],\n bridging: bool,\n coreference: bool,\n relax_exophors: Dict[str, str],\n pas_target: str):\n assert document_pred.doc_id == document_gold.doc_id\n self.doc_id: str = document_gold.doc_id\n self.document_pred: Document = document_pred\n self.document_gold: Document = document_gold\n self.cases: List[str] = cases\n self.pas: bool = pas_target != ''\n self.bridging: bool = bridging\n self.coreference: bool = coreference\n self.comp_result: Dict[tuple, str] = {}\n self.relax_exophors: Dict[str, str] = relax_exophors\n\n self.predicates_pred: List[BasePhrase] = []\n self.bridgings_pred: List[BasePhrase] = []\n self.mentions_pred: List[BasePhrase] = []\n for bp in document_pred.bp_list():\n if is_pas_target(bp, verbal=(pas_target in ('pred', 'all')), nominal=(pas_target in ('noun', 'all'))):\n self.predicates_pred.append(bp)\n if self.bridging and is_bridging_target(bp):\n self.bridgings_pred.append(bp)\n if self.coreference and is_coreference_target(bp):\n self.mentions_pred.append(bp)\n self.predicates_gold: List[BasePhrase] = []\n self.bridgings_gold: List[BasePhrase] = []\n self.mentions_gold: List[BasePhrase] = []\n for bp in document_gold.bp_list():\n if is_pas_target(bp, verbal=(pas_target in ('pred', 'all')), nominal=(pas_target in ('noun', 'all'))):\n self.predicates_gold.append(bp)\n if self.bridging and is_bridging_target(bp):\n self.bridgings_gold.append(bp)\n if self.coreference and is_coreference_target(bp):\n self.mentions_gold.append(bp)\n\n def run(self) -> 'ScoreResult':\n \"\"\"Perform evaluation for the given gold document and system prediction document.\n\n Returns:\n ScoreResult: ่ฉไพก็ตๆใฎในใณใข\n \"\"\"\n self.comp_result = {}\n measures_pas = self._evaluate_pas() if self.pas else None\n measures_bridging = self._evaluate_bridging() if self.bridging else None\n measure_coref = self._evaluate_coref() if self.coreference else None\n return ScoreResult(measures_pas, measures_bridging, measure_coref)\n\n def _evaluate_pas(self) -> pd.DataFrame:\n \"\"\"calculate predicate-argument structure analysis scores\"\"\"\n # measures: Dict[str, Dict[str, Measure]] = OrderedDict(\n # (case, OrderedDict((anal, Measure()) for anal in Scorer.DEPTYPE2ANALYSIS.values()))\n # for case in self.cases)\n measures = pd.DataFrame([[Measure() for _ in Scorer.DEPTYPE2ANALYSIS.values()] for _ in self.cases],\n index=self.cases, columns=Scorer.DEPTYPE2ANALYSIS.values())\n dtid2predicate_pred: Dict[int, Predicate] = {pred.dtid: pred for pred in self.predicates_pred}\n dtid2predicate_gold: Dict[int, Predicate] = {pred.dtid: pred for pred in self.predicates_gold}\n\n for dtid in range(len(self.document_pred.bp_list())):\n if dtid in dtid2predicate_pred:\n predicate_pred = dtid2predicate_pred[dtid]\n arguments_pred = self.document_pred.get_arguments(predicate_pred, relax=False)\n else:\n arguments_pred = None\n\n if dtid in dtid2predicate_gold:\n predicate_gold = dtid2predicate_gold[dtid]\n arguments_gold = self.document_gold.get_arguments(predicate_gold, relax=False)\n arguments_gold_relaxed = self.document_gold.get_arguments(predicate_gold, relax=True)\n else:\n predicate_gold = arguments_gold = arguments_gold_relaxed = None\n\n for case in self.cases:\n args_pred: List[BaseArgument] = arguments_pred[case] if arguments_pred is not None else []\n assert len(args_pred) in (0, 1) # Our analyzer predicts one argument for one predicate\n if predicate_gold is not None:\n args_gold = self._filter_args(arguments_gold[case], predicate_gold)\n args_gold_relaxed = self._filter_args(\n arguments_gold_relaxed[case] + (arguments_gold_relaxed['ๅคใฌ'] if case == 'ใฌ' else []),\n predicate_gold)\n else:\n args_gold = args_gold_relaxed = []\n\n key = (dtid, case)\n\n # calculate precision\n if args_pred:\n arg = args_pred[0]\n if arg in args_gold_relaxed:\n # use dep_type of gold argument if possible\n arg_gold = args_gold_relaxed[args_gold_relaxed.index(arg)]\n analysis = Scorer.DEPTYPE2ANALYSIS[arg_gold.dep_type]\n self.comp_result[key] = analysis\n measures.at[case, analysis].correct += 1\n else:\n # systemๅบๅใฎdep_typeใฏgoldใฎใใฎใจ้ใใฎใงไธๆดๅใ่ตทใใใใใใใชใ\n analysis = Scorer.DEPTYPE2ANALYSIS[arg.dep_type]\n self.comp_result[key] = 'wrong' # precision ใไธใใ\n measures.at[case, analysis].denom_pred += 1\n\n # calculate recall\n # ๆญฃ่งฃใ่คๆฐใใๅ ดๅใใใฎใใกไธใคใๅฝใฆใใใฆใใใฐใใใๆญฃ่งฃใซๆก็จ\n # ใใใใๅฝใฆใใใฆใใชใใใฐใrelax ใใใฆใใชใ้
ใใไธใคใ้ธใณๆญฃ่งฃใซๆก็จ\n if args_gold or (self.comp_result.get(key, None) in Scorer.DEPTYPE2ANALYSIS.values()):\n arg_gold = None\n for arg in args_gold_relaxed:\n if arg in args_pred:\n arg_gold = arg # ไบๆธฌใใใฆใใ้
ใๅชๅ
ใใฆๆญฃ่งฃใฎ้
ใซๆก็จ\n break\n if arg_gold is not None:\n analysis = Scorer.DEPTYPE2ANALYSIS[arg_gold.dep_type]\n assert self.comp_result[key] == analysis\n else:\n analysis = Scorer.DEPTYPE2ANALYSIS[args_gold[0].dep_type]\n if args_pred:\n assert self.comp_result[key] == 'wrong'\n else:\n self.comp_result[key] = 'wrong' # recall ใไธใใ\n measures.at[case, analysis].denom_gold += 1\n return measures\n\n def _filter_args(self,\n args: List[BaseArgument],\n predicate: Predicate,\n ) -> List[BaseArgument]:\n filtered_args = []\n for arg in args:\n if isinstance(arg, SpecialArgument):\n if arg.exophor not in self.relax_exophors: # filter out non-target exophors\n continue\n arg.exophor = self.relax_exophors[arg.exophor] # ใไธ็นๅฎ:ไบบ๏ผใใชใฉใใไธ็นๅฎ:ไบบใใจใใฆๆฑใ\n else:\n assert isinstance(arg, Argument)\n # filter out self-anaphora and cataphoras\n if predicate.dtid == arg.dtid or (predicate.dtid < arg.dtid and arg.sid != predicate.sid):\n continue\n filtered_args.append(arg)\n return filtered_args\n\n def _evaluate_bridging(self) -> pd.Series:\n \"\"\"calculate bridging anaphora resolution scores\"\"\"\n measures: Dict[str, Measure] = OrderedDict((anal, Measure()) for anal in Scorer.DEPTYPE2ANALYSIS.values())\n dtid2anaphor_pred: Dict[int, Predicate] = {pred.dtid: pred for pred in self.bridgings_pred}\n dtid2anaphor_gold: Dict[int, Predicate] = {pred.dtid: pred for pred in self.bridgings_gold}\n\n for dtid in range(len(self.document_pred.bp_list())):\n if dtid in dtid2anaphor_pred:\n anaphor_pred = dtid2anaphor_pred[dtid]\n antecedents_pred: List[BaseArgument] = \\\n self._filter_args(self.document_pred.get_arguments(anaphor_pred, relax=False)['ใ'], anaphor_pred)\n else:\n antecedents_pred = []\n assert len(antecedents_pred) in (0, 1) # in bert_pas_analysis, predict one argument for one predicate\n\n if dtid in dtid2anaphor_gold:\n anaphor_gold: Predicate = dtid2anaphor_gold[dtid]\n antecedents_gold: List[BaseArgument] = \\\n self._filter_args(self.document_gold.get_arguments(anaphor_gold, relax=False)['ใ'], anaphor_gold)\n arguments: Dict[str, List[BaseArgument]] = self.document_gold.get_arguments(anaphor_gold, relax=True)\n antecedents_gold_relaxed: List[BaseArgument] = \\\n self._filter_args(arguments['ใ'] + arguments['ใ๏ผ'], anaphor_gold)\n else:\n antecedents_gold = antecedents_gold_relaxed = []\n\n key = (dtid, 'ใ')\n\n # calculate precision\n if antecedents_pred:\n antecedent_pred = antecedents_pred[0]\n if antecedent_pred in antecedents_gold_relaxed:\n # use dep_type of gold antecedent if possible\n antecedent_gold = antecedents_gold_relaxed[antecedents_gold_relaxed.index(antecedent_pred)]\n analysis = Scorer.DEPTYPE2ANALYSIS[antecedent_gold.dep_type]\n if analysis == 'overt':\n analysis = 'dep'\n self.comp_result[key] = analysis\n measures[analysis].correct += 1\n else:\n analysis = Scorer.DEPTYPE2ANALYSIS[antecedent_pred.dep_type]\n if analysis == 'overt':\n analysis = 'dep'\n self.comp_result[key] = 'wrong'\n measures[analysis].denom_pred += 1\n\n # calculate recall\n if antecedents_gold or (self.comp_result.get(key, None) in Scorer.DEPTYPE2ANALYSIS.values()):\n antecedent_gold = None\n for ant in antecedents_gold_relaxed:\n if ant in antecedents_pred:\n antecedent_gold = ant # ไบๆธฌใใใฆใใๅ
่ก่ฉใๅชๅ
ใใฆๆญฃ่งฃใฎๅ
่ก่ฉใซๆก็จ\n break\n if antecedent_gold is not None:\n analysis = Scorer.DEPTYPE2ANALYSIS[antecedent_gold.dep_type]\n if analysis == 'overt':\n analysis = 'dep'\n assert self.comp_result[key] == analysis\n else:\n analysis = Scorer.DEPTYPE2ANALYSIS[antecedents_gold[0].dep_type]\n if analysis == 'overt':\n analysis = 'dep'\n if antecedents_pred:\n assert self.comp_result[key] == 'wrong'\n else:\n self.comp_result[key] = 'wrong'\n measures[analysis].denom_gold += 1\n return pd.Series(measures)\n\n def _evaluate_coref(self) -> pd.Series:\n \"\"\"calculate coreference resolution scores\"\"\"\n measure = Measure()\n dtid2mention_pred: Dict[int, Mention] = {bp.dtid: self.document_pred.mentions[bp.dtid]\n for bp in self.mentions_pred\n if bp.dtid in self.document_pred.mentions}\n dtid2mention_gold: Dict[int, Mention] = {bp.dtid: self.document_gold.mentions[bp.dtid]\n for bp in self.mentions_gold\n if bp.dtid in self.document_gold.mentions}\n for dtid in range(len(self.document_pred.bp_list())):\n if dtid in dtid2mention_pred:\n src_mention_pred = dtid2mention_pred[dtid]\n tgt_mentions_pred = \\\n self.filter_mentions(self.document_pred.get_siblings(src_mention_pred), src_mention_pred)\n exophors_pred = {e.exophor for e in map(self.document_pred.entities.get, src_mention_pred.eids)\n if e.is_special}\n else:\n tgt_mentions_pred = exophors_pred = set()\n\n if dtid in dtid2mention_gold:\n src_mention_gold = dtid2mention_gold[dtid]\n tgt_mentions_gold = self.filter_mentions(self.document_gold.get_siblings(src_mention_gold, relax=False),\n src_mention_gold)\n tgt_mentions_gold_relaxed = self.filter_mentions(\n self.document_gold.get_siblings(src_mention_gold, relax=True), src_mention_gold)\n exophors_gold = {self.relax_exophors[e.exophor] for e\n in map(self.document_gold.entities.get, src_mention_gold.eids)\n if e.is_special and e.exophor in self.relax_exophors}\n exophors_gold_relaxed = {self.relax_exophors[e.exophor] for e\n in map(self.document_gold.entities.get, src_mention_gold.all_eids)\n if e.is_special and e.exophor in self.relax_exophors}\n else:\n tgt_mentions_gold = tgt_mentions_gold_relaxed = exophors_gold = exophors_gold_relaxed = set()\n\n key = (dtid, '=')\n\n # calculate precision\n if tgt_mentions_pred or exophors_pred:\n if (tgt_mentions_pred & tgt_mentions_gold_relaxed) or (exophors_pred & exophors_gold_relaxed):\n self.comp_result[key] = 'correct'\n measure.correct += 1\n else:\n self.comp_result[key] = 'wrong'\n measure.denom_pred += 1\n\n # calculate recall\n if tgt_mentions_gold or exophors_gold or (self.comp_result.get(key, None) == 'correct'):\n if (tgt_mentions_pred & tgt_mentions_gold_relaxed) or (exophors_pred & exophors_gold_relaxed):\n assert self.comp_result[key] == 'correct'\n else:\n self.comp_result[key] = 'wrong'\n measure.denom_gold += 1\n return pd.Series([measure], index=['all'])\n\n @staticmethod\n def filter_mentions(tgt_mentions: Set[Mention], src_mention: Mention) -> Set[Mention]:\n \"\"\"filter out cataphors\"\"\"\n return {tgt_mention for tgt_mention in tgt_mentions if tgt_mention.dtid < src_mention.dtid}\n\n\n@dataclass(frozen=True)\nclass ScoreResult:\n \"\"\"A data class for storing the numerical result of an evaluation\"\"\"\n measures_pas: Optional[pd.DataFrame]\n measures_bridging: Optional[pd.Series]\n measure_coref: Optional[pd.Series]\n\n def to_dict(self) -> Dict[str, Dict[str, 'Measure']]:\n \"\"\"convert data to dictionary\"\"\"\n df_all = pd.DataFrame(index=['all_case'])\n if self.pas:\n df_pas: pd.DataFrame = self.measures_pas.copy()\n df_pas['zero'] = df_pas['zero_intra'] + df_pas['zero_inter'] + df_pas['zero_exophora']\n df_pas['dep_zero'] = df_pas['zero'] + df_pas['dep']\n df_pas['all'] = df_pas['dep_zero'] + df_pas['overt']\n df_all = pd.concat([df_pas, df_all])\n df_all.loc['all_case'] = df_pas.sum(axis=0)\n\n if self.bridging:\n df_bar = self.measures_bridging.copy()\n df_bar['zero'] = df_bar['zero_intra'] + df_bar['zero_inter'] + df_bar['zero_exophora']\n df_bar['dep_zero'] = df_bar['zero'] + df_bar['dep']\n assert df_bar['overt'] == Measure() # No overt in BAR\n df_bar['all'] = df_bar['dep_zero']\n df_all.at['all_case', 'bridging'] = df_bar['all']\n\n if self.coreference:\n df_all.at['all_case', 'coreference'] = self.measure_coref['all']\n\n return {k1: {k2: v2 for k2, v2 in v1.items() if pd.notnull(v2)}\n for k1, v1 in df_all.to_dict(orient='index').items()}\n\n def export_txt(self,\n destination: Union[str, Path, TextIO]\n ) -> None:\n \"\"\"Export the evaluation results in a text format.\n\n Args:\n destination (Union[str, Path, TextIO]): ๆธใๅบใๅ
\n \"\"\"\n lines = []\n for key, ms in self.to_dict().items():\n lines.append(f'{key}ๆ ผ' if self.pas and key in self.measures_pas.index else key)\n for analysis, measure in ms.items():\n lines.append(f' {analysis}')\n lines.append(f' precision: {measure.precision:.4f} ({measure.correct}/{measure.denom_pred})')\n lines.append(f' recall : {measure.recall:.4f} ({measure.correct}/{measure.denom_gold})')\n lines.append(f' F : {measure.f1:.4f}')\n text = '\\n'.join(lines) + '\\n'\n\n if isinstance(destination, str) or isinstance(destination, Path):\n with Path(destination).open('wt') as writer:\n writer.write(text)\n elif isinstance(destination, io.TextIOBase):\n destination.write(text)\n\n def export_csv(self,\n destination: Union[str, Path, TextIO],\n sep: str = ','\n ) -> None:\n \"\"\"Export the evaluation results in a csv format.\n\n Args:\n destination (Union[str, Path, TextIO]): ๆธใๅบใๅ
\n sep (str): ๅบๅใๆๅญ (default: ',')\n \"\"\"\n text = ''\n result_dict = self.to_dict()\n text += 'case' + sep\n text += sep.join(result_dict['all_case'].keys()) + '\\n'\n for case, measures in result_dict.items():\n text += CASE2YOMI.get(case, case) + sep\n text += sep.join(f'{measure.f1:.6}' for measure in measures.values())\n text += '\\n'\n\n if isinstance(destination, str) or isinstance(destination, Path):\n with Path(destination).open('wt') as writer:\n writer.write(text)\n elif isinstance(destination, io.TextIOBase):\n destination.write(text)\n\n @property\n def pas(self):\n \"\"\"Whether self includes the score of predicate-argument structure analysis.\"\"\"\n return self.measures_pas is not None\n\n @property\n def bridging(self):\n \"\"\"Whether self includes the score of bridging anaphora resolution.\"\"\"\n return self.measures_bridging is not None\n\n @property\n def coreference(self):\n \"\"\"Whether self includes the score of coreference resolution.\"\"\"\n return self.measure_coref is not None\n\n def __add__(self, other: 'ScoreResult') -> 'ScoreResult':\n measures_pas = self.measures_pas + other.measures_pas if self.pas else None\n measures_bridging = self.measures_bridging + other.measures_bridging if self.bridging else None\n measure_coref = self.measure_coref + other.measure_coref if self.coreference else None\n return ScoreResult(measures_pas, measures_bridging, measure_coref)\n\n\n@dataclass\nclass Measure:\n \"\"\"A data class to calculate and represent F-measure\"\"\"\n denom_pred: int = 0\n denom_gold: int = 0\n correct: int = 0\n\n def __add__(self, other: 'Measure'):\n return Measure(self.denom_pred + other.denom_pred,\n self.denom_gold + other.denom_gold,\n self.correct + other.correct)\n\n def __eq__(self, other: 'Measure'):\n return self.denom_pred == other.denom_pred and \\\n self.denom_gold == other.denom_gold and \\\n self.correct == other.correct\n\n @property\n def precision(self) -> float:\n if self.denom_pred == 0:\n return .0\n return self.correct / self.denom_pred\n\n @property\n def recall(self) -> float:\n if self.denom_gold == 0:\n return .0\n return self.correct / self.denom_gold\n\n @property\n def f1(self) -> float:\n if self.denom_pred + self.denom_gold == 0:\n return .0\n return 2 * self.correct / (self.denom_pred + self.denom_gold)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--prediction-dir', default=None, type=str,\n help='path to directory where system output KWDLC files exist (default: None)')\n parser.add_argument('--gold-dir', default=None, type=str,\n help='path to directory where gold KWDLC files exist (default: None)')\n parser.add_argument('--coreference', '--coref', '--cr', action='store_true', default=False,\n help='perform coreference resolution')\n parser.add_argument('--bridging', '--brg', '--bar', action='store_true', default=False,\n help='perform bridging anaphora resolution')\n parser.add_argument('--case-string', type=str, default='ใฌ,ใฒ,ใ,ใฌ๏ผ',\n help='case strings separated by \",\"')\n parser.add_argument('--exophors', '--exo', type=str, default='่่
,่ชญ่
,ไธ็นๅฎ:ไบบ,ไธ็นๅฎ:็ฉ',\n help='exophor strings separated by \",\"')\n parser.add_argument('--read-prediction-from-pas-tag', action='store_true', default=False,\n help='use <่ฟฐ่ช้
ๆง้ :> tag instead of <rel > tag in prediction files')\n parser.add_argument('--pas-target', choices=['', 'pred', 'noun', 'all'], default='pred',\n help='PAS analysis evaluation target (pred: verbal predicates, noun: nominal predicates)')\n parser.add_argument('--result-html', default=None, type=str,\n help='path to html file which prediction result is exported (default: None)')\n parser.add_argument('--result-csv', default=None, type=str,\n help='path to csv file which prediction result is exported (default: None)')\n args = parser.parse_args()\n\n reader_gold = KyotoReader(Path(args.gold_dir), extract_nes=False, use_pas_tag=False)\n reader_pred = KyotoReader(\n Path(args.prediction_dir),\n extract_nes=False,\n use_pas_tag=args.read_prediction_from_pas_tag,\n )\n documents_pred = reader_pred.process_all_documents()\n documents_gold = reader_gold.process_all_documents()\n\n assert set(args.case_string.split(',')) <= set(CASE2YOMI.keys())\n msg = '\"ใ\" found in case string. If you want to perform bridging anaphora resolution, specify \"--bridging\" ' \\\n 'option instead'\n assert 'ใ' not in args.case_string.split(','), msg\n scorer = Scorer(documents_pred, documents_gold,\n target_cases=args.case_string.split(','),\n target_exophors=args.exophors.split(','),\n coreference=args.coreference,\n bridging=args.bridging,\n pas_target=args.pas_target)\n result = scorer.run()\n if args.result_html:\n scorer.write_html(Path(args.result_html))\n if args.result_csv:\n result.export_csv(args.result_csv)\n result.export_txt(sys.stdout)\n\n\nif __name__ == '__main__':\n main()\n"
] | [
[
"pandas.notnull",
"pandas.Series",
"pandas.concat",
"pandas.DataFrame"
]
] |
hzitoun/neat-EO | [
"3519f1b2a5b4eb6b1b8ec38bce0e722efb61a94b"
] | [
"neat_eo/tools/dataset.py"
] | [
"import os\nimport sys\nimport torch\nimport numpy as np\nfrom tqdm import tqdm\nfrom torch.utils.data import DataLoader\nfrom neat_eo.core import load_config, check_classes, check_channels\nfrom neat_eo.tiles import tiles_from_dir, tile_label_from_file, tiles_from_csv\n\n\ndef add_parser(subparser, formatter_class):\n\n parser = subparser.add_parser(\"dataset\", help=\"train dataset helper\", formatter_class=formatter_class)\n parser.add_argument(\"--config\", type=str, help=\"path to config file [required, if no global config setting]\")\n parser.add_argument(\"--dataset\", type=str, required=True, help=\"dataset path [required]\")\n parser.add_argument(\"--cover\", type=str, help=\"path to csv tiles cover file, to filter tiles dataset on [optional]\")\n parser.add_argument(\"--workers\", type=int, help=\"number of workers [default: CPU]\")\n\n choices = [\"check\", \"weights\"]\n parser.add_argument(\"--mode\", type=str, default=\"check\", choices=choices, help=\"dataset mode [default: check]\")\n parser.set_defaults(func=main)\n\n\nclass LabelsDataset(torch.utils.data.Dataset):\n def __init__(self, root, num_classes, cover=None):\n super().__init__()\n self.num_classes = num_classes\n self.tiles = [path for tile, path in tiles_from_dir(os.path.join(root, \"labels\"), cover=cover, xyz_path=True)]\n assert len(self.tiles), \"Empty Dataset\"\n\n def __len__(self):\n return len(self.tiles)\n\n def __getitem__(self, i):\n mask = torch.from_numpy(tile_label_from_file(self.tiles[i]))\n return torch.bincount(mask.view(-1), minlength=self.num_classes), mask.nelement()\n\n\ndef compute_classes_weights(dataset, classes, cover, workers):\n label_dataset = LabelsDataset(dataset, len(classes), cover)\n loader = DataLoader(label_dataset, batch_size=workers, num_workers=workers)\n n_classes = np.zeros(len(classes))\n n_pixels = 0\n for c, n in tqdm(loader, desc=\"Classes Weights\", unit=\"batch\", ascii=True):\n n_classes += c.data.numpy()[0]\n n_pixels += int(n.data.numpy()[0])\n\n weights = 1 / np.log(1.02 + (n_classes / n_pixels)) # cf https://arxiv.org/pdf/1606.02147.pdf\n return weights.round(3, out=weights).tolist()\n\n\ndef main(args):\n\n assert os.path.isdir(os.path.expanduser(args.dataset)), \"--dataset path is not a directory\"\n args.cover = [tile for tile in tiles_from_csv(os.path.expanduser(args.cover))] if args.cover else None\n config = load_config(args.config)\n\n if not args.workers:\n args.workers = os.cpu_count()\n\n print(\"neo dataset {} on CPU, with {} workers\".format(args.mode, args.workers), file=sys.stderr, flush=True)\n\n if args.mode == \"check\":\n check_classes(config)\n check_channels(config)\n\n # TODO check dataset\n\n if args.mode == \"weights\":\n check_classes(config)\n weights = compute_classes_weights(args.dataset, config[\"classes\"], args.cover, args.workers)\n print(\",\".join(map(str, weights)))\n"
] | [
[
"torch.utils.data.DataLoader",
"numpy.log"
]
] |
Michael-Beukman/NEATNoveltyPCG | [
"2441d80eb0f6dd288a00ebb56c432963cefc879d"
] | [
"src/games/game.py"
] | [
"from typing import Tuple\nimport numpy as np\nfrom games.level import Level\nclass Game:\n \"\"\"\n A game can be played (by a human/agent/etc).\n It requires a level and has some rules.\n \"\"\"\n def __init__(self, level: Level):\n self.level = level\n self.current_pos = np.array([0, 0])\n\n def step(self, action: int) -> Tuple[bool, float]:\n \"\"\"Should Step in the environment given the action.\n Args:\n action int\n Returns:\n done, reward\n \"\"\"\n raise NotImplementedError()\n def reset(self, level: Level):\n \"\"\"Resets this env given the level. The player now starts at the original spot again.\n\n Args:\n level (Level): The level to use.\n \"\"\"\n self.level = level\n self.current_pos = np.array([0, 0])"
] | [
[
"numpy.array"
]
] |
godweiyang/ParaGen | [
"9665d1244ea38a41fc06b4e0a7f6411985e2221f"
] | [
"examples/glat/glat/glat_length_search.py"
] | [
"import torch\nfrom torch import Tensor\nfrom typing import Callable, Tuple\nfrom paragen.utils.ops import local_seed\nfrom paragen.modules.utils import create_padding_mask_from_length\nfrom paragen.modules.search.abstract_search import AbstractSearch\n\n\"\"\"\nArgs: window_size L\n\ninput: length [B], encoder_out [S * B * D], encoder_padding_mask [B * S]\n\nmid: l' in [length-window_size, length+window_size] [B, 2*L+1]\npredict sequennce candidate for each l' [B, 2 * L + 1, 2 * L + 1], [B, 2 * L + 1]\nrerank candidates [B, 2*L+1]\n\noutput: sequence\n\"\"\"\nclass GLATLengthSearcher(AbstractSearch):\n def __init__(self,\n window_size=5,\n max_len=256,\n seed=None,\n padding_token=None,\n calc_decoder_input: Callable[[Tensor, Tensor], Tensor]=None,\n decoder=None) -> None:\n super().__init__()\n self._window_size = window_size\n self._max_len = max_len\n self._seed = seed\n self._padding_token = padding_token\n self._calc_decoder_input = calc_decoder_input\n self._decoder = decoder\n\n def build(self, *args, **kwargs):\n pass\n\n def forward(self, \n length: Tensor,\n src_padding_mask: Tensor,\n src_hidden: Tensor) -> Tensor:\n _lower_bound = torch.tensor(1).to(length)\n _upper_bound = torch.tensor(self._max_len).to(length)\n maxlen = torch.minimum(_upper_bound, length.max() + self._window_size)\n candidates = list()\n for offset in range(-self._window_size, self._window_size + 1):\n _length = length + offset\n _length = torch.maximum(_lower_bound, _length)\n _length = torch.minimum(_upper_bound, _length)\n candidates.append(self._search(_length, maxlen, src_padding_mask, src_hidden))\n scores = torch.stack([candidate[1] for candidate in candidates])\n best_idxs = scores.max(dim=0).indices\n outputs = torch.stack([candidates[idx][0][i] for i, idx in enumerate(best_idxs)])\n return outputs\n\n def _search(self,\n length: Tensor,\n maxlen,\n src_padding_mask: Tensor,\n src_hidden: Tensor) -> Tuple[Tensor, Tensor]:\n tgt_padding_mask = create_padding_mask_from_length(length, maxlen)\n decoder_input = self._calc_decoder_input(src_padding_mask, tgt_padding_mask)\n with local_seed(self._seed):\n logits = self._decoder(decoder_input,\n src_hidden,\n tgt_padding_mask,\n src_padding_mask)\n prob, decoder_output = logits.max(dim=-1)\n score = torch.sum(prob * (~tgt_padding_mask), dim=-1) / length\n decoder_output = decoder_output.masked_fill_(tgt_padding_mask, self._padding_token)\n return decoder_output, score\n\n"
] | [
[
"torch.sum",
"torch.stack",
"torch.tensor",
"torch.minimum",
"torch.maximum"
]
] |
jefflai108/fairseq | [
"fd3f3e7712a7084b9219e45e7b3dc843c69797ba"
] | [
"examples/speech_recognition/w2l_decoder.py"
] | [
"#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n\"\"\"\nWav2letter decoders.\n\"\"\"\n\nimport gc\nimport itertools as it\nimport os.path as osp\nimport warnings\nfrom collections import deque, namedtuple\n\nimport numpy as np\nimport torch\nfrom examples.speech_recognition.data.replabels import unpack_replabels\nfrom fairseq import tasks\nfrom fairseq.utils import apply_to_sample\n\n\ntry:\n from wav2letter.common import create_word_dict, load_words\n from wav2letter.criterion import CpuViterbiPath, get_data_ptr_as_bytes\n from wav2letter.decoder import (\n CriterionType,\n DecoderOptions,\n KenLM,\n LM,\n LMState,\n SmearingMode,\n Trie,\n LexiconDecoder,\n )\nexcept:\n warnings.warn(\n \"wav2letter python bindings are required to use this functionality. Please install from https://github.com/facebookresearch/wav2letter/wiki/Python-bindings\"\n )\n LM = object\n LMState = object\n\n\nclass W2lDecoder(object):\n def __init__(self, args, tgt_dict):\n self.tgt_dict = tgt_dict\n self.vocab_size = len(tgt_dict)\n self.nbest = args.nbest\n\n # criterion-specific init\n if args.criterion == \"ctc\":\n self.criterion_type = CriterionType.CTC\n self.blank = (\n tgt_dict.index(\"<ctc_blank>\")\n if \"<ctc_blank>\" in tgt_dict.indices\n else tgt_dict.bos()\n )\n self.asg_transitions = None\n elif args.criterion == \"asg_loss\":\n self.criterion_type = CriterionType.ASG\n self.blank = -1\n self.asg_transitions = args.asg_transitions\n self.max_replabel = args.max_replabel\n assert len(self.asg_transitions) == self.vocab_size ** 2\n else:\n raise RuntimeError(f\"unknown criterion: {args.criterion}\")\n\n def generate(self, models, sample, **unused):\n \"\"\"Generate a batch of inferences.\"\"\"\n # model.forward normally channels prev_output_tokens into the decoder\n # separately, but SequenceGenerator directly calls model.encoder\n encoder_input = {\n k: v for k, v in sample[\"net_input\"].items() if k != \"prev_output_tokens\"\n }\n emissions = self.get_emissions(models, encoder_input)\n return self.decode(emissions)\n\n def get_emissions(self, models, encoder_input):\n \"\"\"Run encoder and normalize emissions\"\"\"\n # encoder_out = models[0].encoder(**encoder_input)\n encoder_out = models[0](**encoder_input)\n if self.criterion_type == CriterionType.CTC:\n emissions = models[0].get_normalized_probs(encoder_out, log_probs=True)\n elif self.criterion_type == CriterionType.ASG:\n emissions = encoder_out[\"encoder_out\"]\n return emissions.transpose(0, 1).float().cpu().contiguous()\n\n def get_tokens(self, idxs):\n \"\"\"Normalize tokens by handling CTC blank, ASG replabels, etc.\"\"\"\n idxs = (g[0] for g in it.groupby(idxs))\n if self.criterion_type == CriterionType.CTC:\n idxs = filter(lambda x: x != self.blank, idxs)\n elif self.criterion_type == CriterionType.ASG:\n idxs = filter(lambda x: x >= 0, idxs)\n idxs = unpack_replabels(list(idxs), self.tgt_dict, self.max_replabel)\n return torch.LongTensor(list(idxs))\n\n\nclass W2lViterbiDecoder(W2lDecoder):\n def __init__(self, args, tgt_dict):\n super().__init__(args, tgt_dict)\n\n def decode(self, emissions):\n B, T, N = emissions.size()\n hypos = []\n if self.asg_transitions is None:\n transitions = torch.FloatTensor(N, N).zero_()\n else:\n transitions = torch.FloatTensor(self.asg_transitions).view(N, N)\n viterbi_path = torch.IntTensor(B, T)\n workspace = torch.ByteTensor(CpuViterbiPath.get_workspace_size(B, T, N))\n CpuViterbiPath.compute(\n B,\n T,\n N,\n get_data_ptr_as_bytes(emissions),\n get_data_ptr_as_bytes(transitions),\n get_data_ptr_as_bytes(viterbi_path),\n get_data_ptr_as_bytes(workspace),\n )\n return [\n [{\"tokens\": self.get_tokens(viterbi_path[b].tolist()), \"score\": 0}]\n for b in range(B)\n ]\n\n\nclass W2lKenLMDecoder(W2lDecoder):\n def __init__(self, args, tgt_dict):\n super().__init__(args, tgt_dict)\n\n self.silence = (\n tgt_dict.index(\"<ctc_blank>\")\n if \"<ctc_blank>\" in tgt_dict.indices\n else tgt_dict.bos()\n )\n self.lexicon = load_words(args.lexicon)\n self.word_dict = create_word_dict(self.lexicon)\n self.unk_word = self.word_dict.get_index(\"<unk>\")\n\n self.lm = KenLM(args.kenlm_model, self.word_dict)\n self.trie = Trie(self.vocab_size, self.silence)\n\n start_state = self.lm.start(False)\n for i, (word, spellings) in enumerate(self.lexicon.items()):\n word_idx = self.word_dict.get_index(word)\n _, score = self.lm.score(start_state, word_idx)\n for spelling in spellings:\n spelling_idxs = [tgt_dict.index(token) for token in spelling]\n assert (\n tgt_dict.unk() not in spelling_idxs\n ), f\"{spelling} {spelling_idxs}\"\n self.trie.insert(spelling_idxs, word_idx, score)\n self.trie.smear(SmearingMode.MAX)\n\n self.decoder_opts = DecoderOptions(\n args.beam,\n int(getattr(args, \"beam_size_token\", len(tgt_dict))),\n args.beam_threshold,\n args.lm_weight,\n args.word_score,\n args.unk_weight,\n args.sil_weight,\n 0,\n False,\n self.criterion_type,\n )\n\n if self.asg_transitions is None:\n N = 768\n # self.asg_transitions = torch.FloatTensor(N, N).zero_()\n self.asg_transitions = []\n\n self.decoder = LexiconDecoder(\n self.decoder_opts,\n self.trie,\n self.lm,\n self.silence,\n self.blank,\n self.unk_word,\n self.asg_transitions,\n False,\n )\n\n def decode(self, emissions):\n B, T, N = emissions.size()\n hypos = []\n for b in range(B):\n emissions_ptr = emissions.data_ptr() + 4 * b * emissions.stride(0)\n results = self.decoder.decode(emissions_ptr, T, N)\n\n nbest_results = results[: self.nbest]\n hypos.append(\n [\n {\n \"tokens\": self.get_tokens(result.tokens),\n \"score\": result.score,\n \"words\": [\n self.word_dict.get_entry(x) for x in result.words if x >= 0\n ],\n }\n for result in nbest_results\n ]\n )\n return hypos\n\n\nFairseqLMState = namedtuple(\"FairseqLMState\", [\"prefix\", \"incremental_state\", \"probs\"])\n\n\nclass FairseqLM(LM):\n def __init__(self, dictionary, model):\n LM.__init__(self)\n self.dictionary = dictionary\n self.model = model\n self.unk = self.dictionary.unk()\n\n self.save_incremental = False # this currently does not work properly\n self.max_cache = 20_000\n\n model.cuda()\n model.eval()\n model.make_generation_fast_()\n\n self.states = {}\n self.stateq = deque()\n\n def start(self, start_with_nothing):\n state = LMState()\n prefix = torch.LongTensor([[self.dictionary.eos()]])\n incremental_state = {} if self.save_incremental else None\n with torch.no_grad():\n res = self.model(prefix.cuda(), incremental_state=incremental_state)\n probs = self.model.get_normalized_probs(res, log_probs=True, sample=None)\n\n if incremental_state is not None:\n incremental_state = apply_to_sample(lambda x: x.cpu(), incremental_state)\n self.states[state] = FairseqLMState(\n prefix.numpy(), incremental_state, probs[0, -1].cpu().numpy()\n )\n self.stateq.append(state)\n\n return state\n\n def score(self, state: LMState, token_index: int, no_cache: bool = False):\n \"\"\"\n Evaluate language model based on the current lm state and new word\n Parameters:\n -----------\n state: current lm state\n token_index: index of the word\n (can be lexicon index then you should store inside LM the\n mapping between indices of lexicon and lm, or lm index of a word)\n\n Returns:\n --------\n (LMState, float): pair of (new state, score for the current word)\n \"\"\"\n curr_state = self.states[state]\n\n def trim_cache(targ_size):\n while len(self.stateq) > targ_size:\n rem_k = self.stateq.popleft()\n rem_st = self.states[rem_k]\n rem_st = FairseqLMState(rem_st.prefix, None, None)\n self.states[rem_k] = rem_st\n\n if curr_state.probs is None:\n new_incremental_state = (\n curr_state.incremental_state.copy()\n if curr_state.incremental_state is not None\n else None\n )\n with torch.no_grad():\n if new_incremental_state is not None:\n new_incremental_state = apply_to_sample(\n lambda x: x.cuda(), new_incremental_state\n )\n elif self.save_incremental:\n new_incremental_state = {}\n\n res = self.model(\n torch.from_numpy(curr_state.prefix).cuda(),\n incremental_state=new_incremental_state,\n )\n probs = self.model.get_normalized_probs(\n res, log_probs=True, sample=None\n )\n\n if new_incremental_state is not None:\n new_incremental_state = apply_to_sample(\n lambda x: x.cpu(), new_incremental_state\n )\n\n curr_state = FairseqLMState(\n curr_state.prefix, new_incremental_state, probs[0, -1].cpu().numpy()\n )\n\n if not no_cache:\n self.states[state] = curr_state\n self.stateq.append(state)\n\n score = curr_state.probs[token_index].item()\n\n trim_cache(self.max_cache)\n\n outstate = state.child(token_index)\n if outstate not in self.states and not no_cache:\n prefix = np.concatenate(\n [curr_state.prefix, torch.LongTensor([[token_index]])], -1\n )\n incr_state = curr_state.incremental_state\n\n self.states[outstate] = FairseqLMState(prefix, incr_state, None)\n\n if token_index == self.unk:\n score = float(\"-inf\")\n\n return outstate, score\n\n def finish(self, state: LMState):\n \"\"\"\n Evaluate eos for language model based on the current lm state\n\n Returns:\n --------\n (LMState, float): pair of (new state, score for the current word)\n \"\"\"\n return self.score(state, self.dictionary.eos())\n\n def empty_cache(self):\n self.states = {}\n self.stateq = deque()\n gc.collect()\n\n\nclass W2lFairseqLMDecoder(W2lDecoder):\n def __init__(self, args, tgt_dict):\n super().__init__(args, tgt_dict)\n\n self.silence = tgt_dict.bos()\n\n self.unit_lm = getattr(args, \"unit_lm\", False)\n\n self.lexicon = load_words(args.lexicon) if args.lexicon else None\n self.idx_to_wrd = {}\n\n checkpoint = torch.load(args.kenlm_model, map_location=\"cpu\")\n lm_args = checkpoint[\"args\"]\n lm_args.data = osp.dirname(args.kenlm_model)\n print(lm_args)\n task = tasks.setup_task(lm_args)\n model = task.build_model(lm_args)\n model.load_state_dict(checkpoint[\"model\"], strict=False)\n\n self.trie = Trie(self.vocab_size, self.silence)\n\n self.word_dict = task.dictionary\n self.unk_word = self.word_dict.unk()\n self.lm = FairseqLM(self.word_dict, model)\n\n self.decoder_opts = DecoderOptions(\n args.beam,\n int(getattr(args, \"beam_size_token\", len(tgt_dict))),\n args.beam_threshold,\n args.lm_weight,\n args.word_score,\n args.unk_weight,\n args.sil_weight,\n 0,\n False,\n self.criterion_type,\n )\n\n if self.lexicon:\n start_state = self.lm.start(False)\n for i, (word, spellings) in enumerate(self.lexicon.items()):\n if self.unit_lm:\n word_idx = i\n self.idx_to_wrd[i] = word\n score = 0\n else:\n word_idx = self.word_dict.index(word)\n _, score = self.lm.score(start_state, word_idx, no_cache=True)\n\n for spelling in spellings:\n spelling_idxs = [tgt_dict.index(token) for token in spelling]\n assert (\n tgt_dict.unk() not in spelling_idxs\n ), f\"{spelling} {spelling_idxs}\"\n self.trie.insert(spelling_idxs, word_idx, score)\n self.trie.smear(SmearingMode.MAX)\n\n self.decoder = LexiconDecoder(\n self.decoder_opts,\n self.trie,\n self.lm,\n self.silence,\n self.blank,\n self.unk_word,\n [],\n self.unit_lm,\n )\n else:\n from wav2letter.decoder import LexiconFreeDecoder\n self.decoder = LexiconFreeDecoder(\n self.decoder_opts, self.lm, self.silence, self.blank, []\n )\n\n def decode(self, emissions):\n B, T, N = emissions.size()\n hypos = []\n\n def idx_to_word(idx):\n if self.unit_lm:\n return self.idx_to_wrd[idx]\n else:\n return self.word_dict[idx]\n\n def make_hypo(result):\n hypo = {\"tokens\": self.get_tokens(result.tokens), \"score\": result.score}\n if self.lexicon:\n hypo[\"words\"] = [idx_to_word(x) for x in result.words if x >= 0]\n return hypo\n\n for b in range(B):\n emissions_ptr = emissions.data_ptr() + 4 * b * emissions.stride(0)\n results = self.decoder.decode(emissions_ptr, T, N)\n\n nbest_results = results[: self.nbest]\n hypos.append([make_hypo(result) for result in nbest_results])\n self.lm.empty_cache()\n\n return hypos\n"
] | [
[
"torch.FloatTensor",
"torch.load",
"torch.no_grad",
"torch.from_numpy",
"torch.IntTensor",
"torch.LongTensor"
]
] |
abhinavsp0730/datasets | [
"3c69b42456fb947a7af7086a3310b972bd1ae3fb"
] | [
"tensorflow_datasets/object_detection/kitti.py"
] | [
"# coding=utf-8\n# Copyright 2020 The TensorFlow Datasets Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Kitti dataset.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport csv\nimport os\nimport numpy as np\nimport tensorflow.compat.v2 as tf\nimport tensorflow_datasets.public_api as tfds\n\n_CITATION = \"\"\"\\\n@inproceedings{Geiger2012CVPR,\n author = {Andreas Geiger and Philip Lenz and Raquel Urtasun},\n title = {Are we ready for Autonomous Driving? The KITTI Vision Benchmark Suite},\n booktitle = {Conference on Computer Vision and Pattern Recognition (CVPR)},\n year = {2012}\n}\n\"\"\"\n_DESCRIPTION = \"\"\"\\\nKitti contains a suite of vision tasks built using an autonomous driving\nplatform. The full benchmark contains many tasks such as stereo, optical flow,\nvisual odometry, etc. This dataset contains the object detection dataset,\nincluding the monocular images and bounding boxes. The dataset contains 7481\ntraining images annotated with 3D bounding boxes. A full description of the\nannotations can be found in the readme of the object development kit readme on\nthe Kitti homepage.\n\"\"\"\n_HOMEPAGE_URL = \"http://www.cvlibs.net/datasets/kitti/\"\n_DATA_URL = \"https://s3.eu-central-1.amazonaws.com/avg-kitti\"\n_IMAGES_FNAME = \"data_object_image_2.zip\"\n_LABELS_FNAME = \"data_object_label_2.zip\"\n_DEVKIT_FNAME = \"devkit_object.zip\"\n_OBJECT_LABELS = [\n \"Car\",\n \"Van\",\n \"Truck\",\n \"Pedestrian\",\n \"Person_sitting\",\n \"Cyclist\",\n \"Tram\",\n \"Misc\",\n]\n# The percentage of trainset videos to put into validation and test sets.\n# The released test images do not have labels.\n_VALIDATION_SPLIT_PERCENT_VIDEOS = 10\n_TEST_SPLIT_PERCENT_VIDEOS = 10\n\n# Raw Kitti representation of a bounding box. Coordinates are in pixels,\n# measured from the top-left hand corner.\nRawBoundingBox = collections.namedtuple(\"RawBoundingBox\",\n [\"top\", \"bottom\", \"left\", \"right\"])\n\n\nclass Kitti(tfds.core.GeneratorBasedBuilder):\n \"\"\"Kitti dataset.\"\"\"\n\n VERSION = tfds.core.Version(\"3.1.0\")\n SUPPORTED_VERSIONS = [\n tfds.core.Version(\n \"2.0.0\", \"New split API (https://tensorflow.org/datasets/splits)\"),\n ]\n\n def _info(self):\n # Annotation descriptions are in the object development kit.\n annotations = {\n \"type\": tfds.features.ClassLabel(names=_OBJECT_LABELS),\n \"truncated\": tfds.features.Tensor(shape=(), dtype=tf.float32),\n \"occluded\": tfds.features.ClassLabel(num_classes=4),\n \"alpha\": tfds.features.Tensor(shape=(), dtype=tf.float32),\n \"bbox\": tfds.features.BBoxFeature(),\n \"dimensions\": tfds.features.Tensor(shape=(3,), dtype=tf.float32),\n \"location\": tfds.features.Tensor(shape=(3,), dtype=tf.float32),\n \"rotation_y\": tfds.features.Tensor(shape=(), dtype=tf.float32),\n }\n return tfds.core.DatasetInfo(\n builder=self,\n description=_DESCRIPTION,\n features=tfds.features.FeaturesDict({\n \"image\": tfds.features.Image(),\n \"image/file_name\": tfds.features.Text(), # E.g. \"000001.png\".\n \"objects\": tfds.features.Sequence(annotations),\n }),\n homepage=_HOMEPAGE_URL,\n citation=_CITATION,\n )\n\n def _split_generators(self, dl_manager):\n filenames = {\n \"images\": _DATA_URL + \"/\" + _IMAGES_FNAME,\n \"annotations\": _DATA_URL + \"/\" + _LABELS_FNAME,\n \"devkit\": _DATA_URL + \"/\" + _DEVKIT_FNAME,\n }\n files = dl_manager.download(filenames)\n train_images, validation_images, test_images = _build_splits(\n dl_manager.iter_archive(files[\"devkit\"]))\n\n return [\n tfds.core.SplitGenerator(\n name=tfds.Split.TRAIN,\n gen_kwargs={\n \"images\": dl_manager.iter_archive(files[\"images\"]),\n \"annotations\": dl_manager.iter_archive(files[\"annotations\"]),\n \"subdir\": \"training\",\n \"image_ids\": train_images,\n }),\n tfds.core.SplitGenerator(\n name=tfds.Split.VALIDATION,\n gen_kwargs={\n \"images\": dl_manager.iter_archive(files[\"images\"]),\n \"annotations\": dl_manager.iter_archive(files[\"annotations\"]),\n \"subdir\": \"training\",\n \"image_ids\": validation_images,\n }),\n tfds.core.SplitGenerator(\n name=tfds.Split.TEST,\n gen_kwargs={\n \"images\": dl_manager.iter_archive(files[\"images\"]),\n \"annotations\": dl_manager.iter_archive(files[\"annotations\"]),\n \"subdir\": \"training\",\n \"image_ids\": test_images,\n }),\n ]\n\n def _generate_examples(self, images, annotations, subdir, image_ids):\n \"\"\"Yields images and annotations.\n\n Args:\n images: object that iterates over the archive of images.\n annotations: object that iterates over the archive of annotations.\n subdir: subdirectory from which to extract images and annotations, e.g.\n training or testing.\n image_ids: file ids for images in this split.\n\n Yields:\n A tuple containing the example's key, and the example.\n \"\"\"\n cv2 = tfds.core.lazy_imports.cv2\n\n all_annotations = dict()\n for fpath, fobj in annotations:\n prefix, ext = os.path.splitext(fpath)\n if ext != \".txt\":\n continue\n if prefix.split(\"/\")[0] != subdir:\n continue\n\n # Key is the datapoint id. E.g. training/label_2/label_000016 -> 16.\n all_annotations[int(prefix[-6:])] = _parse_kitti_annotations(fobj)\n\n for fpath, fobj in images:\n prefix, ext = os.path.splitext(fpath)\n if ext != \".png\":\n continue\n if prefix.split(\"/\")[0] != subdir:\n continue\n image_id = int(prefix[-6:])\n if image_id not in image_ids:\n continue\n annotations = all_annotations[image_id]\n img = cv2.imdecode(np.fromstring(fobj.read(), dtype=np.uint8),\n cv2.IMREAD_COLOR)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n height, width, _ = img.shape\n for obj in annotations:\n obj[\"bbox\"] = _build_bounding_box(obj[\"bbox_raw\"], height, width)\n del obj[\"bbox_raw\"]\n _, fname = os.path.split(fpath)\n record = {\"image\": img, \"image/file_name\": fname, \"objects\": annotations}\n yield fname, record\n\n\ndef _build_bounding_box(bbox, height, width):\n \"\"\"Builds and returns TFDS bounding box.\n\n Args:\n bbox: RawBoundingBox, bounding box in Kitti coordinates (origin top left).\n height: Image height in pixels.\n width: Image width in pixels.\n\n Returns:\n A TFDS BBox (origin bottom left).\n \"\"\"\n return tfds.features.BBox(\n ymin=(height - bbox.bottom) / height,\n ymax=(height - bbox.top) / height,\n xmin=bbox.left / width,\n xmax=bbox.right / width,\n )\n\n\ndef _parse_kitti_annotations(annotations_csv):\n \"\"\"Loads and parses the Kitti object annotations.\n\n Args:\n annotations_csv: csv file containing annotations for a single image.\n\n Returns:\n A list of labelled bounding boxes. Each bounding box is stored as a\n dictionary of features.\n \"\"\"\n annotations = []\n for line in annotations_csv:\n (obj_type, truncated, occluded, alpha, left, top, right, bottom, height,\n width, length, x, y, z,\n rotation_y) = list(csv.reader([line.decode()], delimiter=\" \"))[0]\n # DontCare objects lack annotations, so skip them.\n if obj_type == \"DontCare\":\n continue\n annotations.append({\n \"type\": obj_type,\n \"truncated\": float(truncated),\n \"occluded\": int(occluded),\n \"alpha\": float(alpha),\n \"bbox_raw\": RawBoundingBox(\n top=float(top),\n bottom=float(bottom),\n left=float(left),\n right=float(right)),\n \"dimensions\": [float(v) for v in [height, width, length]],\n \"location\": [float(v) for v in [x, y, z]],\n \"rotation_y\": float(rotation_y),\n })\n return annotations\n\n\ndef _build_splits(devkit):\n \"\"\"Splits the train data into train/val/test by video.\n\n Ensures that images from the same video do not traverse the splits.\n\n Args:\n devkit: object that iterates over the devkit archive.\n\n Returns:\n train_images: File ids for the training set images.\n validation_images: File ids for the validation set images.\n test_images: File ids for the test set images.\n \"\"\"\n mapping_line_ids = None\n mapping_lines = None\n for fpath, fobj in devkit:\n if fpath == \"mapping/train_rand.txt\":\n # Converts 1-based line index to 0-based line index.\n mapping_line_ids = [\n int(x.strip()) - 1 for x in fobj.read().decode(\"utf-8\").split(\",\")\n ]\n if fpath == \"mapping/train_mapping.txt\":\n mapping_lines = fobj.readlines()\n mapping_lines = [x.decode(\"utf-8\") for x in mapping_lines]\n\n assert mapping_line_ids\n assert mapping_lines\n\n video_to_image = collections.defaultdict(list)\n for image_id, mapping_lineid in enumerate(mapping_line_ids):\n line = mapping_lines[mapping_lineid]\n video_id = line.split(\" \")[1]\n video_to_image[video_id].append(image_id)\n\n # Sets numpy random state.\n numpy_original_state = np.random.get_state()\n np.random.seed(seed=123)\n\n # Max 1 for testing.\n num_test_videos = max(1,\n _TEST_SPLIT_PERCENT_VIDEOS * len(video_to_image) // 100)\n num_validation_videos = max(\n 1,\n _VALIDATION_SPLIT_PERCENT_VIDEOS * len(video_to_image) // 100)\n test_videos = set(\n np.random.choice(\n sorted(list(video_to_image.keys())), num_test_videos, replace=False))\n validation_videos = set(\n np.random.choice(\n sorted(list(set(video_to_image.keys()) - set(test_videos))),\n num_validation_videos,\n replace=False))\n test_images = []\n validation_images = []\n train_images = []\n for k, v in video_to_image.items():\n if k in test_videos:\n test_images.extend(v)\n elif k in validation_videos:\n validation_images.extend(v)\n else:\n train_images.extend(v)\n\n # Resets numpy random state.\n np.random.set_state(numpy_original_state)\n return train_images, validation_images, test_images\n"
] | [
[
"numpy.random.set_state",
"numpy.random.seed",
"numpy.random.get_state"
]
] |
mfwofford/ginga | [
"e1b4d04e32b49229fd1345f8a909bc614140cafd"
] | [
"ginga/util/io_rgb.py"
] | [
"#\n# io_rgb.py -- RGB image file handling.\n#\n# This is open-source software licensed under a BSD license.\n# Please see the file LICENSE.txt for details.\n#\nimport sys\nimport time\nimport mimetypes\nfrom io import BytesIO\n\nimport numpy as np\n\nfrom ginga.BaseImage import Header, ImageError\nfrom ginga.util import iohelper, rgb_cms\n\ntry:\n # do we have opencv available?\n import cv2\n have_opencv = True\nexcept ImportError:\n have_opencv = False\n\ntry:\n # do we have Python Imaging Library available?\n import PIL.Image as PILimage\n from PIL.ExifTags import TAGS\n have_pil = True\nexcept ImportError:\n have_pil = False\n\nhave_pilutil = False\ntry:\n from scipy.misc import imresize, imsave\n have_pilutil = True\nexcept ImportError:\n pass\n\n# piexif library for getting metadata, in the case that we don't have PIL\ntry:\n import piexif\n have_exif = True\nexcept ImportError:\n have_exif = False\n\n# For testing...\n#have_pilutil = False\n#have_pil = False\n#have_cms = False\n#have_exif = False\n#have_opencv = False\n\n\nclass RGBFileHandler(object):\n\n def __init__(self, logger):\n self.logger = logger\n self._path = None\n\n self.clr_mgr = rgb_cms.ColorManager(self.logger)\n\n def load_file(self, filespec, dstobj=None, **kwargs):\n info = iohelper.get_fileinfo(filespec)\n if not info.ondisk:\n raise ValueError(\"File does not appear to be on disk: %s\" % (\n info.url))\n\n filepath = info.filepath\n if dstobj is None:\n # Put here to avoid circular import\n from ginga.RGBImage import RGBImage\n dstobj = RGBImage(logger=self.logger)\n\n header = Header()\n metadata = {'header': header, 'path': filepath}\n\n data_np = self._imload(filepath, header)\n\n # TODO: set up the channel order correctly\n dstobj.set_data(data_np, metadata=metadata)\n\n if dstobj.name is not None:\n dstobj.set(name=dstobj.name)\n else:\n name = iohelper.name_image_from_path(filepath, idx=None)\n dstobj.set(name=name)\n\n dstobj.set(path=filepath, idx=None, image_loader=self.load_file)\n return dstobj\n\n def open_file(self, filespec, **kwargs):\n self._path = filespec\n return self\n\n def close(self):\n self._path = None\n\n def __len__(self):\n return 1\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.close()\n return False\n\n def load_idx_cont(self, idx_spec, loader_cont_fn, **kwargs):\n if self._path is None:\n raise ValueError(\"Please call open_file() first!\")\n\n # TODO: raise an error if idx_spec doesn't match a single image\n data_obj = self.load_file(self._path, **kwargs)\n\n # call continuation function\n loader_cont_fn(data_obj)\n\n def save_file_as(self, filepath, data_np, header):\n if not have_pil:\n raise ImageError(\"Install PIL to be able to save images\")\n\n # TODO: save keyword metadata!\n imsave(filepath, data_np)\n\n def _imload(self, filepath, kwds):\n \"\"\"Load an image file, guessing the format, and return a numpy\n array containing an RGB image. If EXIF keywords can be read\n they are returned in the dict _kwds_.\n \"\"\"\n start_time = time.time()\n typ, enc = mimetypes.guess_type(filepath)\n if not typ:\n typ = 'image/jpeg'\n typ, subtyp = typ.split('/')\n self.logger.debug(\"MIME type is %s/%s\" % (typ, subtyp))\n\n data_loaded = False\n if have_opencv and subtyp not in ['gif']:\n # First choice is OpenCv, because it supports high-bit depth\n # multiband images\n means = 'opencv'\n data_np = cv2.imread(filepath,\n cv2.IMREAD_ANYDEPTH + cv2.IMREAD_ANYCOLOR)\n if data_np is not None:\n data_loaded = True\n # funky indexing because opencv returns BGR images,\n # whereas PIL and others return RGB\n if len(data_np.shape) >= 3 and data_np.shape[2] >= 3:\n data_np = data_np[..., :: -1]\n\n # OpenCv doesn't \"do\" image metadata, so we punt to piexif\n # library (if installed)\n self.piexif_getexif(filepath, kwds)\n\n # OpenCv added a feature to do auto-orientation when loading\n # (see https://github.com/opencv/opencv/issues/4344)\n # So reset these values to prevent auto-orientation from\n # happening later\n kwds['Orientation'] = 1\n kwds['Image Orientation'] = 1\n\n # convert to working color profile, if can\n if self.clr_mgr.can_profile():\n data_np = self.clr_mgr.profile_to_working_numpy(data_np, kwds)\n\n if not data_loaded and have_pil:\n means = 'PIL'\n image = PILimage.open(filepath)\n\n try:\n if hasattr(image, '_getexif'):\n info = image._getexif()\n if info is not None:\n for tag, value in info.items():\n kwd = TAGS.get(tag, tag)\n kwds[kwd] = value\n\n elif have_exif:\n self.piexif_getexif(image.info[\"exif\"], kwds)\n\n else:\n self.logger.warning(\"Please install 'piexif' module to get image metadata\")\n\n except Exception as e:\n self.logger.warning(\"Failed to get image metadata: %s\" % (str(e)))\n\n # convert to working color profile, if can\n if self.clr_mgr.can_profile():\n image = self.clr_mgr.profile_to_working_pil(image, kwds)\n\n # convert from PIL to numpy\n data_np = np.array(image)\n if data_np is not None:\n data_loaded = True\n\n if (not data_loaded and (typ == 'image') and\n (subtyp in ('x-portable-pixmap', 'x-portable-greymap'))):\n # Special opener for PPM files, preserves high bit depth\n means = 'built-in'\n data_np = open_ppm(filepath)\n if data_np is not None:\n data_loaded = True\n\n if not data_loaded:\n raise ImageError(\"No way to load image format '%s/%s'\" % (\n typ, subtyp))\n\n end_time = time.time()\n self.logger.debug(\"loading (%s) time %.4f sec\" % (\n means, end_time - start_time))\n return data_np\n\n def imload(self, filepath, kwds):\n return self._imload(filepath, kwds)\n\n def get_thumb(self, filepath):\n if not have_pil:\n raise Exception(\"Install PIL to use this method\")\n if not have_exif:\n raise Exception(\"Install piexif to use this method\")\n\n try:\n info = piexif.load(filepath)\n buf = info['thumbnail']\n\n except Exception as e:\n return None\n\n image = PILimage.open(BytesIO(buf))\n data_np = np.array(image)\n return data_np\n\n def piexif_getexif(self, filepath, kwds):\n if have_exif:\n try:\n info = piexif.load(filepath)\n if info is not None:\n # TODO: is there a more efficient way to do this than\n # iterating in python?\n for ifd in [\"0th\", \"Exif\", \"GPS\", \"Interop\", \"1st\"]:\n if ifd in info:\n for tag, value in info[ifd].items():\n kwd = piexif.TAGS[ifd][tag].get('name', tag)\n kwds[kwd] = value\n\n except Exception as e:\n self.logger.warning(\"Failed to get image metadata: %s\" % (str(e)))\n\n else:\n self.logger.warning(\"Please install 'piexif' module to get image metadata\")\n\n def get_buffer(self, data_np, header, format, output=None):\n \"\"\"Get image as a buffer in (format).\n Format should be 'jpeg', 'png', etc.\n \"\"\"\n if not have_pil:\n raise Exception(\"Install PIL to use this method\")\n image = PILimage.fromarray(data_np)\n buf = output\n if buf is None:\n buf = BytesIO()\n image.save(buf, format)\n return buf\n\n def imresize(self, data, new_wd, new_ht, method='bilinear'):\n \"\"\"Scale an image in numpy array _data_ to the specified width and\n height. A smooth scaling is preferred.\n \"\"\"\n old_ht, old_wd = data.shape[:2]\n start_time = time.time()\n\n if have_pilutil:\n means = 'PIL'\n zoom_x = float(new_wd) / float(old_wd)\n zoom_y = float(new_ht) / float(old_ht)\n if (old_wd >= new_wd) or (old_ht >= new_ht):\n # data size is bigger, skip pixels\n zoom = max(zoom_x, zoom_y)\n else:\n zoom = min(zoom_x, zoom_y)\n\n newdata = imresize(data, zoom, interp=method)\n\n else:\n raise ImageError(\"No way to scale image smoothly\")\n\n end_time = time.time()\n self.logger.debug(\"scaling (%s) time %.4f sec\" % (\n means, end_time - start_time))\n\n return newdata\n\n\n# UTILITY FUNCTIONS\n\ndef open_ppm(filepath):\n infile = open(filepath, 'rb')\n # Get type: PPM or PGM\n header = infile.readline()\n ptype = header.strip().upper()\n if ptype == b'P5':\n depth = 1\n elif ptype == b'P6':\n depth = 3\n #print header\n\n # Get image dimensions\n header = infile.readline().strip()\n while header.startswith(b'#') or len(header) == 0:\n header = infile.readline().strip()\n\n #print(header)\n width, height = [int(x) for x in header.split()]\n header = infile.readline()\n\n # Get unit size\n maxval = int(header)\n if maxval <= 255:\n dtype = np.uint8\n elif maxval <= 65535:\n dtype = np.uint16\n #print width, height, maxval\n\n # read image\n if depth > 1:\n arr = np.fromfile(infile, dtype=dtype).reshape((height, width, depth))\n else:\n arr = np.fromfile(infile, dtype=dtype).reshape((height, width))\n\n if sys.byteorder == 'little':\n arr = arr.byteswap()\n return arr\n\n\ndef get_rgbloader(kind=None, logger=None):\n return RGBFileHandler(logger)\n\n# END\n"
] | [
[
"numpy.array",
"scipy.misc.imsave",
"scipy.misc.imresize",
"numpy.fromfile"
]
] |
mherbert93/DS-Unit-3-Sprint-2-SQL-and-Databases | [
"c322a132ca53ab7fad04da3bd8b3c7f982d8ce65"
] | [
"module2-sql-for-analysis/insert_titanic.py"
] | [
"import psycopg2\nimport sqlite3\nimport os\nfrom dotenv import load_dotenv\nimport pandas as pd\nfrom sqlalchemy import create_engine\n\nload_dotenv()\n\nDB_NAME = os.getenv(\"DB_NAME\")\nDB_USER = os.getenv(\"DB_USER\")\nDB_PW = os.getenv(\"DB_PW\")\nDB_HOST = os.getenv(\"DB_HOST\")\nDB_URL = os.getenv(\"DB_URL\")\n\ndf = pd.read_csv('titanic.csv')\n\nalchemyEngine = create_engine(DB_URL)\n\npostgreSQLConnection = alchemyEngine.connect()\ndf.to_sql('titanic_test', postgreSQLConnection, if_exists='fail')\n\npostgreSQLConnection.close()\n\npg_conn = psycopg2.connect(\n dbname=DB_NAME, user=DB_USER,\n password=DB_PW, host=DB_HOST\n )\npg_curs = pg_conn.cursor()\n\nquery = \"\"\"SELECT \n\tSUM(CASE when \"Survived\" = 0 THEN 1 else 0 END) as dead,\n\tSUM(CASE when \"Survived\" = 1 THEN 1 else 0 END) as alive\nFROM \n\ttitanic_test\"\"\"\n\npg_curs.execute(query)\nresult = pg_curs.fetchall()\n\nprint(\"Passengers dead: \", result[0][0])\nprint(\"Passengers survived: \", result[0][1])\n\npg_curs.close()\npg_conn.close()"
] | [
[
"pandas.read_csv"
]
] |
bos-lab/piret | [
"23ecdf80331d72612bb2f48ab3207117673c373d"
] | [
"piret/maps/star.py"
] | [
"#! /usr/bin/env python\n\n\"\"\"Luigi Tasks to perform various RNA seq functions, from Mapping to Counting.\n\nMapping is done using hisat2 and counting is done using featurecounts\nand stringtie\n\"\"\"\n\nimport os\nimport luigi\nimport sys\ndir_path = os.path.dirname(os.path.realpath(__file__))\nlib_path = os.path.abspath(os.path.join(dir_path, '..'))\nsys.path.append(lib_path)\nfrom luigi.contrib.external_program import ExternalProgramTask\nfrom luigi import ExternalTask\nfrom luigi import LocalTarget\nfrom luigi import Parameter, IntParameter, DictParameter, ListParameter\nfrom luigi.util import inherits, requires\nimport subprocess\nfrom plumbum.cmd import hisat2\nfrom plumbum.cmd import samtools, stringtie, mv, awk\nfrom plumbum.cmd import STAR\nimport pandas as pd\nfrom sys import stderr, exit\nimport logging\nfrom collections import defaultdict as dd, Counter\nfrom piret.miscs import RefFile\n\n\n\n\nclass STARindex(luigi.Task):\n \"\"\" Creates STAR index.\"\"\"\n fasta = Parameter()\n num_cpus = IntParameter()\n gff_file = Parameter()\n stardb_dir= Parameter()\n kingdom = Parameter()\n\n def requires(self):\n if self.kingdom == \"both\":\n return[RefFile(self.fasta.split(\",\")[1])]\n else:\n return[RefFile(self.fasta)]\n\n def output(self):\n \"\"\"Expected index output\"\"\"\n return LocalTarget(os.path.join(self.stardb_dir, \"chrName.txt\"))\n \n def run(self):\n if os.path.exists(self.stardb_dir) is False:\n os.makedirs(self.stardb_dir)\n if self.kingdom == \"eukarya\":\n ind_opt = [\"--runMode\", \"genomeGenerate\",\n \"--runThreadN\", self.num_cpus,\n \"--genomeDir\", self.stardb_dir,\n \"--genomeFastaFiles\", self.fasta,\n \"--sjdbGTFfile\", self.gff_file]\n elif self.kingdom == \"prokarya\":\n ind_opt = [\"--runMode\", \"genomeGenerate\",\n \"--runThreadN\", self.num_cpus,\n \"--genomeDir\", self.stardb_dir,\n \"--genomeFastaFiles\", self.fasta]\n elif self.kingdom == \"both\":\n ind_opt = [\"--runMode\", \"genomeGenerate\",\n \"--runThreadN\", self.num_cpus,\n \"--genomeDir\", self.stardb_dir,\n \"--sjdbGTFfile\", self.gff_file,\n \"--genomeFastaFiles\", self.fasta.split(\",\")[0],\n self.fasta.split(\",\")[1]]\n\n star_cmd = STAR[ind_opt]\n logger = logging.getLogger('luigi-interface')\n logger.info(star_cmd)\n star_cmd()\n\n\nclass map_star(luigi.Task):\n \"\"\"Mapping the QCed sequences to reference using star aligner.\"\"\"\n fastqs = ListParameter()\n stardb_dir = Parameter()\n map_dir = Parameter()\n sample = Parameter()\n num_cpus = IntParameter()\n align_intron_min = luigi.IntParameter()\n align_intron_max = luigi.IntParameter()\n\n # def requires(self):\n # \"\"\"See if input file exist.\"\"\"\n # return [luigi.LocalTarget(self.fastqs[0]),\n # luigi.LocalTarget(self.fastqs[1])]\n\n def output(self):\n \"\"\"SAM file output of the mapping.\"\"\"\n bam_file = os.path.join(self.map_dir, self.sample) + \"_srt.bam\"\n return luigi.LocalTarget(bam_file)\n\n def run(self):\n \"\"\"Run star\"\"\"\n if os.path.exists(self.map_dir) is False:\n os.makedirs(self.map_dir)\n star_option = [\"--genomeDir\", self.stardb_dir,\n \"--runThreadN\", self.num_cpus,\n \"--outFileNamePrefix\", os.path.join(self.map_dir, self.sample + \"_\"),\n \"--outSAMtype\", \"BAM\", \"SortedByCoordinate\",\n \"--alignIntronMax\", self.align_intron_max,\n \"alignIntronMin\", self.align_intron_min,\n \"--readFilesIn\", self.fastqs[0], self.fastqs[1]]\n star_cmd = STAR[star_option]\n star_cmd()\n bam_file = os.path.join(self.map_dir, self.sample) + \"_Aligned.sortedByCoord.out.bam\"\n mv_list = [bam_file, os.path.join(self.map_dir, self.sample) + \"_srt.bam\"]\n mv_cmd = mv[mv_list]\n mv_cmd()\n\n\nclass map_starW(luigi.WrapperTask):\n \"\"\"A wrapper task for mapping using star.\"\"\"\n\n fastq_dic = luigi.DictParameter()\n stardb_dir = luigi.Parameter()\n workdir = luigi.Parameter()\n num_cpus = luigi.IntParameter()\n\n def requires(self):\n \"\"\"A wrapper task for mapping using STAR.\"\"\"\n for samp, fastq in self.fastq_dic.items():\n trim_dir = os.path.join(self.workdir, \"processes\", \"qc\", samp)\n map_dir = os.path.join(self.workdir, \"processes\", \"mapping\", samp)\n if os.path.isdir(map_dir) is False:\n os.makedirs(map_dir)\n yield map_star(fastqs=[trim_dir + \"/\" + samp + \".1.trimmed.fastq\",\n trim_dir + \"/\" + samp + \".2.trimmed.fastq\"],\n stardb_dir=self.stardb_dir, map_dir=map_dir,\n sample=samp, num_cpus=self.num_cpus)\n\n@requires(map_starW)\nclass SummarizeStarMap(luigi.Task):\n \"\"\"Summarizes mapping results of all samples into a table\"\"\"\n\n def output(self):\n \"\"\"Mapping Summary Output.\"\"\"\n out_file = self.workdir + \"/\" + \"MapSummary.csv\"\n return luigi.LocalTarget(out_file)\n\n def run(self):\n \"\"\"Parse the mapping stats.\"\"\"\n summ_dic = {}\n for samp, fastq in self.fastq_dic.items():\n map_dir = os.path.join(self.workdir, \"processes\", \"mapping\", samp)\n filename = map_dir + \"/\" + samp + \"_Log.final.out\"\n with open(filename, 'r') as file:\n lines = file.readlines()\n total_reads = lines[5].split(\"|\")[1].strip()\n unq_map_reads = lines[8].split(\"|\")[1].strip()\n multi_map_reads = lines[23].split(\"|\")[1].strip()\n multiX_map_reads = lines[25].split(\"|\")[1].strip()\n summ_dic[samp] = [total_reads,\n unq_map_reads,\n multi_map_reads,\n multiX_map_reads]\n summ_table = pd.DataFrame.from_dict(summ_dic, orient='index')\n summ_table.columns = [\"Paired reads\", \"Uniquely mapped reads\",\n \"mapped to multiple loci\", \"mapped to too many loci\"]\n out_file = self.workdir + \"/\" + \"MapSummary.csv\"\n summ_table.to_csv(out_file)\n"
] | [
[
"pandas.DataFrame.from_dict"
]
] |
simonydbutt/b2a | [
"0bf4a6de8547d73ace22967780442deeaff2d5c6"
] | [
"Backtest/main/Simul/TestStrat.py"
] | [
"from Backtest.main.Exit.Exit import Exit\nfrom Backtest.main.Utils.TimeUtil import TimeUtil\nfrom Backtest.main.Visual.StratVisual import StratVisual\nfrom Backtest.main.Utils.AssetBrackets import AssetBrackets\nfrom Backtest.main.Entrance.Enter import Enter\nimport numpy as np\n\n\nclass TestStrat:\n def __init__(self, Entrance, exitStrat, isVisual=False, verbose=False):\n self.E = Entrance\n self.positionDict = Exit(self.E, exitStrat).run()\n print(self.positionDict)\n self.assetList = self.E.assetList\n self.dfDict = self.E.dfDict\n self.ts2Bin = TimeUtil().ts2Bin\n self.isVisual = isVisual\n self.verbose = verbose\n\n def run(self):\n resultsDict = {\n asset: {\"results\": [], \"numPeriods\": []}\n for asset in self.assetList + [\"Total\"]\n }\n resultsDict[\"Total\"][\"dfSize\"] = 0\n for asset in self.assetList:\n df = self.dfDict[asset]\n gran = int(df[\"TS\"].iloc[1] - df[\"TS\"].iloc[0])\n positionList = self.positionDict[asset]\n n = 0\n for position in positionList:\n if position[1] < len(df):\n result = (\n df.iloc[position[1]][\"close\"] / df.iloc[position[0]][\"close\"]\n - 1\n ) * 100\n resultsDict[asset][\"results\"].append(result)\n resultsDict[asset][\"numPeriods\"].append(position[1] - position[0])\n resultsDict[\"Total\"][\"results\"].append(result)\n resultsDict[\"Total\"][\"numPeriods\"].append(position[1] - position[0])\n resultsDict[asset][\"gran\"] = gran\n resultsDict[asset][\"dfSize\"] = len(df)\n resultsDict[\"Total\"][\"dfSize\"] += len(df)\n resultsDict[\"Total\"][\"gran\"] = gran\n self.printStats(resultsDict)\n\n def printStats(self, resultsDict):\n printList = resultsDict.keys() if self.verbose else [\"Total\"]\n for asset in printList:\n noEntries = len(resultsDict[asset][\"results\"])\n print(\"_________________________________\")\n print(\"---------------------------------\")\n print(\n \"Asset\\t\\t |\\t%s\\n\"\n \"Granularity\\t |\\t%s\\n\"\n \"No. Entries\\t |\\t%s\\n\"\n \"Availability |\\t%.2f%%\\n\"\n \"---------------------------------\"\n % (\n asset,\n self.ts2Bin[str(resultsDict[asset][\"gran\"])],\n noEntries,\n 100 * (noEntries / resultsDict[asset][\"dfSize\"]),\n )\n )\n results = resultsDict[asset][\"results\"]\n periods = resultsDict[asset][\"numPeriods\"]\n if len(results) > 0:\n print(\n \"Avg PnL\\t\\t |\\t%.4f%%\\n\"\n \"Max Profit\\t |\\t%.4f%%\\n\"\n \"Max Loss\\t |\\t%.4f%%\\n\"\n \"Sharpe Ratio |\\t%.2f\\n\"\n \"Win/Loss\\t |\\t%.f%%\\n\"\n % (\n float(np.nanmean(results)),\n float(np.nanmax(results)),\n float(np.nanmin(results)),\n float(np.nanmean(results) / np.nanstd(results))\n if len(results) != 1\n else np.NaN,\n len([_ for _ in results if _ > 0]) * 100 / len(results),\n )\n )\n print(\"---------------------------------\")\n print(\n \"Mean Periods |\\t%.2f\\n\"\n \"Med. Periods |\\t%s\\n\"\n \"Max Periods\\t |\\t%s\\n\"\n \"Min Periods\\t |\\t%s\\n\"\n % (\n float(np.nanmean(periods)),\n float(np.median(periods)),\n float(np.nanmax(periods)),\n float(np.nanmin(periods)),\n )\n )\n print(\"---------------------------------\")\n print(\"_________________________________\")\n if self.isVisual:\n S = StratVisual(resultsDict=resultsDict)\n S.periodReturns()\n\n\nA = AssetBrackets(exchangeName=\"binance\").getBrackets(base=\"BTC\")\n\n\nprint(\"Number assets: %s\" % len(A[\"small\"]))\nE = Enter(\n \"binance\",\n A[\"small\"],\n \"6h\",\n stratDict={\n \"IsFeasible\": {\n \"periodsVolLong\": 50,\n \"periodsVolShort\": 5,\n \"numPeriodsMA\": 50,\n \"volCoef\": 1.3,\n \"numStd\": 1.6,\n }\n },\n)\nTestStrat(\n E,\n (\n \"StdExit\",\n {\n \"numPeriods\": 50,\n \"closeAt\": 50,\n \"stdDict\": {\"up\": 0.25, \"down\": 2},\n \"maxRun\": True,\n },\n ),\n isVisual=True,\n).run()\n"
] | [
[
"numpy.nanmax",
"numpy.nanmean",
"numpy.nanstd",
"numpy.median",
"numpy.nanmin"
]
] |
vishalbelsare/GEM | [
"ea1cb5f9f28c0d2f49646442ccfd2b6ea7b6cab8"
] | [
"gem/evaluation/evaluate_link_prediction.py"
] | [
"try: import cPickle as pickle\nexcept: import pickle\nfrom gem.evaluation import metrics\nfrom gem.utils import evaluation_util, graph_util\nimport numpy as np\nimport networkx as nx\n\nimport sys\nsys.path.insert(0, './')\nfrom gem.utils import embed_util\n\n\ndef evaluateStaticLinkPrediction(digraph, graph_embedding,\n train_ratio=0.8,\n n_sample_nodes=None,\n sample_ratio_e=None,\n no_python=False,\n is_undirected=True):\n node_num = len(digraph.nodes)\n # seperate train and test graph\n train_digraph, test_digraph = evaluation_util.splitDiGraphToTrainTest(\n digraph,\n train_ratio=train_ratio,\n is_undirected=is_undirected\n )\n if not nx.is_connected(train_digraph.to_undirected()):\n train_digraph = max(\n nx.weakly_connected_component_subgraphs(train_digraph),\n key=len\n )\n tdl_nodes = list(train_digraph.nodes())\n nodeListMap = dict(zip(tdl_nodes, range(len(tdl_nodes))))\n nx.relabel_nodes(train_digraph, nodeListMap, copy=False)\n test_digraph = test_digraph.subgraph(tdl_nodes)\n nx.relabel_nodes(test_digraph, nodeListMap, copy=False)\n\n # learning graph embedding\n X, _ = graph_embedding.learn_embedding(\n graph=train_digraph,\n no_python=no_python\n )\n node_l = None\n if n_sample_nodes:\n test_digraph, node_l = graph_util.sample_graph(\n test_digraph,\n n_sample_nodes\n )\n X = X[node_l]\n\n # evaluation\n if sample_ratio_e:\n eval_edge_pairs = evaluation_util.getRandomEdgePairs(\n node_num,\n sample_ratio_e,\n is_undirected\n )\n else:\n eval_edge_pairs = None\n estimated_adj = graph_embedding.get_reconstructed_adj(X, node_l)\n predicted_edge_list = evaluation_util.getEdgeListFromAdjMtx(\n estimated_adj,\n is_undirected=is_undirected,\n edge_pairs=eval_edge_pairs\n )\n if node_l is None:\n node_l = list(range(len(train_digraph.nodes)))\n filtered_edge_list = [e for e in predicted_edge_list if not train_digraph.has_edge(node_l[e[0]], node_l[e[1]])]\n\n MAP = metrics.computeMAP(filtered_edge_list, test_digraph)\n prec_curv, _ = metrics.computePrecisionCurve(\n filtered_edge_list,\n test_digraph\n )\n return (MAP, prec_curv)\n\n\ndef expLP(digraph, graph_embedding,\n n_sample_nodes, rounds,\n res_pre, m_summ, train_ratio=0.8,\n no_python=False, is_undirected=True):\n print('\\tLink Prediction')\n summ_file = open('%s_%s.lpsumm' % (res_pre, m_summ), 'w')\n summ_file.write('Method\\t%s\\n' % metrics.getMetricsHeader())\n MAP = [None] * rounds\n prec_curv = [None] * rounds\n for round_id in range(rounds):\n MAP[round_id], prec_curv[round_id] = \\\n evaluateStaticLinkPrediction(digraph, graph_embedding,\n train_ratio=train_ratio,\n n_sample_nodes=1024,\n no_python=no_python,\n is_undirected=is_undirected)\n summ_file.write('\\t%f/%f\\t%s\\n' % (\n np.mean(MAP),\n np.std(MAP),\n metrics.getPrecisionReport(\n prec_curv[0],\n len(prec_curv[0])\n )\n ))\n summ_file.close()\n pickle.dump([MAP, prec_curv],\n open('%s_%s.lp' % (res_pre, m_summ),\n 'wb'))\n"
] | [
[
"numpy.std",
"numpy.mean"
]
] |
Huxx0804/gibbon_lib | [
"b1f4e565f336f6ce7399f6e5e8e10392d5712dea"
] | [
"gibbon/fem/_score_point.py"
] | [
"import uuid\nimport numpy as np\nfrom shapely.geometry import Point, LineString\nfrom ._finite_cell import FiniteCell\n\n\nclass ScorePoint:\n def __init__(\n self,\n coords: list,\n value: float = 1,\n influence_range: float = 2000\n ):\n self.uuid = str(uuid.uuid4())\n self.value = value\n\n self._coords = np.array(coords)\n self._influence_range = influence_range\n self.setup()\n\n @property\n def type(self):\n return self.__class__.__name__\n\n @property\n def coords(self):\n return self._coords.tolist()\n\n @property\n def influence_range(self):\n return self._influence_range\n\n def set_coords(self, coords):\n self._coords = np.array(coords)\n self.setup()\n\n def set_influence_range(self, influence_range):\n self._influence_range = influence_range\n self.setup()\n\n def setup(self):\n self.geo = Point(self._coords)\n self.buffer = self.geo.buffer(self._influence_range)\n\n def compute(self, obj: FiniteCell) -> float:\n if self.buffer.intersects(obj.geo_center):\n obj._scores[self.type] += self.value \n\n\nclass Road(ScorePoint):\n def __init__(self, geometry, value, influence_range):\n ScorePoint.__init__(self, geometry, value, influence_range)\n\n def setup(self):\n self.geo = LineString(self._coords)\n self.buffer = self.geo.buffer(self._influence_range)\n\n def compute(self, obj: FiniteCell) -> float:\n if self.buffer.intersects(obj.geo_center):\n if self.value > obj._scores[self.type][0]:\n obj._scores[self.type] = [self.value] \n\n\nclass Intersection(ScorePoint):\n def __init__(self, geometry, value, influence_range):\n ScorePoint.__init__(self, geometry, value, influence_range)\n\n def compute(self, obj: FiniteCell) -> float:\n if self.buffer.intersects(obj.geo_center):\n obj._forbidden[self.type].append(self.value)\n\n\nclass BusStop(ScorePoint):\n def __init__(self, geometry, value, influence_range):\n ScorePoint.__init__(self, geometry, value, influence_range)\n\n\nclass Metro(ScorePoint):\n def __init__(self, geometry, value, influence_range):\n ScorePoint.__init__(self, geometry, value, influence_range)\n\n\nclass UnderGround(ScorePoint):\n def __init__(self, geometry, value, influence_range):\n ScorePoint.__init__(self, geometry, value, influence_range)\n\n\nclass Pavement(ScorePoint):\n def __init__(self, geometry, value, influence_range):\n ScorePoint.__init__(self, geometry, value, influence_range)\n"
] | [
[
"numpy.array"
]
] |
jordanmkoncz/openpilot | [
"7502daf28ff6f217de67f5bc1139eac79a4fa6a6"
] | [
"selfdrive/controls/lib/driver_monitor.py"
] | [
"import numpy as np\nfrom common.realtime import DT_CTRL, DT_DMON\nfrom selfdrive.controls.lib.drive_helpers import create_event, EventTypes as ET\nfrom common.filter_simple import FirstOrderFilter\nfrom common.stat_live import RunningStatFilter\n\n_AWARENESS_TIME = 100. # 1.6 minutes limit without user touching steering wheels make the car enter a terminal status\n_AWARENESS_PRE_TIME_TILL_TERMINAL = 25. # a first alert is issued 25s before expiration\n_AWARENESS_PROMPT_TIME_TILL_TERMINAL = 15. # a second alert is issued 15s before start decelerating the car\n_DISTRACTED_TIME = 11.\n_DISTRACTED_PRE_TIME_TILL_TERMINAL = 8.\n_DISTRACTED_PROMPT_TIME_TILL_TERMINAL = 6.\n\n_FACE_THRESHOLD = 0.4\n_EYE_THRESHOLD = 0.4\n_BLINK_THRESHOLD = 0.2 # 0.225\n_PITCH_WEIGHT = 1.35 # 1.5 # pitch matters a lot more\n_METRIC_THRESHOLD = 0.4\n_PITCH_POS_ALLOWANCE = 0.04 # 0.08 # rad, to not be too sensitive on positive pitch\n_PITCH_NATURAL_OFFSET = 0.12 # 0.1 # people don't seem to look straight when they drive relaxed, rather a bit up\n_YAW_NATURAL_OFFSET = 0.08 # people don't seem to look straight when they drive relaxed, rather a bit to the right (center of car)\n\n_DISTRACTED_FILTER_TS = 0.25 # 0.6Hz\n\n_POSE_CALIB_MIN_SPEED = 13 # 30 mph\n_POSE_OFFSET_MIN_COUNT = 600 # valid data counts before calibration completes, 1 seg is 600 counts\n_POSE_OFFSET_MAX_COUNT = 3600 # stop deweighting new data after 6 min, aka \"short term memory\"\n\n_RECOVERY_FACTOR_MAX = 5. # relative to minus step change\n_RECOVERY_FACTOR_MIN = 1.25 # relative to minus step change\n\nMAX_TERMINAL_ALERTS = 3 # not allowed to engage after 3 terminal alerts\n\n# model output refers to center of cropped image, so need to apply the x displacement offset\nRESIZED_FOCAL = 320.0\nH, W, FULL_W = 320, 160, 426\n\nclass DistractedType(object):\n NOT_DISTRACTED = 0\n BAD_POSE = 1\n BAD_BLINK = 2\n\ndef head_orientation_from_descriptor(angles_desc, pos_desc, rpy_calib):\n # the output of these angles are in device frame\n # so from driver's perspective, pitch is up and yaw is right\n\n pitch_prnet = angles_desc[0]\n yaw_prnet = angles_desc[1]\n roll_prnet = angles_desc[2]\n\n face_pixel_position = ((pos_desc[0] + .5)*W - W + FULL_W, (pos_desc[1]+.5)*H)\n yaw_focal_angle = np.arctan2(face_pixel_position[0] - FULL_W/2, RESIZED_FOCAL)\n pitch_focal_angle = np.arctan2(face_pixel_position[1] - H/2, RESIZED_FOCAL)\n\n roll = roll_prnet\n pitch = pitch_prnet + pitch_focal_angle\n yaw = -yaw_prnet + yaw_focal_angle\n\n # no calib for roll\n pitch -= rpy_calib[1]\n yaw -= rpy_calib[2]\n return np.array([roll, pitch, yaw])\n\nclass DriverPose():\n def __init__(self):\n self.yaw = 0.\n self.pitch = 0.\n self.roll = 0.\n self.pitch_offseter = RunningStatFilter(max_trackable=_POSE_OFFSET_MAX_COUNT)\n self.yaw_offseter = RunningStatFilter(max_trackable=_POSE_OFFSET_MAX_COUNT)\n\nclass DriverBlink():\n def __init__(self):\n self.left_blink = 0.\n self.right_blink = 0.\n\nclass DriverStatus():\n def __init__(self):\n self.pose = DriverPose()\n self.pose_calibrated = self.pose.pitch_offseter.filtered_stat.n > _POSE_OFFSET_MIN_COUNT and \\\n self.pose.yaw_offseter.filtered_stat.n > _POSE_OFFSET_MIN_COUNT\n self.blink = DriverBlink()\n self.awareness = 1.\n self.awareness_active = 1.\n self.driver_distracted = False\n self.driver_distraction_filter = FirstOrderFilter(0., _DISTRACTED_FILTER_TS, DT_DMON)\n self.face_detected = False\n self.terminal_alert_cnt = 0\n self.step_change = 0.\n self.active_monitoring_mode = True\n self.threshold_prompt = _DISTRACTED_PROMPT_TIME_TILL_TERMINAL / _DISTRACTED_TIME\n\n self.is_rhd_region = False\n self.is_rhd_region_checked = False\n\n self._set_timers(active_monitoring=True)\n\n def _set_timers(self, active_monitoring):\n if self.active_monitoring_mode and self.awareness <= self.threshold_prompt:\n if active_monitoring:\n self.step_change = DT_CTRL / _DISTRACTED_TIME\n else:\n self.step_change = 0.\n return # no exploit after orange alert\n elif self.awareness <= 0.:\n return\n\n if active_monitoring:\n # when falling back from passive mode to active mode, reset awareness to avoid false alert\n if not self.active_monitoring_mode:\n self.awareness = self.awareness_active\n\n self.threshold_pre = _DISTRACTED_PRE_TIME_TILL_TERMINAL / _DISTRACTED_TIME\n self.threshold_prompt = _DISTRACTED_PROMPT_TIME_TILL_TERMINAL / _DISTRACTED_TIME\n self.step_change = DT_CTRL / _DISTRACTED_TIME\n self.active_monitoring_mode = True\n else:\n if self.active_monitoring_mode:\n self.awareness_active = self.awareness\n\n self.threshold_pre = _AWARENESS_PRE_TIME_TILL_TERMINAL / _AWARENESS_TIME\n self.threshold_prompt = _AWARENESS_PROMPT_TIME_TILL_TERMINAL / _AWARENESS_TIME\n self.step_change = DT_CTRL / _AWARENESS_TIME\n self.active_monitoring_mode = False\n\n def _is_driver_distracted(self, pose, blink):\n if not self.pose_calibrated:\n pitch_error = pose.pitch - _PITCH_NATURAL_OFFSET\n yaw_error = pose.yaw - _YAW_NATURAL_OFFSET\n # add positive pitch allowance\n if pitch_error > 0.:\n pitch_error = max(pitch_error - _PITCH_POS_ALLOWANCE, 0.)\n else:\n pitch_error = pose.pitch - self.pose.pitch_offseter.filtered_stat.mean()\n yaw_error = pose.yaw - self.pose.yaw_offseter.filtered_stat.mean()\n\n pitch_error *= _PITCH_WEIGHT\n pose_metric = np.sqrt(yaw_error**2 + pitch_error**2)\n\n if pose_metric > _METRIC_THRESHOLD:\n return DistractedType.BAD_POSE\n elif blink.left_blink>_BLINK_THRESHOLD and blink.right_blink>_BLINK_THRESHOLD:\n return DistractedType.BAD_BLINK\n else:\n return DistractedType.NOT_DISTRACTED\n\n def get_pose(self, driver_monitoring, cal_rpy, car_speed, op_engaged):\n # 10 Hz\n if len(driver_monitoring.faceOrientation) == 0 or len(driver_monitoring.facePosition) == 0:\n return\n\n self.pose.roll, self.pose.pitch, self.pose.yaw = head_orientation_from_descriptor(driver_monitoring.faceOrientation, driver_monitoring.facePosition, cal_rpy)\n self.blink.left_blink = driver_monitoring.leftBlinkProb * (driver_monitoring.leftEyeProb>_EYE_THRESHOLD)\n self.blink.right_blink = driver_monitoring.rightBlinkProb * (driver_monitoring.rightEyeProb>_EYE_THRESHOLD)\n self.face_detected = driver_monitoring.faceProb > _FACE_THRESHOLD and not self.is_rhd_region\n\n self.driver_distracted = self._is_driver_distracted(self.pose, self.blink)>0\n # first order filters\n self.driver_distraction_filter.update(self.driver_distracted)\n\n # update offseter\n # only update when driver is actively driving the car above a certain speed\n if self.face_detected and car_speed>_POSE_CALIB_MIN_SPEED and not op_engaged:\n self.pose.pitch_offseter.push_and_update(self.pose.pitch)\n self.pose.yaw_offseter.push_and_update(self.pose.yaw)\n\n self.pose_calibrated = self.pose.pitch_offseter.filtered_stat.n > _POSE_OFFSET_MIN_COUNT and \\\n self.pose.yaw_offseter.filtered_stat.n > _POSE_OFFSET_MIN_COUNT\n\n self._set_timers(self.face_detected)\n\n def update(self, events, driver_engaged, ctrl_active, standstill):\n if (driver_engaged and self.awareness > 0) or not ctrl_active:\n # reset only when on disengagement if red reached\n self.awareness = 1.\n self.awareness_active = 1.\n return events\n\n driver_attentive = self.driver_distraction_filter.x < 0.37\n awareness_prev = self.awareness\n\n if (driver_attentive and self.face_detected and self.awareness > 0):\n # only restore awareness when paying attention and alert is not red\n self.awareness = min(self.awareness + ((_RECOVERY_FACTOR_MAX-_RECOVERY_FACTOR_MIN)*(1.-self.awareness)+_RECOVERY_FACTOR_MIN)*self.step_change, 1.)\n # don't display alert banner when awareness is recovering and has cleared orange\n if self.awareness > self.threshold_prompt:\n return events\n\n # should always be counting if distracted unless at standstill and reaching orange\n if (not self.face_detected or (self.driver_distraction_filter.x > 0.63 and self.driver_distracted and self.face_detected)) and \\\n not (standstill and self.awareness - self.step_change <= self.threshold_prompt):\n self.awareness = max(self.awareness - self.step_change, -0.1)\n\n alert = None\n if self.awareness <= 0.:\n # terminal red alert: disengagement required\n alert = 'driverDistracted' if self.active_monitoring_mode else 'driverUnresponsive'\n if awareness_prev > 0.:\n self.terminal_alert_cnt += 1\n elif self.awareness <= self.threshold_prompt:\n # prompt orange alert\n alert = 'promptDriverDistracted' if self.active_monitoring_mode else 'promptDriverUnresponsive'\n elif self.awareness <= self.threshold_pre:\n # pre green alert\n alert = 'preDriverDistracted' if self.active_monitoring_mode else 'preDriverUnresponsive'\n\n if alert is not None:\n events.append(create_event(alert, [ET.WARNING]))\n\n return events\n"
] | [
[
"numpy.array",
"numpy.arctan2",
"numpy.sqrt"
]
] |
wutb15/pai | [
"649200b70fac69e9f33bdd10b50995761eeb8bbe"
] | [
"contrib/profiler/profiler.py"
] | [
"# Copyright (c) Microsoft Corporation\n# All rights reserved.\n#\n# MIT License\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,\n# and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above\n# copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\n# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\n\"\"\"\nThe profiler is used to profile the using information of the hardware while a deep learing model is running\n\"\"\"\nimport pynvml as nv\nimport numpy as np\nimport glob\nimport csv\nimport os\nimport time\nimport argparse\nfrom utils import Sample\nfrom utils import Adviser\nfrom utils import print_process\nfrom utils import SlideWindows\nfrom utils import GPU_INFO_OFFSET\nfrom utils import INFO_NUM_PER_GPU\nfrom utils import GPU_MEM_OFFSET\n\n\n# To get the CPU running time of system from being booted\ndef get_system_cpu_ticks():\n with open('/proc/stat', 'r') as f:\n for line in f.readlines():\n if line.startswith('cpu '):\n items = line.split()\n if len(items) < 8:\n return -1\n\n total_clock_ticks = 0\n for item in items[1:8]:\n total_clock_ticks += int(item)\n return total_clock_ticks\n return -1\n\n\n# To get the CPU running time of container from being booted\ndef get_container_cpu_ticks(file_name):\n user_time = 0\n system_time = 0\n with open(file_name, 'r') as f:\n for line in f:\n items = line.split()\n if len(items) != 2:\n return -1\n if items[0] == 'user':\n user_time = int(items[1])\n elif items[1] == 'system':\n system_time = int(items[1])\n return user_time + system_time\n\n\ndef get_cpu_ticks(file_name):\n sys_ticks = get_system_cpu_ticks()\n container_ticks = get_container_cpu_ticks(file_name)\n return [sys_ticks, container_ticks]\n\n\ndef get_gpu_utilization(gpu_idx):\n try:\n handle = nv.nvmlDeviceGetHandleByIndex(gpu_idx)\n util = nv.nvmlDeviceGetUtilizationRates(handle)\n except nv.NVMLError as err:\n util = err\n return util\n\n\ndef get_gpu_memory(gpu_idx):\n try:\n handle = nv.nvmlDeviceGetHandleByIndex(gpu_idx)\n mem = nv.nvmlDeviceGetMemoryInfo(handle)\n except nv.NVMLError as err:\n mem = err\n return mem\n\n\ndef get_memory_percent(file_name):\n total_memory_path = '/proc/meminfo'\n\n memory_docker_used = 0.0\n total_memory = 1.0\n with open(file_name, 'r') as f:\n for line in f:\n memory_docker_used = int(line)\n\n with open(total_memory_path, 'r') as f:\n for line in f:\n if line.startswith('MemTotal'):\n lines = line.split()\n total_memory = int(lines[1]) * 1024\n break\n return [memory_docker_used, total_memory]\n\n\ndef get_disk_read_bytes(file_name):\n read_bytes = 0\n with open(file_name, 'r') as f:\n for line in f:\n items = line.split()\n if len(items) != 3 or len(items) != 2:\n return -1\n if items[1] == 'Read':\n read_bytes += int(items[1])\n return read_bytes\n\n\ndef get_disk_write_bytes(file_name):\n write_bytes = 0\n with open(file_name, 'r') as f:\n for line in f:\n items = line.split()\n if len(items) != 3 or len(items) != 2:\n return -1\n if items[1] == 'Write':\n write_bytes += int(items[1])\n return write_bytes\n\n\ndef get_network_bytes(file_name):\n receive_bytes, transmit_bytes = 0, 0\n with open(file_name, 'r') as f:\n for line in f:\n if len(line.split()) != 17:\n continue\n else:\n items = line.split()\n receive_bytes += int(items[1])\n transmit_bytes += int(items[9])\n return [receive_bytes, transmit_bytes]\n\n\ndef get_sample_data(cpu_file, mem_file, blk_file, net_file, gpu_id, period):\n [mem_used, mem_total] = get_memory_percent(mem_file)\n\n # 1st info about I/O, network and CPU\n read_bytes1 = get_disk_read_bytes(blk_file)\n write_bytes1 = get_disk_write_bytes(blk_file)\n [network_receive1, network_transmit1] = get_network_bytes(net_file)\n [sys_ticks1, container_ticks1] = get_cpu_ticks(cpu_file)\n time.sleep(period)\n # 2nd info about I/O, network and CPU, calculate how many bytes used in this period\n read_bytes2 = get_disk_read_bytes(blk_file)\n write_bytes2 = get_disk_write_bytes(blk_file)\n [network_receive2, network_transmit2] = get_network_bytes(net_file)\n [sys_ticks2, container_ticks2] = get_cpu_ticks(cpu_file)\n\n online_cpus = os.sysconf(os.sysconf_names['SC_NPROCESSORS_ONLN'])\n cpu_usage = (container_ticks2 - container_ticks1) * 1.0 / (sys_ticks2 - sys_ticks1) * online_cpus * 100\n\n # get the usage of the GPU to analyze\n gpu_usage = list()\n gpu_mem = list()\n gpu_mem_used = list()\n gpu_mem_total = list()\n for gid in gpu_id:\n gpu_usage.append(get_gpu_utilization(gid).gpu)\n gpu_mem.append(get_gpu_utilization(gid).memory)\n gpu_mem_used.append(get_gpu_memory(gid).used)\n gpu_mem_total.append(get_gpu_memory(gid).total)\n sample_data = Sample(cpu_usage, mem_used, mem_total, read_bytes2 - read_bytes1, write_bytes2 - write_bytes1,\n network_receive2 - network_receive1, network_transmit2 - network_transmit1, gpu_usage, gpu_mem,\n gpu_mem_used, gpu_mem_total)\n return sample_data\n\n\n# The analyze function. It will be modified when the analyzing module is finished.\ndef analyze_samples(sample_list, adviser):\n # sample_list is a 2-D array with m rows and 7 + (num_GPU * 4) cols\n # The number of rows is decided by the sampling time.\n # The number of cols is decided by the number of GPU that used.\n sample_list = np.array(sample_list, dtype=np.float)\n used_gpu_num = (sample_list.shape[1] - GPU_INFO_OFFSET) / INFO_NUM_PER_GPU\n cpu_usage = sample_list[:, 0]\n mem_usage = sample_list[:, 1] / sample_list[:, 2]\n gpu_usage = list()\n gpu_mem_usage = list()\n for i in range(int(used_gpu_num)):\n gpu_usage.append(sample_list[:, GPU_INFO_OFFSET + i * INFO_NUM_PER_GPU])\n gpu_mem_usage.append(\n sample_list[:, GPU_INFO_OFFSET + GPU_MEM_OFFSET + i * INFO_NUM_PER_GPU]\n / sample_list[:, GPU_INFO_OFFSET + GPU_MEM_OFFSET + 1 + i * INFO_NUM_PER_GPU]\n )\n\n if used_gpu_num >= 2:\n # multiple GPUs, analyze whether each GPU has the same memory usage\n gpu_mem_avg_0 = np.average(gpu_mem_usage[0])\n gpu_mem_avg_1 = np.average(gpu_mem_usage[1])\n if abs(gpu_mem_avg_0 - gpu_mem_avg_1) > 0.15:\n adviser.add_times(index=1)\n\n if np.average(gpu_usage[0]) >= 90:\n adviser.add_times(index=0)\n else:\n if np.average(gpu_mem_usage[0]) < 0.80:\n adviser.add_times(index=2)\n else:\n adviser.add_times(index=3)\n # slide the cpu and get the value to divide the cpu value\n slide_windows = SlideWindows(10)\n cpu_slide = list()\n for i in range(cpu_usage.shape[0]):\n cpu_slide.append(slide_windows.get_data(cpu_usage[i]))\n cpu_slide_copy = cpu_slide.copy()\n cpu_slide_copy.sort()\n cpu_std_max = cpu_slide_copy[int(len(cpu_slide_copy) * 0.8)]\n cpu_std_min = cpu_slide_copy[int(len(cpu_slide_copy) * 0.2)]\n\n gpu_usage_up_down = [0]\n for i in range(1, len(gpu_usage[0])):\n if gpu_usage[0][i] > gpu_usage[0][i - 1]:\n gpu_usage_up_down.append(1)\n elif gpu_usage[0][i] < gpu_usage[0][i - 1]:\n gpu_usage_up_down.append(-1)\n else:\n gpu_usage_up_down.append(0)\n gpu_usage_up_down[0] = gpu_usage_up_down[1]\n\n # Solution 1\n gpu_up_interval = list()\n gpu_down_interval = list()\n up_flag = True\n down_flag = True\n for i in range(len(gpu_usage_up_down)):\n if gpu_usage_up_down[i] == 1 and up_flag:\n up_flag = False\n elif i >= 1 and gpu_usage_up_down[i] == -1 and not up_flag:\n up_flag = True\n\n if gpu_usage_up_down[i] == -1 and down_flag:\n down_flag = False\n elif i >= 1 and gpu_usage_up_down[i] == 1 and not down_flag:\n down_flag = True\n if not up_flag:\n gpu_up_interval.append(i)\n elif not down_flag:\n gpu_down_interval.append(i)\n up_cpu_min, down_cpu_min = 0, 0\n up_cpu_max, down_cpu_max = 0, 0\n for i in range(1, len(cpu_slide) - 1):\n if cpu_slide[i] < cpu_slide[i - 1] and cpu_slide[i] < cpu_slide[i + 1] and cpu_slide[i] < cpu_std_min:\n if i in gpu_up_interval:\n up_cpu_min += 1\n elif i in gpu_down_interval:\n down_cpu_min += 1\n if cpu_slide[i] > cpu_slide[i - 1] and cpu_slide[i] > cpu_slide[i + 1] and cpu_slide[i] > cpu_std_max:\n if i in gpu_up_interval:\n up_cpu_max += 1\n elif i in gpu_down_interval:\n down_cpu_max += 1\n if up_cpu_min + down_cpu_min != 0 and up_cpu_max + down_cpu_max != 0:\n if float(down_cpu_min / (up_cpu_min + down_cpu_min)) > 0.6 or float(\n up_cpu_max / (up_cpu_max + down_cpu_max)) > 0.6:\n adviser.add_times(index=4)\n adviser.add_total()\n\n\ndef start_sample(container_id, period, analyze_period, duration, output_dir, gpu_id, container_pid):\n start_time = time.time()\n if not os.path.exists('./' + output_dir):\n os.mkdir(output_dir)\n realtime_log = csv.writer(open('./' + output_dir + '/log_result.csv', 'w')) # , newline=''))\n\n str_write_realtime = ['cpu_usage', 'mem_used', 'mem_total', 'IO_read', 'IO_write', 'network_receive',\n 'network_transmit']\n for i in range(len(gpu_id)):\n str_write_realtime.append('gpu_usage_' + str(gpu_id[i]))\n str_write_realtime.append('gpu_mem_usage_' + str(gpu_id[i]))\n str_write_realtime.append('gpu_mem_used_' + str(gpu_id[i]))\n str_write_realtime.append('gpu_mem_total_' + str(gpu_id[i]))\n realtime_log.writerow(str_write_realtime)\n\n nv.nvmlInit()\n sample_list = list()\n container_cpu_file = ''\n container_mem_file = ''\n container_blk_file = ''\n container_net_file = ''\n\n if int(container_pid) == -1:\n container_cpu_file = '/sys/fs/cgroup/cpuacct/cpuacct.stat'\n container_mem_file = '/sys/fs/cgroup/memory/memory.usage_in_bytes'\n container_blk_file = '/sys/fs/cgroup/blkio/blkio.throttle.io_service_bytes'\n container_net_file = '/proc/net/dev'\n else:\n container_cpu_file = glob.glob('/sys/fs/cgroup/cpuacct/docker/' + str(container_id) + '*/cpuacct.stat')[0]\n container_mem_file = glob.glob(\n '/sys/fs/cgroup/memory/docker/' + str(container_id) + '*/memory.usage_in_bytes')[0]\n container_blk_file = glob.glob(\n '/sys/fs/cgroup/blkio/docker/' + str(container_id) + '*/blkio.throttle.io_service_bytes')[0]\n container_net_file = '/proc/' + str(container_pid) + '/net/dev'\n\n adviser = Adviser()\n\n while time.time() - start_time < duration * 60:\n sample_data = get_sample_data(container_cpu_file, container_mem_file, container_blk_file,\n container_net_file, gpu_id, period)\n\n sample_list.append(sample_data.get_array())\n\n str_write_realtime = [sample_data.get_cpu_usage(), sample_data.get_mem_used(), sample_data.get_mem_total(),\n sample_data.get_read_bytes(), sample_data.get_write_bytes(),\n sample_data.get_network_receive(), sample_data.get_network_transmit()]\n # the real-time file will log the information of all the GPUs that the model use\n for i in range(len(gpu_id)):\n str_write_realtime.append(sample_data.get_gpu_usage()[i])\n str_write_realtime.append(sample_data.get_gpu_mem()[i])\n str_write_realtime.append(sample_data.get_gpu_mem_used()[i])\n str_write_realtime.append(sample_data.get_gpu_mem_total()[i])\n realtime_log.writerow(str_write_realtime)\n\n if len(sample_list) > analyze_period / period:\n analyze_samples(sample_list, adviser)\n sample_list = list()\n print_process((time.time() - start_time) / (duration * 60))\n print_process(1)\n analyze_result = adviser.get_advise()\n # print('The final advice is:')\n # for i, advice in zip(range(len(analyze_result)), analyze_result):\n # print(i + 1, ':', advice)\n\n\n# prepare for the args\nparser = argparse.ArgumentParser(description='The profiler to collect the hardware information')\nparser.add_argument('--container_id', '-i', help='The SHA of the docker container', required=True)\nparser.add_argument('--container_pid', '-p', help='The pid of the docker container', required=True)\nparser.add_argument('--sample_period', help='The period of the CPU usage collecting', required=True, type=float)\nparser.add_argument('--analyze_period', help='The period of the CPU usage analyzing', required=True, type=float)\nparser.add_argument('--duration', help='The duration of sampling the data once', required=True, type=float)\nparser.add_argument('--output_dir', '-o', help='The output directory to store the files', required=True)\nparser.add_argument('--gpu_index', '-g', help='Which GPUS the deep learning model is using', required=True)\nargs = parser.parse_args()\n\nif __name__ == '__main__':\n # get the GPU INDEX\n GPU_INDEX = list(map(int, args.gpu_index.split(',')))\n start_sample(args.container_id, args.sample_period, args.analyze_period, args.duration, args.output_dir, GPU_INDEX,\n args.container_pid)\n"
] | [
[
"numpy.array",
"numpy.average"
]
] |
codelibs/logana | [
"48b475e9fd5224821bfba7d41e755d8d64806651"
] | [
"python/ranking/loganary/ranking/model.py"
] | [
"import dataclasses\nimport logging\nfrom typing import Any, Callable, Dict, List, Optional, Tuple\n\nimport tensorflow as tf\nimport tensorflow_ranking as tfr\nfrom loganary.ranking.common import get_ndcg_metric\nfrom tensorflow.python.feature_column.feature_column_v2 import FeatureColumn\nfrom tensorflow.python.ops.init_ops import Initializer\n\nlogger = logging.getLogger(__name__)\n\n\[email protected]\nclass RankingModelField:\n name: str\n column_type: str = \"numeric\"\n default_value: Optional[int] = None\n\n def get_column(self) -> FeatureColumn:\n if self.column_type == \"int8\":\n return tf.feature_column.numeric_column(\n self.name, dtype=tf.int8, default_value=self.default_value\n )\n if self.column_type == \"int16\":\n return tf.feature_column.numeric_column(\n self.name, dtype=tf.int16, default_value=self.default_value\n )\n if self.column_type == \"int32\":\n return tf.feature_column.numeric_column(\n self.name, dtype=tf.int32, default_value=self.default_value\n )\n if self.column_type == \"int64\" or self.column_type == \"numeric\":\n return tf.feature_column.numeric_column(\n self.name, dtype=tf.int64, default_value=self.default_value\n )\n if self.column_type == \"float16\":\n return tf.feature_column.numeric_column(\n self.name, dtype=tf.float16, default_value=self.default_value\n )\n if self.column_type == \"float32\":\n return tf.feature_column.numeric_column(\n self.name, dtype=tf.float32, default_value=self.default_value\n )\n if self.column_type == \"float64\":\n return tf.feature_column.numeric_column(\n self.name, dtype=tf.float64, default_value=self.default_value\n )\n if self.column_type == \"double\":\n return tf.feature_column.numeric_column(\n self.name, dtype=tf.double, default_value=self.default_value\n )\n raise ValueError(f\"Unknown column type: {self.column_type}\")\n\n\[email protected]\nclass RankingModelEmbeddingField(RankingModelField):\n vocabulary_file: Optional[str] = None\n vocabulary_size: Optional[int] = None\n num_oov_buckets: int = 0\n dimension: Optional[int] = None\n combiner: str = \"mean\"\n initializer: Optional[Initializer] = None\n ckpt_to_load_from = None\n tensor_name_in_ckpt = None\n max_norm = None\n trainable: bool = True\n use_safe_embedding_lookup: bool = True\n\n def get_column(self) -> FeatureColumn:\n categorical_column_ = tf.feature_column.categorical_column_with_vocabulary_file(\n key=self.name,\n vocabulary_file=self.vocabulary_file,\n vocabulary_size=self.vocabulary_size,\n default_value=self.default_value,\n num_oov_buckets=self.num_oov_buckets,\n )\n return tf.feature_column.embedding_column(\n categorical_column_,\n self.dimension,\n combiner=self.combiner,\n initializer=self.initializer,\n ckpt_to_load_from=self.ckpt_to_load_from,\n tensor_name_in_ckpt=self.tensor_name_in_ckpt,\n max_norm=self.max_norm,\n trainable=self.trainable,\n use_safe_embedding_lookup=self.use_safe_embedding_lookup,\n )\n\n\ndef _get_default_loss_keys() -> List[str]:\n return [tfr.losses.RankingLossKey.APPROX_NDCG_LOSS]\n\n\[email protected]\nclass RankingModelConfig:\n model_path: str\n train_path: str\n eval_path: str\n context_fields: List[RankingModelField]\n example_fields: List[RankingModelField]\n label_field: RankingModelField\n num_train_steps: int = 15000\n loss_keys: List[str] = dataclasses.field(default_factory=_get_default_loss_keys)\n hidden_layer_dims: List[int] = dataclasses.field(default_factory=list)\n batch_size: int = 32\n list_size: int = 120\n learning_rate: float = 0.05\n group_size: int = 1\n dropout_rate: float = 0.5\n save_checkpoints_steps: Optional[int] = 1000\n eval_metric: Dict[str, Callable] = dataclasses.field(\n default_factory=get_ndcg_metric\n )\n\n\nclass RankingModel:\n def __init__(self, config: RankingModelConfig) -> None:\n self._config = config\n\n def train(self) -> Tuple[Any, Any]:\n tf.compat.v1.reset_default_graph()\n\n optimizer: Any = self._make_optimizer_fn()\n\n ranking_head: Any = tfr.head.create_ranking_head(\n loss_fn=self._make_loss_fn(),\n eval_metric_fns=self._config.eval_metric,\n train_op_fn=self._make_train_op_fn(optimizer),\n )\n\n model_fn: Callable = tfr.model.make_groupwise_ranking_fn(\n group_score_fn=self._make_score_fn(),\n transform_fn=self._make_transform_fn(),\n group_size=self._config.group_size,\n ranking_head=ranking_head,\n )\n\n run_config: tf.estimator.RunConfig = tf.estimator.RunConfig(\n save_checkpoints_steps=self._config.save_checkpoints_steps\n )\n self._ranker: tf.estimator.Estimator = tf.estimator.Estimator(\n model_fn=model_fn,\n model_dir=self._config.model_path,\n config=run_config,\n )\n\n def train_input_fn() -> Tuple[Any, Any]:\n return self._input_fn(True)\n\n train_spec: tf.estimator.TrainSpec = tf.estimator.TrainSpec(\n input_fn=train_input_fn, max_steps=self._config.num_train_steps\n )\n\n def eval_input_fn() -> Tuple[Any, Any]:\n return self._input_fn(False)\n\n eval_spec: tf.estimator.EvalSpec = tf.estimator.EvalSpec(\n name=\"eval\", input_fn=eval_input_fn, throttle_secs=15\n )\n\n return tf.estimator.train_and_evaluate(self._ranker, train_spec, eval_spec)\n\n def get_ranker(self) -> tf.estimator.Estimator:\n return self._ranker\n\n @staticmethod\n def _get_feature_columns(\n fields: List[RankingModelField],\n ) -> Dict[str, FeatureColumn]:\n columns: Dict[str, FeatureColumn] = {}\n for field in fields:\n columns[field.name] = field.get_column()\n return columns\n\n def _input_fn(self, is_training: bool = True) -> Tuple[Any, Any]:\n context_feature_spec: Dict[\n str, FeatureColumn\n ] = tf.feature_column.make_parse_example_spec(\n self._get_feature_columns(self._config.context_fields).values()\n )\n\n example_fields: List[FeatureColumn] = list(\n self._get_feature_columns(self._config.example_fields).values()\n )\n example_fields.append(self._config.label_field.get_column())\n example_feature_spec: Dict[\n str, FeatureColumn\n ] = tf.feature_column.make_parse_example_spec(example_fields)\n\n dataset: Any = tfr.data.build_ranking_dataset(\n file_pattern=self._config.train_path\n if is_training\n else self._config.eval_path,\n data_format=tfr.data.ELWC,\n batch_size=self._config.batch_size,\n list_size=self._config.list_size,\n context_feature_spec=context_feature_spec,\n example_feature_spec=example_feature_spec,\n reader=tf.data.TFRecordDataset,\n shuffle=False,\n num_epochs=None if is_training else 1,\n )\n features: Any = tf.compat.v1.data.make_one_shot_iterator(dataset).get_next()\n label: Any = tf.squeeze(features.pop(self._config.label_field.name), axis=2)\n label = tf.cast(label, tf.float32)\n\n return features, label\n\n def _make_transform_fn(self) -> Callable:\n def _transform_fn(features, mode):\n context_features, example_features = tfr.feature.encode_listwise_features(\n features=features,\n context_feature_columns=self._get_feature_columns(\n self._config.context_fields\n ),\n example_feature_columns=self._get_feature_columns(\n self._config.example_fields\n ),\n mode=mode,\n scope=\"transform_layer\",\n )\n\n return context_features, example_features\n\n return _transform_fn\n\n def _make_score_fn(self) -> Callable:\n def _score_fn(context_features, group_features, mode, params, _config):\n with tf.compat.v1.name_scope(\"input_layer\"):\n context_input = [\n tf.compat.v1.layers.flatten(context_features[name])\n for name in sorted(\n self._get_feature_columns(self._config.context_fields)\n )\n ]\n group_input = [\n tf.compat.v1.layers.flatten(group_features[name])\n for name in sorted(\n self._get_feature_columns(self._config.example_fields)\n )\n ]\n input_layer = tf.concat(context_input + group_input, 1)\n\n is_training = mode == tf.estimator.ModeKeys.TRAIN\n cur_layer = input_layer\n cur_layer = tf.compat.v1.layers.batch_normalization(\n cur_layer, training=is_training, momentum=0.99\n )\n\n for i, layer_width in enumerate(\n int(d) for d in self._config.hidden_layer_dims\n ):\n cur_layer = tf.compat.v1.layers.dense(cur_layer, units=layer_width)\n cur_layer = tf.compat.v1.layers.batch_normalization(\n cur_layer, training=is_training, momentum=0.99\n )\n cur_layer = tf.nn.relu(cur_layer)\n cur_layer = tf.compat.v1.layers.dropout(\n inputs=cur_layer,\n rate=self._config.dropout_rate,\n training=is_training,\n )\n logits = tf.compat.v1.layers.dense(cur_layer, units=self._config.group_size)\n return logits\n\n return _score_fn\n\n def _make_loss_fn(self) -> Callable:\n return tfr.losses.make_loss_fn(self._config.loss_keys)\n\n def _make_optimizer_fn(self) -> Callable:\n return tf.compat.v1.train.AdagradOptimizer(\n learning_rate=self._config.learning_rate\n )\n\n def _make_train_op_fn(self, optimizer: Any) -> Callable:\n def _train_op_fn(loss):\n update_ops: Any = tf.compat.v1.get_collection(\n tf.compat.v1.GraphKeys.UPDATE_OPS\n )\n minimize_op: Any = optimizer.minimize(\n loss=loss, global_step=tf.compat.v1.train.get_global_step()\n )\n train_op: Any = tf.group([update_ops, minimize_op])\n return train_op\n\n return _train_op_fn\n\n def _make_serving_input_fn(self) -> Callable:\n context_feature_spec = tf.feature_column.make_parse_example_spec(\n self._get_feature_columns(self._config.context_fields).values()\n )\n example_feature_spec = tf.feature_column.make_parse_example_spec(\n self._get_feature_columns(self._config.example_fields).values()\n )\n return tfr.data.build_ranking_serving_input_receiver_fn(\n data_format=\"example_list_with_context\",\n context_feature_spec=context_feature_spec,\n example_feature_spec=example_feature_spec,\n )\n\n def save_model(self, model_path: str = None) -> str:\n if model_path is None:\n model_path = self._config.model_path\n return self._ranker.export_saved_model(\n f\"{model_path}\",\n self._make_serving_input_fn(),\n checkpoint_path=f\"{model_path}/model.ckpt-{self._config.num_train_steps}\",\n ).decode(\"utf-8\")\n"
] | [
[
"tensorflow.compat.v1.data.make_one_shot_iterator",
"tensorflow.estimator.TrainSpec",
"tensorflow.concat",
"tensorflow.compat.v1.layers.flatten",
"tensorflow.feature_column.categorical_column_with_vocabulary_file",
"tensorflow.compat.v1.layers.batch_normalization",
"tensorflow.estimator.EvalSpec",
"tensorflow.compat.v1.name_scope",
"tensorflow.compat.v1.train.AdagradOptimizer",
"tensorflow.estimator.RunConfig",
"tensorflow.feature_column.numeric_column",
"tensorflow.compat.v1.layers.dropout",
"tensorflow.cast",
"tensorflow.group",
"tensorflow.compat.v1.layers.dense",
"tensorflow.compat.v1.reset_default_graph",
"tensorflow.estimator.Estimator",
"tensorflow.feature_column.embedding_column",
"tensorflow.compat.v1.train.get_global_step",
"tensorflow.feature_column.make_parse_example_spec",
"tensorflow.estimator.train_and_evaluate",
"tensorflow.nn.relu",
"tensorflow.compat.v1.get_collection"
]
] |
vish119/Neural-Network-for-XOR-and-Binary-Image-Classification | [
"10e27cc5618c2c399826af06aae6a2e86b4b3df2"
] | [
"dataset.py"
] | [
"import numpy as np\nimport matplotlib.pyplot as plt\nimport sys\n\nsys.path.append('../../core')\nfrom imgutils import *\n\n\nclass xor(object):\n \"\"\"\n Class that creates a xor dataset. Note that for the grading of the project, this method\n might be changed, although it's output format will not be. This implies we might use other\n methods to create data. You must assume that the dataset will be blind and your machine is\n capable of running any dataset. Although the dataset will not be changed drastically and will\n hold the XOR style .\n \"\"\"\n\n def __init__(self):\n\n self.dimensions = 2\n self.positive_means = [[-1, -1], [1, 1]]\n self.negative_means = [[-1, 1], [1, -1]]\n self.covariance = [[0.35, 0.1], [0.1, 0.35]]\n\n def query_data(self, **kwargs):\n \"\"\"\n Once initialized, this method will create more data.\n\n Args:\n samples: number of samples of data needed (optional, default randomly 10k - 50k)\n Returns:\n tuple: data a tuple, ``(x,y)``\n ``x`` is a two dimensional ndarray ordered such that axis 0 is independent\n data and data is spread along axis 1.\n ``y`` is a 1D ndarray it will be of the same length as axis 0 of x.\n \"\"\"\n if 'samples' in kwargs.keys():\n samples = kwargs['samples']\n else:\n samples = np.random.randint(low=1000, high=5000)\n\n # make positive samples\n dim1, dim2 = np.random.multivariate_normal(self.positive_means[0],\n self.covariance, samples / 4).T\n positive = np.stack((dim1, dim2), axis=1)\n dim1, dim2 = np.random.multivariate_normal(self.positive_means[1],\n self.covariance, samples / 4).T\n positive = np.concatenate((positive, np.stack((dim1, dim2), axis=1)), axis=0)\n labels = np.ones(positive.shape[0])\n\n # make the negative samples\n dim1, dim2 = np.random.multivariate_normal(self.negative_means[0],\n self.covariance, samples / 4).T\n negative = np.stack((dim1, dim2), axis=1)\n dim1, dim2 = np.random.multivariate_normal(self.negative_means[1],\n self.covariance, samples / 4).T\n negative = np.concatenate((negative, np.stack((dim1, dim2), axis=1)), axis=0)\n labels = np.concatenate((labels, np.zeros(negative.shape[0])), axis=0)\n\n data = np.concatenate((positive, negative), axis=0)\n assert data.shape[0] == labels.shape[0]\n\n perm = np.random.permutation(labels.shape[0])\n data = data[perm, :]\n labels = labels[perm]\n\n return (data, np.asarray(labels, dtype='int'))\n\n def plot(self, data, labels):\n \"\"\"\n This method will plot the data as created by this dataset generator.\n\n Args:\n data: as produced by the ``query_data`` method's first element.\n labels: as produced by the ``query_data`` method's second element.\n \"\"\"\n positive = data[labels == 1, :]\n negative = data[labels == 0, :]\n\n plt.plot(positive[:, 0], positive[:, 1], 'bo', negative[:, 0], negative[:, 1], 'rs')\n plt.axis('equal')\n plt.title('XOR Dataset')\n plt.xlabel('Dimension 1')\n plt.ylabel('Dimension 2')\n plt.show()\n\n def _demo(self):\n \"\"\"\n This is a demonstration method that will plot a version of the dataset on the screen.\n \"\"\"\n data, labels = self.query_data(samples=5000)\n self.plot(data, labels)\n\n\nclass waldo(object):\n \"\"\"\n Class that creates the waldo dataset.\n\n Args:\n dimensions: <tuple> the dimensions of image (optional, default randomly (28,28))\n noise: controls the variance of the noise being applied.\n img: <tuple>load and use an image that is not default ('waldo.jpg', 'not_waldo.jpg')\n \"\"\"\n\n def __init__(self, **kwargs):\n if 'dimensions' in kwargs.keys():\n self.sample_height = kwargs['dimensions'][0]\n self.sample_width = kwargs['dimensions'][1]\n else:\n self.sample_height = 28\n self.sample_width = 28\n\n if 'img' in kwargs.keys():\n img_waldo, img_not_waldo = kwargs['img']\n else:\n img_waldo, img_not_waldo = ('waldo.jpg', 'not_waldo.jpg')\n\n if 'noise' in kwargs.keys():\n self.var = kwargs['noise']\n else:\n if self.sample_width < 32 and self.sample_height < 32:\n self.var = 0.02\n elif self.sample_width < 64 and self.sample_heigh < 64:\n self.var = 0.07\n else:\n self.var = 0.1\n\n img = imread(img_waldo) # Load the image\n self.waldo = rgb2gray(img) # convert to grayscale\n self.waldo = normalize(self.waldo)\n\n img = imread(img_not_waldo)\n self.not_waldo = rgb2gray(img)\n self.not_waldo = normalize(self.not_waldo)\n\n self.reshape_low_height = np.floor(self.sample_height * 0.35)\n self.reshape_high_height = np.floor(self.sample_height * 0.95)\n self.reshape_low_width = np.floor(self.sample_width * 0.35)\n self.reshape_high_width = np.floor(self.sample_width * 0.95)\n\n def _query_sample(self, img):\n \"\"\"\n This is an internal method that creates a data samples.\n\n Notes:\n This creates one sample.\n \"\"\"\n sample = np.random.randint(low=0, high=256,\n size=(self.sample_height, self.sample_width))\n rshp = (np.random.randint(low=self.reshape_low_height, high=self.reshape_high_height + 1),\n np.random.randint(low=self.reshape_low_width, high=self.reshape_high_width + 1))\n img_reshaped = imresize(img, size=rshp)\n img_sample = imnoise(img_reshaped, mode='gaussian', var=self.var, clip=True)\n img_sample = imnoise(img_sample, mode='s&p', clip=True) * 255\n current_img_height = img_sample.shape[0]\n current_img_width = img_sample.shape[1]\n height_low = 1\n height_high = self.sample_height - current_img_height - 1\n width_low = 1\n width_high = self.sample_width - current_img_width - 1\n img_x_pos = np.random.randint(low=height_low, high=height_high + 1)\n img_y_pos = np.random.randint(low=width_low, high=width_high + 1)\n sample[img_x_pos: img_x_pos + current_img_height,\n img_y_pos: img_y_pos + current_img_width] = 0.7 * img_sample + \\\n 0.3 * sample[img_x_pos: img_x_pos + current_img_height,\n img_y_pos: img_y_pos + current_img_width]\n return np.asarray(sample, dtype='uint8').flatten()\n\n def _query_negative_sample(self):\n \"\"\"\n This is an internal method that creates negative data samples.\n\n Notes:\n This creates one sample.\n \"\"\"\n sample = self._query_sample(img=self.not_waldo)\n return sample\n\n def _query_positive_sample(self):\n \"\"\"\n This is an internal method that creates positive data samples.\n\n Notes:\n This creates one sample.\n \"\"\"\n sample = self._query_sample(img=self.waldo)\n return sample\n\n def query_data(self, **kwargs):\n \"\"\"\n Once initialized, this method will create data.\n\n Args:\n samples: number of samples of data needed (optional, default randomly 10k - 50k)\n Returns:\n tuple: data a tuple, ``(x,y)``\n ``x`` is a two dimensional ndarray ordered such that axis 0 is independent\n data and data is spread along axis 1.\n ``y`` is a 1D ndarray it will be of the same length as axis 0 or x. Will be integer.\n \"\"\"\n if 'samples' in kwargs.keys():\n samples = kwargs['samples']\n else:\n samples = np.random.randint(low=100, high=500)\n\n # Create dummy arrays\n data = np.zeros((samples, self.sample_height * self.sample_width))\n labels = np.zeros((samples,), dtype='int')\n\n for sample in xrange(samples):\n labels[sample] = np.random.randint(low=0, high=2)\n if labels[sample] == 1:\n data[sample] = self._query_positive_sample()\n else:\n data[sample] = self._query_negative_sample()\n\n return (data, labels)\n\n def _demo(self):\n \"\"\"\n This is a demonstration method that will display a random positive and negative samples.\n \"\"\"\n sample_positive = self._query_positive_sample().reshape(self.sample_height,\n self.sample_width)\n imshow(sample_positive, window='positive')\n\n sample_negative = self._query_negative_sample().reshape(self.sample_height,\n self.sample_width)\n imshow(sample_negative, window='negative')\n\n def display_sample(self, sample, title='image'):\n \"\"\"\n This method will display a particular smaple in the dataset generated.\n\n Args:\n sample: provide one row of data\n title: (optional) title of the window for image display\n \"\"\"\n imshow(sample.reshape(self.sample_height, self.sample_width), window=title)"
] | [
[
"numpy.ones",
"numpy.zeros",
"numpy.random.permutation",
"matplotlib.pyplot.axis",
"numpy.floor",
"numpy.asarray",
"matplotlib.pyplot.title",
"numpy.random.multivariate_normal",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"numpy.stack",
"matplotlib.pyplot.plot",
"numpy.concatenate",
"numpy.random.randint",
"matplotlib.pyplot.xlabel"
]
] |
JLans/chemprop | [
"4907f77d6ad3a316b70744a6b4cb5e290bd98d40"
] | [
"chemprop/train/cross_validate.py"
] | [
"from collections import defaultdict\nimport csv\nfrom logging import Logger\nimport logging\nimport os\nimport sys\nfrom typing import Callable, Dict, List, Tuple\n\nimport numpy as np\nimport pandas as pd\n\nfrom .run_training import run_training\nfrom chemprop.args import TrainArgs\nfrom chemprop.constants import TEST_SCORES_FILE_NAME, TRAIN_LOGGER_NAME\nfrom chemprop.data import get_data, get_task_names, MoleculeDataset, validate_dataset_type\nfrom chemprop.utils import create_logger, makedirs, timeit\nfrom chemprop.features import set_extra_atom_fdim, set_extra_bond_fdim\nfrom chemprop.models import MoleculeModel\n\n\n@timeit(logger_name=TRAIN_LOGGER_NAME)\ndef cross_validate(args: TrainArgs,\n train_func: Callable[[TrainArgs, MoleculeDataset, Logger], Dict[str, List[float]]],\n model_list: List[MoleculeModel] = None) -> Tuple[float, float]:\n \"\"\"\n Runs k-fold cross-validation.\n\n For each of k splits (folds) of the data, trains and tests a model on that split\n and aggregates the performance across folds.\n\n :param args: A :class:`~chemprop.args.TrainArgs` object containing arguments for\n loading data and training the Chemprop model.\n :param train_func: Function which runs training.\n :param model_list: A list of :class:`~chemprop.models.model.MoleculeModel`.\n :return: A tuple containing the mean and standard deviation performance across folds.\n \"\"\"\n logging.root.manager.loggerDict.pop(TRAIN_LOGGER_NAME,None)\n logger = create_logger(name=TRAIN_LOGGER_NAME, save_dir=args.save_dir, quiet=args.quiet)\n if logger is not None:\n debug, info = logger.debug, logger.info\n else:\n debug = info = print\n\n # Initialize relevant variables\n init_seed = args.seed\n save_dir = args.save_dir\n args.task_names = get_task_names(path=args.data_path, smiles_columns=args.smiles_columns,\n target_columns=args.target_columns, ignore_columns=args.ignore_columns)\n\n # Print command line\n debug('Command line')\n debug(f'python {\" \".join(sys.argv)}')\n\n # Print args\n debug('Args')\n debug(args)\n\n # Save args\n makedirs(args.save_dir)\n args.save(os.path.join(args.save_dir, 'args.json'))\n\n # Get data\n debug('Loading data')\n data = get_data(\n path=args.data_path,\n args=args,\n smiles_columns=args.smiles_columns,\n logger=logger,\n skip_none_targets=True\n )\n validate_dataset_type(data, dataset_type=args.dataset_type)\n args.features_size = data.features_size()\n\n if args.atom_descriptors == 'descriptor':\n args.atom_descriptors_size = data.atom_descriptors_size()\n args.ffn_hidden_size += args.atom_descriptors_size\n elif args.atom_descriptors == 'feature':\n args.atom_features_size = data.atom_features_size()\n set_extra_atom_fdim(args.atom_features_size)\n if args.bond_features_path is not None:\n args.bond_features_size = data.bond_features_size()\n set_extra_bond_fdim(args.bond_features_size)\n\n debug(f'Number of tasks = {args.num_tasks}')\n\n # Run training on different random seeds for each fold\n all_scores = defaultdict(list)\n for fold_num in range(args.num_folds):\n info(f'Fold {fold_num}')\n args.seed = init_seed + fold_num\n args.save_dir = os.path.join(save_dir, f'fold_{fold_num}')\n makedirs(args.save_dir)\n data.reset_features_and_targets()\n model_scores = train_func(args, data, logger, model_list)\n for metric, scores in model_scores.items():\n all_scores[metric].append(scores)\n all_scores = dict(all_scores)\n\n # Convert scores to numpy arrays\n for metric, scores in all_scores.items():\n all_scores[metric] = np.array(scores)\n\n # Report results\n info(f'{args.num_folds}-fold cross validation')\n\n # Report scores for each fold\n for fold_num in range(args.num_folds):\n for metric, scores in all_scores.items():\n info(f'\\tSeed {init_seed + fold_num} ==> test {metric} = {np.nanmean(scores[fold_num]):.6f}')\n\n if args.show_individual_scores:\n for task_name, score in zip(args.task_names, scores[fold_num]):\n info(f'\\t\\tSeed {init_seed + fold_num} ==> test {task_name} {metric} = {score:.6f}')\n\n # Report scores across folds\n for metric, scores in all_scores.items():\n avg_scores = np.nanmean(scores, axis=1) # average score for each model across tasks\n mean_score, std_score = np.nanmean(avg_scores), np.nanstd(avg_scores)\n info(f'Overall test {metric} = {mean_score:.6f} +/- {std_score:.6f}')\n\n if args.show_individual_scores:\n for task_num, task_name in enumerate(args.task_names):\n info(f'\\tOverall test {task_name} {metric} = '\n f'{np.nanmean(scores[:, task_num]):.6f} +/- {np.nanstd(scores[:, task_num]):.6f}')\n\n # Save scores\n with open(os.path.join(save_dir, TEST_SCORES_FILE_NAME), 'w') as f:\n writer = csv.writer(f)\n\n header = ['Task']\n for metric in args.metrics:\n header += [f'Mean {metric}', f'Standard deviation {metric}'] + \\\n [f'Fold {i} {metric}' for i in range(args.num_folds)]\n writer.writerow(header)\n\n for task_num, task_name in enumerate(args.task_names):\n row = [task_name]\n for metric, scores in all_scores.items():\n task_scores = scores[:, task_num]\n mean, std = np.nanmean(task_scores), np.nanstd(task_scores)\n row += [mean, std] + task_scores.tolist()\n writer.writerow(row)\n\n # Determine mean and std score of main metric\n avg_scores = np.nanmean(all_scores[args.metric], axis=1)\n mean_score, std_score = np.nanmean(avg_scores), np.nanstd(avg_scores)\n\n # Optionally merge and save test preds\n if args.save_preds:\n all_preds = pd.concat([pd.read_csv(os.path.join(save_dir, f'fold_{fold_num}', 'test_preds.csv'))\n for fold_num in range(args.num_folds)])\n all_preds.to_csv(os.path.join(save_dir, 'test_preds.csv'), index=False)\n\n for handler in logger.handlers[:]:\n handler.close()\n logger.removeHandler(handler)\n del logger\n return mean_score, std_score\n\n\ndef chemprop_train() -> None:\n \"\"\"Parses Chemprop training arguments and trains (cross-validates) a Chemprop model.\n\n This is the entry point for the command line command :code:`chemprop_train`.\n \"\"\"\n cross_validate(args=TrainArgs().parse_args(), train_func=run_training)\n"
] | [
[
"numpy.nanmean",
"numpy.array",
"numpy.nanstd"
]
] |
williamchevremont/dynamix | [
"445a85b331278097a0c997dfecd73c39dc8f1afd"
] | [
"dynamix/correlator/dense.py"
] | [
"from math import sqrt\nfrom collections import namedtuple\nimport numpy as np\nimport pyopencl.array as parray\nfrom os import path\nfrom multiprocessing import cpu_count\nfrom ..utils import nextpow2, updiv, get_opencl_srcfile, get_next_power\nfrom .common import OpenclCorrelator, BaseCorrelator\n\nfrom silx.math.fft.fftw import FFTW\ntry:\n from silx.math.fft.cufft import CUFFT\n import pycuda.gpuarray as garray\n from pycuda.compiler import SourceModule\nexcept ImportError:\n CUFFT = None\ntry:\n import skcuda.linalg as cublas\n import skcuda.misc as skmisc\nexcept ImportError:\n cublas = None\ntry:\n import pyfftw\nexcept ImportError:\n pyfftw = None\n\nNCPU = cpu_count()\n\nCorrelationResult = namedtuple(\"CorrelationResult\", \"res dev\")\n\n\ndef py_dense_correlator(xpcs_data, mask, calc_std=False):\n \"\"\"\n Reference implementation of the dense correlator.\n\n Parameters\n -----------\n xpcs_data: numpy.ndarray\n Stack of XPCS frames with shape (n_frames, n_rows, n_columns)\n mask: numpy.ndarray\n Mask of bins in the format (n_rows, n_columns).\n Zero pixels indicate unused pixels.\n calc_std: boolean\n Calculate the standard deviation in addition to the mean\n \n Return: 1 or 2 arrays depending on `calc_std` \n \"\"\"\n ind = np.where(mask > 0) # unused pixels are 0\n xpcs_data = np.array(xpcs_data[:, ind[0], ind[1]], np.float32) # (n_tau, n_pix)\n meanmatr = np.mean(xpcs_data, axis=1) # xpcs_data.sum(axis=-1).sum(axis=-1)/n_pix\n ltimes, lenmatr = np.shape(xpcs_data) # n_tau, n_pix\n meanmatr.shape = 1, ltimes\n\n num = np.dot(xpcs_data, xpcs_data.T)\n denom = np.dot(meanmatr.T, meanmatr)\n\n res = np.zeros(ltimes) # was ones()\n if calc_std:\n dev = np.zeros_like(res)\n\n for i in range(ltimes): # was ltimes-1, so res[-1] was always 1 !\n dia_n = np.diag(num, k=i) / lenmatr\n dia_d = np.diag(denom, k=i)\n res[i] = np.sum(dia_n) / np.sum(dia_d)\n if calc_std:\n dev[i] = np.std(dia_n / dia_d) / sqrt(len(dia_d))\n if calc_std:\n return CorrelationResult(res, dev)\n else:\n return res\n\n\ndef y_dense_correlator(xpcs_data, mask):\n \"\"\"\n version of YC\n Reference implementation of the dense correlator.\n\n Parameters\n -----------\n xpcs_data: numpy.ndarray\n Stack of XPCS frames with shape (n_frames, n_rows, n_columns)\n mask: numpy.ndarray\n Mask of bins in the format (n_rows, n_columns).\n Zero pixels indicate unused pixels.\n \"\"\"\n ind = np.where(mask > 0) # unused pixels are 0\n xpcs_data = xpcs_data[:, ind[0], ind[1]] # (n_tau, n_pix)\n del ind\n ltimes, lenmatr = np.shape(xpcs_data) # n_tau, n_pix\n meanmatr = np.array(np.mean(xpcs_data, axis=1), np.float32) # xpcs_data.sum(axis=-1).sum(axis=-1)/n_pix\n meanmatr.shape = 1, ltimes\n\n if ltimes * lenmatr > 1000 * 512 * 512:\n nn = 16\n newlen = lenmatr // nn\n num = np.dot(np.array(xpcs_data[:,:newlen], np.float32), np.array(xpcs_data[:,:newlen], np.float32).T)\n xpcs_data = xpcs_data[:, newlen:] + 0\n for i in range(1, nn - 1, 1):\n num += np.dot(np.array(xpcs_data[:,:newlen], np.float32), np.array(xpcs_data[:,:newlen], np.float32).T)\n xpcs_data = xpcs_data[:, newlen:] + 0\n num += np.dot(np.array(xpcs_data, np.float32), np.array(xpcs_data, np.float32).T)\n else:\n num = np.dot(np.array(xpcs_data, np.float32), np.array(xpcs_data, np.float32).T)\n\n num /= lenmatr\n denom = np.dot(meanmatr.T, meanmatr)\n del meanmatr\n res = np.zeros((ltimes - 1, 3)) # was ones()\n for i in range(1, ltimes, 1): # was ltimes-1, so res[-1] was always 1 !\n dia_n = np.diag(num, k=i)\n sdia_d = np.diag(denom, k=i)\n res[i - 1, 0] = i\n res[i - 1, 1] = np.sum(dia_n) / np.sum(sdia_d)\n res[i - 1, 2] = np.std(dia_n / sdia_d) / len(sdia_d) ** 0.5\n return res\n\n\nclass MatMulCorrelator(BaseCorrelator):\n\n def __init__(self, shape, nframes,\n qmask=None,\n scale_factor=None,\n extra_options={}):\n\n super().__init__()\n super()._set_parameters(shape, nframes, qmask, scale_factor, extra_options)\n\n def correlate(self, frames, calc_std=False):\n res = np.zeros((self.n_bins, self.nframes), dtype=np.float32)\n if calc_std:\n dev = np.zeros_like(res)\n for i, bin_value in enumerate(self.bins):\n mask = (self.qmask == bin_value)\n tmp = py_dense_correlator(frames, mask, calc_std)\n if calc_std:\n res[i], dev[i] = tmp\n else:\n res[i] = tmp\n if calc_std:\n return CorrelationResult(res, dev)\n else:\n return res\n\n\nclass DenseCorrelator(OpenclCorrelator):\n\n kernel_files = [\"densecorrelator.cl\"]\n\n def __init__(\n self, shape, nframes,\n qmask=None, dtype=\"f\", weights=None, extra_options={},\n ctx=None, devicetype=\"all\", platformid=None, deviceid=None,\n block_size=None, memory=None, profile=False\n ):\n \"\"\"\n Class for OpenCL dense correlator.\n This correlator is usually slower than all the other correlators.\n \"\"\"\n super(DenseCorrelator, self).__init__(\n shape, nframes, qmask=qmask, dtype=dtype, weights=weights,\n extra_options=extra_options,\n ctx=ctx, devicetype=devicetype, platformid=platformid,\n deviceid=deviceid, block_size=block_size, memory=memory,\n profile=profile\n )\n self._setup_kernels()\n self._allocate_arrays()\n\n def _setup_kernels(self):\n kernel_files = list(map(get_opencl_srcfile, self.kernel_files))\n self.compile_kernels(\n kernel_files=kernel_files,\n compile_options=[\n \"-DIMAGE_WIDTH=%d\" % self.shape[1],\n \"-DNUM_BINS=%d\" % self.n_bins,\n \"-DDTYPE=%s\" % self.c_dtype,\n \"-DDTYPE_SUMS=%s\" % self.c_sums_dtype,\n \"-DN_FRAMES=%d\" % self.nframes,\n \"-DUSE_SHARED=%d\" % 0, # <\n \"-DSUM_WG_SIZE=%d\" % min(1024, nextpow2(self.shape[1])),\n ]\n )\n self.correlation_kernel = self.kernels.get_kernel(\"correlator_multiQ_dense\")\n self.wg = (\n min(1024, nextpow2(self.shape[1])),\n 1\n )\n self.grid = (max(self.wg[0], self.shape[1]), self.nframes)\n self.sums_kernel = self.kernels.get_kernel(\"compute_sums_dense\")\n self.corr1D_kernel = self.kernels.get_kernel(\"correlate_1D\")\n\n def _allocate_arrays(self):\n self.d_frames = parray.zeros(\n self.queue,\n (self.nframes,) + self.shape,\n self.dtype\n )\n self._old_d_frames = None\n self.d_sums = parray.zeros(\n self.queue,\n self.output_shape,\n self.sums_dtype\n )\n self.d_sums_f = parray.zeros(\n self.queue,\n self.output_shape,\n self.output_dtype,\n )\n self.d_output = parray.zeros(\n self.queue,\n (self.n_bins, self.nframes),\n np.float32\n )\n\n def _normalize_sums(self):\n if self.n_bins == 0:\n self.d_sums_f[:] *= self.scale_factors[0]\n else:\n for i, factor in enumerate(self.scale_factors.values()):\n self.d_sums_f[i] /= np.array([factor], dtype=self.output_dtype)[0]\n self.d_sums_f.finish()\n\n def correlate(self, frames):\n self._set_data({\"frames\": frames})\n\n # Denominator\n self._sum_frames()\n self._correlate_1d()\n self._normalize_sums()\n\n # Numerator\n evt = self.correlation_kernel(\n self.queue,\n self.grid,\n self.wg,\n self.d_frames.data,\n self.d_qmask.data,\n self.d_sums_f.data,\n self.d_output.data,\n np.int32(self.shape[0]),\n np.int32(self.nframes),\n )\n\n self.profile_add(evt, \"Dense correlator\")\n self._reset_arrays([\"frames\"])\n\n return self.d_output.get() # get ?\n\n def _sum_frames(self):\n evt = self.sums_kernel(\n self.queue,\n (self.wg[0], self.nframes),\n (self.wg[0], 1),\n self.d_frames.data,\n self.d_qmask.data,\n self.d_sums.data,\n np.int32(self.shape[0]),\n np.int32(self.nframes)\n )\n evt.wait()\n self.profile_add(evt, \"Sum kernel\")\n\n def _correlate_1d(self):\n evt = self.corr1D_kernel(\n self.queue,\n (self.nframes, self.n_bins),\n None,\n self.d_sums.data,\n self.d_sums_f.data,\n )\n evt.wait()\n self.profile_add(evt, \"Corr 1D kernel\")\n\n\nclass FFTCorrelator(BaseCorrelator):\n\n def __init__(self, shape, nframes,\n qmask=None,\n weights=None,\n scale_factor=None,\n precompute_fft_plans=False,\n extra_options={}):\n super().__init__()\n super()._set_parameters(shape, nframes, qmask, scale_factor, extra_options)\n self._init_fft_plans(precompute_fft_plans)\n\n def _init_fft_plans(self, precompute_fft_plans):\n self.precompute_fft_plans = precompute_fft_plans\n self.Nf = int(get_next_power(2 * self.nframes))\n self.n_pix = {}\n for bin_val in self.bins:\n mask = (self.qmask == bin_val)\n self.n_pix[bin_val] = mask.sum()\n\n self.fft_plans = {}\n for bin_val, npix in self.n_pix.items():\n if precompute_fft_plans:\n self.fft_plans[bin_val] = self._create_fft_plan(npix)\n else:\n self.fft_plans[bin_val] = None\n\n def _create_fft_plan(self, npix):\n raise NotImplementedError(\"This must be implemented by child class\")\n\n def _get_plan(self, bin_val):\n fft_plan = self.fft_plans[bin_val]\n if fft_plan is None:\n fft_plan = self._create_fft_plan(self.n_pix[bin_val])\n return fft_plan\n\n def _correlate_fft(self, frames_flat, fftw_plan):\n raise NotImplementedError(\"This must be implemented by child class\")\n\n def correlate(self, frames):\n res = np.zeros((self.n_bins, self.nframes), dtype=np.float32)\n frames_flat = frames.reshape((self.nframes, -1))\n for i, bin_val in enumerate(self.bins):\n mask = (self.qmask == bin_val).ravel()\n frames_flat_currbin = frames_flat[:, mask]\n fft_plan = self._get_plan(bin_val)\n res[i] = self._correlate_fft(frames_flat_currbin, fft_plan)\n return res\n\n\nclass FFTWCorrelator(FFTCorrelator):\n\n def __init__(self, shape, nframes,\n qmask=None,\n weights=None,\n scale_factor=None,\n precompute_fft_plans=False,\n extra_options={}):\n super().__init__(\n shape, nframes, qmask=qmask,\n weights=weights, scale_factor=scale_factor,\n precompute_fft_plans=precompute_fft_plans, extra_options=extra_options\n )\n if pyfftw is None:\n raise ImportError(\"pyfftw needs to be installed\")\n\n def _create_fft_plan(self, npix):\n return FFTW(\n shape=(npix, self.Nf), dtype=np.float32,\n num_threads=NCPU, axes=(-1,)\n )\n\n def _correlate_fft(self, frames_flat, fftw_plan):\n npix = frames_flat.shape[1]\n\n fftw_plan.data_in.fill(0)\n f_out1 = fftw_plan.data_out\n f_out2 = np.zeros_like(fftw_plan.data_out)\n\n fftw_plan.data_in[:,:self.nframes] = frames_flat.T\n\n f_out1 = fftw_plan.fft(None, output=f_out1)\n fftw_plan.data_in.fill(0)\n fftw_plan.data_in[:,:self.nframes] = frames_flat.T[:,::-1]\n\n f_out2 = fftw_plan.fft(None, output=f_out2)\n f_out1 *= f_out2\n num = fftw_plan.ifft(f_out1)\n\n num = num.sum(axis=0)[self.nframes - 1:self.nframes - 1 + self.nframes]\n sums = frames_flat.sum(axis=1)\n denom = np.correlate(sums, sums, \"full\")[sums.size - 1:] / npix\n\n res = num / denom\n return res\n\n\ndef export_wisdom(basedir):\n w = pyfftw.export_wisdom()\n for i in range(len(w)):\n fname = path.join(basedir, \"wis%d.dat\" % i)\n with open(fname, \"wb\") as fid:\n fid.write(w[i])\n\n\ndef import_wisdom(basedir):\n w = []\n for i in range(3): # always 3 ?\n fname = path.join(basedir, \"wis%d.dat\" % i)\n if not(path.isfile(fname)):\n raise RuntimeError(\"Could find wisdom file %s\" % fname)\n with open(fname, \"rb\") as fid:\n w.append(fid.read())\n pyfftw.import_wisdom(w)\n\n"
] | [
[
"numpy.zeros_like",
"numpy.sum",
"numpy.dot",
"numpy.zeros",
"numpy.diag",
"numpy.correlate",
"numpy.int32",
"numpy.shape",
"numpy.array",
"numpy.std",
"numpy.where",
"numpy.mean"
]
] |
waltervrossem/tomso | [
"6502bfda598d2b8d13e8e06249c4687fe2bb5f37"
] | [
"tomso/fgong.py"
] | [
"\"\"\"\nFunctions for manipulating FGONG files.\n\"\"\"\n\nimport numpy as np\nfrom tomso.common import integrate, DEFAULT_G\nfrom tomso.adipls import fgong_to_amdl\n\n\ndef load_fgong(filename, N=-1, return_comment=False):\n \"\"\"Given an FGONG file, returns NumPy arrays `glob` and `var` that\n correspond to the scalar and point-wise variables, as specified\n in the `FGONG format`_.\n\n .. _FGONG format: https://www.astro.up.pt/corot/ntools/docs/CoRoT_ESTA_Files.pdf\n\n Also returns the first four lines of the file as a `comment`, if\n desired.\n\n The version number `ivers` is not implemented.\n\n Parameters\n ----------\n filename: str\n Name of the FGONG file to read.\n N: integer, optional\n Number of characters in each float. If negative, the function\n tries to guess the size of each float. (default: -1)\n return_comment: bool, optional\n If ``True``, return the first four lines of the FGONG file.\n These are comments that are not used in any calculations.\n\n Returns\n -------\n glob: NumPy array\n The scalar (or global) variables for the stellar model\n var: NumPy array\n The point-wise variables for the stellar model. i.e. things\n that vary through the star like temperature, density, etc.\n comment: list of strs, optional\n The first four lines of the FGONG file. These are comments\n that are not used in any calculations. Only returned if\n ``return_comment=True``.\n\n \"\"\"\n \n def replace(s):\n # handles annoying Fortran formatting\n t = s[:].lower().strip()\n t = t.replace('d', 'e')\n t = t.replace('+', 'e+')\n t = t.replace('-', 'e-')\n t = t.replace('ee', 'e')\n if t.startswith('e'):\n t = t[1:]\n return t\n \n f = open(filename, 'r')\n\n comment = [f.readline() for i in range(4)]\n\n nn, iconst, ivar, ivers = [int(i) for i in f.readline().split()]\n\n lines = f.readlines()\n tmp = []\n\n # try to guess the length of each float in the data\n if N < 0:\n N = len(lines[0].strip('\\n').rstrip(' '))//5\n \n for line in lines:\n for i in range(len(line)//N):\n s = line[i*N:i*N+N]\n # print(s)\n if s[-9:] == '-Infinity':\n s = '-Inf'\n elif s[-9:] == ' Infinity':\n s = 'Inf'\n elif s.lower().endswith('nan'):\n s = 'nan'\n elif 'd' in s.lower():\n s.lower().replace('d', 'e')\n else:\n s = replace(s.lower())\n \n if s == '': # Catch files with space padding.\n continue\n tmp.append(float(s))\n\n glob = np.array(tmp[:iconst])\n var = np.array(tmp[iconst:]).reshape((-1, ivar))\n\n f.close()\n\n if return_comment:\n return glob, var, comment\n else:\n return glob, var\n\n\ndef save_fgong(filename, glob, var, fmt='%16.9E', ivers=0,\n comment=['\\n','\\n','\\n','\\n']):\n \"\"\"Given data for an FGONG file in the format returned by\n :py:meth:`~tomso.fgong.load_fgong` (i.e. two NumPy arrays and a\n possible header), writes the data to a file.\n\n Parameters\n ----------\n filename: str\n Filename to which FGONG data is written.\n glob: NumPy array\n The global variables for the stellar model.\n var: NumPy array\n The point-wise variables for the stellar model. i.e. things\n that vary through the star like temperature, density, etc.\n ivers: int, optional\n The integer indicating the version number of the file.\n (default=0)\n comment: list of strs, optional\n The first four lines of the FGONG file, which usually contain\n notes about the stellar model.\n\n \"\"\"\n nn, ivar = var.shape\n iconst = len(glob)\n\n with open(filename, 'wt') as f:\n f.writelines(comment)\n\n line = '%10i'*4 % (nn, iconst, ivar, ivers)\n f.writelines([line + '\\n'])\n\n for i in range(0, iconst, 5):\n N = np.mod(i+4, 5)+1 # number of floats in this row\n line = fmt*N % tuple(glob[i:i+5])\n if len(line) != N*int(fmt[1:3]):\n line = ''\n for j in range(5):\n part = fmt % glob[i:i+5][j]\n if len(part) != int(fmt[1:3]):\n part = part.replace('E', '')\n line += part\n f.writelines([line + '\\n'])\n\n for row in var:\n for i in range(0, ivar, 5):\n N = np.mod(i+4, 5)+1 # number of floats in this row\n line = fmt*N % tuple(row[i:i+5])\n if len(line) != N * int(fmt[1:3]):\n line = ''\n for j in range(5):\n part = fmt % row[i:i+5][j]\n if len(part) != int(fmt[1:3]):\n part = part.replace('E', '')\n line += part\n f.writelines([line + '\\n'])\n\n\ndef fgong_get(key_or_keys, glob, var, G=DEFAULT_G):\n \"\"\"Retrieves physical properties of a FGONG model from the ``glob`` and\n ``var`` arrays.\n\n Parameters\n ----------\n key_or_keys: str or list of strs\n The desired variable or a list of desired variables. Current\n options are:\n\n - ``M``: total mass (float)\n - ``R``: photospheric radius (float)\n - ``L``: total luminosity (float)\n - ``r``: radius (array)\n - ``x``: fractional radius (array)\n - ``m``: mass co-ordinate (array)\n - ``q``: fractional mass co-ordinate (array)\n - ``g``: gravity (array)\n - ``rho``: density (array)\n - ``P``: pressure (array)\n - ``Hp``: pressure scale height (array)\n - ``Hrho``: density scale height (array)\n - ``G1``: first adiabatic index (array)\n - ``T``: temperature (array)\n - ``X``: hydrogen abundance (array)\n - ``L_r``: luminosity at radius ``r`` (array)\n - ``kappa``: opacity (array)\n - ``epsilon``: specific energy generation rate (array)\n - ``cs2``: sound speed squared (array)\n - ``cs``: sound speed (array)\n - ``tau``: acoustic depth (array)\n\n For example, if ``glob`` and ``var`` have been returned from\n :py:meth:`~tomso.fgong.load_fgong`, you could use\n\n >>> M, m = fgong.fgong_get(['M', 'm'], glob, var)\n\n to get the total mass and mass co-ordinate. If you only want\n one variable, you don't need to use a list. The return type\n is just the one corresponding float or array. So, to get a\n single variable you could use either\n\n >>> x, = fgong.fgong_get(['x'], glob, var)\n\n or\n\n >>> x = fgong.fgong_get('x', glob, var)\n\n glob: NumPy array\n The scalar (or global) variables for the stellar model\n var: NumPy array\n The point-wise variables for the stellar model. i.e. things\n that vary through the star like temperature, density, etc.\n \n Returns\n -------\n output: list of floats and arrays\n A list returning the floats or arrays in the order requested\n by the parameter ``keys``.\n\n \"\"\"\n M, R, L = glob[:3]\n r, lnq, T, P, rho, X, L_r, kappa, epsilon, G1 = var[:,:10].T\n A = var[:,14]\n \n x = r/R\n q = np.exp(lnq)\n m = q*M\n g = G*m/r**2\n Hp = P/(rho*g)\n Hrho = 1/(1/G1/Hp + A/r)\n cs2 = G1*P/rho # square of the sound speed\n cs = np.sqrt(cs2)\n tau = -integrate(1./cs[::-1], r[::-1])[::-1] # acoustic depth\n\n if type(key_or_keys) == str:\n keys = [key_or_keys]\n just_one = True\n else:\n keys = key_or_keys\n just_one = False\n \n output = []\n for key in keys:\n if key == 'M': output.append(M)\n elif key == 'R': output.append(R)\n elif key == 'L': output.append(L)\n elif key == 'r': output.append(r)\n elif key == 'x': output.append(x)\n elif key == 'm': output.append(m)\n elif key == 'q': output.append(q)\n elif key == 'g': output.append(g)\n elif key == 'rho': output.append(rho)\n elif key == 'P': output.append(P)\n elif key == 'Hp': output.append(Hp)\n elif key == 'Hrho': output.append(Hrho)\n elif key == 'G1': output.append(G1)\n elif key == 'T': output.append(T)\n elif key == 'X': output.append(X)\n elif key == 'L_r': output.append(L_r)\n elif key == 'kappa': output.append(kappa)\n elif key == 'epsilon': output.append(epsilon)\n elif key == 'cs2': output.append(cs2)\n elif key == 'cs': output.append(cs)\n elif key == 'tau': output.append(tau)\n else: raise ValueError('%s is not a valid key for fgong.fgong_get' % key)\n\n if just_one:\n assert(len(output) == 1)\n return output[0]\n else:\n return output\n"
] | [
[
"numpy.array",
"numpy.sqrt",
"numpy.exp",
"numpy.mod"
]
] |
Isakon/Viral_Tweets_Predictions_Challenge_1st_Place_Solution | [
"f4b52748d7b87ad092051c6982553b9550895354"
] | [
"code/exp_cv688180_lgb_refactored_jun23/utils.py"
] | [
"import os\nimport numpy as np\nimport pandas as pd\n\ndef compare_data(test,\n compare_path='/home/isakev/challenges/viral_tweets/data/processed/a_test_data_lgb_NoImpute_NoOhe_jun23.csv'):\n print(\"preprocessed path:\\n\", compare_path)\n # print(\"cfg.test_preprocessed_path\\n:\", cfg.test_preprocessed_path)\n # assert os.path.basename(compare_path) == os.path.basename(cfg.test_preprocessed_path)\n\n test_compare = pd.read_csv(compare_path)\n\n cols_here_not_in_preproc = set(test.columns).difference(set(test_compare.columns))\n cols_preproc_not_in_here = set(test_compare.columns).difference(set(test.columns))\n\n print(\"cols_preproc_not_in_here:\\n\", cols_preproc_not_in_here)\n print()\n print(\"cols_here_not_in_preproc:\\n\", cols_here_not_in_preproc)\n\n print(\"test.isnull().sum().sort_values().tail():\\n\", test.isnull().sum().sort_values().tail())\n print(\"\\ntest_compare.isnull().sum().sort_values().tail():\\n\", test_compare.isnull().sum().sort_values().tail())\n print()\n minus_ones_compare, minus_ones_here = [], []\n for col in test_compare.columns:\n minus_ones_compare.append((test_compare[col] == -1).sum())\n minus_ones_here.append((test_compare[col] == -1).sum())\n print(\"minus_ones_compare:\", sum(minus_ones_compare))\n print(\"minus_ones_here:\", sum(minus_ones_here))\n print()\n\n assert len(cols_preproc_not_in_here) == 0\n assert len(cols_preproc_not_in_here) == 0\n if len(test)>5000:\n assert len(test) == len(test_compare), f\"len test = {len(test)} , len test_compare = {len(test_compare)}\"\n assert sum(minus_ones_compare) == sum(minus_ones_here)\n min_len = min(len(test), len(test_compare))\n test = test.iloc[:min_len].reset_index(drop=True)\n test_compare = test_compare[:min_len]\n unequals = test.compare(test_compare)\n print(\"test.compare(test_compare).shape[1]\", unequals.shape[1])\n print(\"test.compare(test_compare).columns\", unequals.columns)\n\n diffs_ls = []\n for col0 in unequals.columns.get_level_values(0):\n diffs = unequals[(col0, 'self')] - unequals[(col0, 'other')]\n diffs_ls.append(np.sum(diffs)/len(diffs))\n\n argsorted_cols = unequals.columns.get_level_values(0)[np.argsort(diffs_ls)]\n\n print(\"np.sum(diffs_ls\", np.sum(diffs_ls))\n print(\"some diffs_ls[-10:]\",\n [f\"{col}: {diff_}\" for (col, diff_) in\n zip(argsorted_cols[-10:], np.sort(diffs_ls)[-10:])])\n\n # assert test.compare(test_compare).shape[1] == 0, \"test.compare(test_compare).shape[1] == 0\"\n"
] | [
[
"pandas.read_csv",
"numpy.sum",
"numpy.sort",
"numpy.argsort"
]
] |
nmoran/CosmiQ_SN6_Baseline | [
"063b62605eb9e426ac4407e48c46735ffb420dd5"
] | [
"baseline.py"
] | [
"#!/usr/bin/env python\n\nimport os\nimport sys\nimport glob\nimport math\nimport uuid\nimport shutil\nimport pathlib\nimport argparse\nimport numpy as np\nimport pandas as pd\nimport geopandas as gpd\nimport skimage\nimport torch\nimport tqdm\nimport gdal\n\nimport solaris as sol\n\nimport model\n\ndef makeemptyfolder(path):\n \"\"\"\n Create an empty folder, deleting anything there already\n \"\"\"\n shutil.rmtree(path, ignore_errors=True)\n pathlib.Path(path).mkdir(exist_ok=True)\n\n\ndef readrotationfile(path):\n \"\"\"\n Reads SAR_orientations file, which lists whether each strip was imaged\n from the north (denoted by 0) or from the south (denoted by 1).\n \"\"\"\n rotationdf = pd.read_csv(path,\n sep=' ',\n index_col=0,\n names=['strip', 'direction'],\n header=None)\n rotationdf['direction'] = rotationdf['direction'].astype(int)\n return rotationdf\n\n\ndef lookuprotation(tilepath, rotationdf):\n \"\"\"\n Looks up the SAR_orientations value for a tile based on its filename\n \"\"\"\n tilename = os.path.splitext(os.path.basename(tilepath))[0]\n stripname = '_'.join(tilename.split('_')[-4:-2])\n rotation = rotationdf.loc[stripname].squeeze()\n return rotation\n\n\ndef copyrotateimage(srcpath, dstpath, rotate=False, deletesource=False):\n \"\"\"\n Copying with rotation: Copies a TIFF image from srcpath to dstpath,\n rotating the image by 180 degrees if specified.\n \"\"\"\n #Handles special case where source path and destination path are the same\n if srcpath==dstpath:\n if not rotate:\n #Then there's nothing to do\n return\n else:\n #Move file to temporary location before continuing\n srcpath = srcpath + str(uuid.uuid4())\n shutil.move(dstpath, srcpath)\n deletesource = True\n\n if not rotate:\n shutil.copy(srcpath, dstpath, follow_symlinks=True)\n else:\n driver = gdal.GetDriverByName('GTiff')\n tilefile = gdal.Open(srcpath)\n copyfile = driver.CreateCopy(dstpath, tilefile, strict=0)\n numbands = copyfile.RasterCount\n for bandnum in range(1, numbands+1):\n banddata = tilefile.GetRasterBand(bandnum).ReadAsArray()\n banddata = np.fliplr(np.flipud(banddata)) #180 deg rotation\n copyfile.GetRasterBand(bandnum).WriteArray(banddata)\n copyfile.FlushCache()\n copyfile = None\n tilefile = None\n\n if deletesource:\n os.remove(srcpath)\n\n\ndef reorderbands(srcpath, dstpath, bandlist, deletesource=False):\n \"\"\"\n Copies a TIFF image from srcpath to dstpath, reordering the bands.\n \"\"\"\n #Handles special case where source path and destination path are the same\n if srcpath==dstpath:\n #Move file to temporary location before continuing\n srcpath = srcpath + str(uuid.uuid4())\n shutil.move(dstpath, srcpath)\n deletesource = True\n\n driver = gdal.GetDriverByName('GTiff')\n tilefile = gdal.Open(srcpath)\n geotransform = tilefile.GetGeoTransform()\n projection = tilefile.GetProjection()\n numbands = len(bandlist)\n shape = tilefile.GetRasterBand(1).ReadAsArray().shape\n copyfile = driver.Create(dstpath, shape[1], shape[0],\n numbands, gdal.GDT_Byte)\n for bandnum in range(1, numbands+1):\n banddata = tilefile.GetRasterBand(bandlist[bandnum-1]).ReadAsArray()\n copyfile.GetRasterBand(bandnum).WriteArray(banddata)\n copyfile.SetGeoTransform(geotransform)\n copyfile.SetProjection(projection)\n copyfile.FlushCache()\n copyfile = None\n tilefile = None\n\n if deletesource:\n os.remove(srcpath)\n\n\ndef pretrain(args):\n \"\"\"\n Creates rotated versions of imagery used for training\n as well as raster label masks. Optical bands are re-ordered to\n mimic SAR bands.\n \"\"\"\n print('Pretrain')\n assert(args.sardir is not None and args.labeldir is not None and args.maskdir is not None and args.sarprocdir is not None)\n\n #Save local copy of rotation file\n if args.rotate:\n shutil.copy(args.rotationfile, args.rotationfilelocal, follow_symlinks=True)\n\n #Get paths to relevant files\n sarpaths = glob.glob(os.path.join(args.sardir, '*.tif'))\n sarpaths.sort()\n labelpaths = glob.glob(os.path.join(args.labeldir, '*.geojson'))\n labelpaths.sort()\n maskpaths = [os.path.join(args.maskdir, os.path.basename(sarpath)) for sarpath in sarpaths]\n sarprocpaths = [os.path.join(args.sarprocdir, os.path.basename(sarpath)) for sarpath in sarpaths]\n if args.opticaldir is not None:\n opticalpaths = glob.glob(os.path.join(args.opticaldir, '*.tif'))\n opticalpaths.sort()\n opticalprocpaths = [os.path.join(args.opticalprocdir, os.path.basename(opticalpath)) for opticalpath in opticalpaths]\n else:\n opticalpaths = [''] * len(sarpaths)\n opticalprocpaths = [''] * len(sarpaths)\n\n #Create empty folders to hold masks, processed SAR, & processed optical\n folders = [args.maskdir, args.sarprocdir]\n if args.opticalprocdir is not None:\n folders.append(args.opticalprocdir)\n for folder in folders:\n makeemptyfolder(folder)\n pathlib.Path(args.modeldir).mkdir(exist_ok=True)\n\n #Look up how to rotate masks and images, if enabled\n if args.rotate:\n assert(args.rotationfilelocal is not None)\n rotationdf = readrotationfile(args.rotationfilelocal)\n\n #Create masks, with optional rotation and optional size threshold\n #Also copy SAR and optical imagery to local folder, with optional rotation\n #Optical files are optionally modified to more closely resemble SAR\n #Also create Pandas dataframe of training data\n combodf = pd.DataFrame(columns=['opticalimage',\n 'sarimage',\n 'label',\n 'group'])\n ledge = 591550 #Approximate west edge of training data area\n redge = 596250 #Approximate east edge of training data area\n numgroups = 5\n reorganizeoptical = True\n for i, (sarpath, opticalpath, labelpath, maskpath, sarprocpath, opticalprocpath) in tqdm.tqdm(enumerate(zip(sarpaths, opticalpaths, labelpaths, maskpaths, sarprocpaths, opticalprocpaths)), total=len(sarpaths)):\n #Generate mask\n gdf = gpd.read_file(labelpath)\n if args.mintrainsize is not None:\n cut = gdf.area > float(args.mintrainsize)\n gdf = gdf.loc[cut]\n maskdata = sol.vector.mask.footprint_mask(\n df=gdf,\n reference_im=sarpath,\n out_file=maskpath\n )\n #Optionally rotate mask\n if args.rotate:\n rotationflag = lookuprotation(sarpath, rotationdf)\n else:\n rotationflag = 0\n if rotationflag==1:\n copyrotateimage(maskpath, maskpath, rotate=True)\n #Copy SAR and optical imagery, with optional rotation\n rotationflagbool = rotationflag == 1\n copyrotateimage(sarpath, sarprocpath, rotate=rotationflagbool)\n if args.opticaldir is not None:\n copyrotateimage(opticalpath, opticalprocpath,\n rotate=rotationflagbool)\n if reorganizeoptical:\n reorderbands(opticalprocpath, opticalprocpath, [3,1,1,2])\n\n #Assign the tile to one of a small number of groups, for setting\n #aside validation data (or for k-fold cross-validation, not used here).\n #Caveats: These groups slightly overlap each other. Also, they are\n #not of equal size.\n sarfile = gdal.Open(sarpath)\n sartransform = sarfile.GetGeoTransform()\n sarx = sartransform[0]\n groupnum = min(numgroups-1, max(0, math.floor((sarx-ledge) / (redge-ledge) * numgroups)))\n combodf = combodf.append({\n 'sarimage': sarprocpath,\n 'opticalimage': opticalprocpath,\n 'label': maskpath,\n 'group': groupnum}, ignore_index=True)\n\n #Optionally end loop early (for debugging purposes)\n if args.earlycutoff is not None:\n if i >= int(args.earlycutoff) - 1:\n break\n\n #Write reference CSVs for training\n for i in range(numgroups+1):\n print( '%i: %i' % (i, len(combodf[combodf['group']==i])))\n validationgroup = numgroups - 1\n traindf = combodf[combodf['group'] != validationgroup]\n validdf = combodf[combodf['group'] == validationgroup]\n sartraindf = traindf.loc[:, ['sarimage', 'label']].rename(columns={'sarimage':'image'})\n sarvaliddf = validdf.loc[:, ['sarimage', 'label']].rename(columns={'sarimage':'image'})\n opticaltraindf = traindf.loc[:, ['opticalimage', 'label']].rename(columns={'opticalimage':'image'})\n opticalvaliddf = validdf.loc[:, ['opticalimage', 'label']].rename(columns={'opticalimage':'image'})\n sartraindf.to_csv(args.traincsv, index=False)\n sarvaliddf.to_csv(args.validcsv, index=False)\n opticaltraindf.to_csv(args.opticaltraincsv, index=False)\n opticalvaliddf.to_csv(args.opticalvalidcsv, index=False)\n\n\n#Custom model dictionaries, defined globally\nsar_dict = {\n 'model_name': 'unet11',\n 'weight_path': None,\n 'weight_url': None,\n 'arch': model.UNet11\n}\n\noptical_dict = {\n 'model_name': 'unet11',\n 'weight_path': None,\n 'weight_url': None,\n 'arch': model.UNet11\n}\n\n\ndef defineyaml():\n #YAML\n yamlcontents = \"\"\"\nmodel_name: unet11\n\nmodel_path:\ntrain: true\ninfer: true\n\npretrained:\nnn_framework: torch\nbatch_size: 8\n\ndata_specs:\n width: 512\n height: 512\n dtype:\n image_type: 32bit\n rescale: false\n rescale_minima: auto\n rescale_maxima: auto\n channels: 4\n label_type: mask\n is_categorical: false\n mask_channels: 1\n val_holdout_frac:\n data_workers:\n\ntraining_data_csv: '$TRAINCSV'\nvalidation_data_csv: '$VALIDCSV'\ninference_data_csv: '$TESTCSV'\n\ntraining_augmentation:\n augmentations:\n HorizontalFlip:\n p: 0.5\n RandomCrop:\n height: 512\n width: 512\n p: 1.0\n Normalize:\n mean:\n - 0.5\n std:\n - 0.125\n max_pixel_value: 255.0\n p: 1.0\n p: 1.0\n shuffle: true\nvalidation_augmentation:\n augmentations:\n CenterCrop:\n height: 512\n width: 512\n p: 1.0\n Normalize:\n mean:\n - 0.5\n std:\n - 0.125\n max_pixel_value: 255.0\n p: 1.0\n p: 1.0\ninference_augmentation:\n augmentations:\n Normalize:\n mean:\n - 0.5\n std:\n - 0.125\n max_pixel_value: 255.0\n p: 1.0\n p: 1.0\ntraining:\n epochs: 50\n steps_per_epoch:\n optimizer: AdamW\n lr: 1e-4\n opt_args:\n loss:\n dice:\n logits: true\n focal:\n logits: true\n loss_weights:\n dice: 1.0\n focal: 10.0\n metrics:\n training:\n validation:\n checkpoint_frequency: 10\n callbacks:\n model_checkpoint:\n filepath: '$MODELDIR/best.model'\n monitor: val_loss\n model_dest_path: '$MODELDIR/last.model'\n verbose: true\n\ninference:\n window_step_size_x: 512\n window_step_size_y: 512\n output_dir: '$TESTOUTDIR'\n\"\"\"\n if args.traincsv is not None:\n yamlcontents = yamlcontents.replace('$TRAINCSV', args.traincsv)\n if args.validcsv is not None:\n yamlcontents = yamlcontents.replace('$VALIDCSV', args.validcsv)\n if args.testcsv is not None:\n yamlcontents = yamlcontents.replace('$TESTCSV', args.testcsv)\n if args.modeldir is not None:\n yamlcontents = yamlcontents.replace('$MODELDIR', args.modeldir)\n if args.testoutdir is not None:\n yamlcontents = yamlcontents.replace('$TESTOUTDIR', args.testoutdir)\n yamlfile = open(args.yamlpath, 'w')\n yamlfile.write(yamlcontents)\n yamlfile.close()\n\n\n\ndef defineopticalyaml():\n #Optical YAML\n yamlcontents = \"\"\"\nmodel_name: unet11\n\nmodel_path:\ntrain: true\ninfer: false\n\npretrained: false\nnn_framework: torch\nbatch_size: 8\n\ndata_specs:\n width: 512\n height: 512\n dtype:\n image_type: 32bit\n rescale: false\n rescale_minima: auto\n rescale_maxima: auto\n channels: 4\n label_type: mask\n is_categorical: false\n mask_channels: 1\n val_holdout_frac:\n data_workers:\n\ntraining_data_csv: '$OPTICALTRAINCSV'\nvalidation_data_csv: '$OPTICALVALIDCSV'\ninference_data_csv:\n\ntraining_augmentation:\n augmentations:\n HorizontalFlip:\n p: 0.5\n RandomRotate90:\n p: 1.0\n RandomCrop:\n height: 512\n width: 512\n p: 1.0\n Normalize:\n mean:\n - 0.5\n std:\n - 0.125\n max_pixel_value: 255.0\n p: 1.0\n p: 1.0\n shuffle: true\nvalidation_augmentation:\n augmentations:\n CenterCrop:\n height: 512\n width: 512\n p: 1.0\n Normalize:\n mean:\n - 0.5\n std:\n - 0.125\n max_pixel_value: 255.0\n p: 1.0\n p: 1.0\ninference_augmentation:\n augmentations:\n Normalize:\n mean:\n - 0.5\n std:\n - 0.125\n max_pixel_value: 255.0\n p: 1.0\n p: 1.0\ntraining:\n epochs: 150\n steps_per_epoch:\n optimizer: AdamW\n lr: 1e-4\n opt_args:\n loss:\n dice:\n logits: true\n focal:\n logits: true\n loss_weights:\n dice: 1.0\n focal: 10.0\n metrics:\n training:\n validation:\n checkpoint_frequency: 10\n callbacks:\n model_checkpoint:\n filepath: '$MODELDIR/opticalbest.model'\n monitor: val_loss\n model_dest_path: '$MODELDIR/opticallast.model'\n verbose: true\n\"\"\"\n yamlcontents = yamlcontents.replace('$OPTICALTRAINCSV',\n args.opticaltraincsv)\n yamlcontents = yamlcontents.replace('$OPTICALVALIDCSV',\n args.opticalvalidcsv)\n yamlcontents = yamlcontents.replace('$MODELDIR', args.modeldir)\n yamlfile = open(args.opticalyamlpath, 'w')\n yamlfile.write(yamlcontents)\n yamlfile.close()\n\n\ndef train(args):\n \"\"\"\n Trains the model.\n \"\"\"\n print('Train')\n \n #Create YAML files\n defineyaml()\n defineopticalyaml()\n\n #Optionally start by training on optical imagery for transfer learning\n if args.transferoptical:\n print('Training on Optical: Start')\n config = sol.utils.config.parse(args.opticalyamlpath)\n trainer = sol.nets.train.Trainer(config,\n custom_model_dict=optical_dict)\n trainer.train()\n\n #Select best-performing optical imagery model\n if not args.uselastmodel:\n modelfiles = sorted(glob.glob(os.path.join(args.modeldir,\n 'opticalbest*.model')))\n timestamps = [os.path.getmtime(modelfile)\n for modelfile in modelfiles]\n latestindex = timestamps.index(max(timestamps))\n modelfile = modelfiles[latestindex]\n else:\n modelfile = os.path.join(args.modeldir, 'opticallast.model')\n print(modelfile)\n destfile = os.path.join(args.modeldir, 'optical.model')\n shutil.copyfile(modelfile, destfile, follow_symlinks=True)\n print('Training on Optical: End')\n\n #Instantiate trainer and train on SAR imagery\n config = sol.utils.config.parse(args.yamlpath)\n if args.transferoptical:\n config['pretrained'] = True\n sar_dict['weight_path'] = os.path.join(args.modeldir, 'optical.model')\n else:\n config['pretrained'] = False\n trainer = sol.nets.train.Trainer(config, custom_model_dict=sar_dict)\n trainer.train()\n\n\ndef pretest(args):\n \"\"\"\n Create rotated versions of imagery used for testing.\n \"\"\"\n print('Pretest')\n assert(args.testdir is not None and args.testprocdir is not None)\n\n #Get paths to relevant files\n sarpaths = glob.glob(os.path.join(args.testdir, '*.tif'))\n sarpaths.sort()\n sarprocpaths = [os.path.join(args.testprocdir, os.path.basename(sarpath)) for sarpath in sarpaths]\n\n #Create empty folder to hold processed test SAR images\n makeemptyfolder(args.testprocdir)\n\n #Look up how to rotate masks and images, if enabled\n if args.rotate:\n assert(args.rotationfilelocal is not None)\n rotationdf = readrotationfile(args.rotationfilelocal)\n\n #Copy SAR test images to local folder, with optional rotation\n #Also create Pandas dataframe of testing data\n testdf = pd.DataFrame(columns=['image'])\n for i, (sarpath, sarprocpath) in tqdm.tqdm(enumerate(zip(sarpaths, sarprocpaths)), total=len(sarpaths)):\n #Copy SAR test imagery, with optional rotation\n if args.rotate:\n rotationflag = lookuprotation(sarpath, rotationdf)\n else:\n rotationflag = 0\n rotationflagbool = rotationflag == 1\n copyrotateimage(sarpath, sarprocpath, rotate=rotationflagbool)\n\n #Add row to Pandas dataframe of testing data\n testdf = testdf.append({\n 'image': sarprocpath\n }, ignore_index=True)\n\n #Optionally end loop early (for debugging purposes)\n if args.earlycutoff is not None:\n if i >= int(args.earlycutoff) - 1:\n break\n\n #Write reference CSVs for testing\n testdf.to_csv(args.testcsv, index=False)\n\ndef test(args):\n \"\"\"\n Uses the trained model to conduct inference on the test dataset.\n Outputs are a continuously-varying pixel map, a binary pixel map,\n and a CSV file of vector labels for evaluation.\n \"\"\"\n print('Test')\n\n #Overwrite last model with best model\n modelfiles = sorted(glob.glob(os.path.join(args.modeldir, 'best*.model')))\n timestamps = [os.path.getmtime(modelfile) for modelfile in modelfiles]\n latestindex = timestamps.index(max(timestamps))\n modelfile = modelfiles[latestindex]\n print(modelfile)\n if not args.uselastmodel:\n destfile = os.path.join(args.modeldir, 'last.model')\n shutil.copyfile(modelfile, destfile, follow_symlinks=True)\n\n #Create empty folders to hold various inference outputs\n folders = [args.testoutdir, args.testbinarydir, args.testvectordir]\n for folder in folders:\n makeemptyfolder(folder)\n\n #Run inference on the test data\n config = sol.utils.config.parse(args.yamlpath)\n inferer = sol.nets.infer.Inferer(config, custom_model_dict=sar_dict)\n print('Start inference.')\n inferer()\n print('Finished inference.')\n\n #Binary and vector inference output\n driver = gdal.GetDriverByName('GTiff')\n firstfile = True\n sourcefolder = config['inference']['output_dir']\n sourcefiles = sorted(glob.glob(os.path.join(sourcefolder, '*')))\n if args.rotate:\n rotationdf = readrotationfile(args.rotationfilelocal)\n minbuildingsize = float(args.mintestsize) if args.mintestsize is not None else 0\n for sourcefile in tqdm.tqdm(sourcefiles, total=len(sourcefiles)):\n filename = os.path.basename(sourcefile)\n destfile = os.path.join(args.testbinarydir, filename)\n\n #Create binary array\n cutoff = 0.\n sourcedataorig = gdal.Open(sourcefile).ReadAsArray()\n sourcedata = np.zeros(np.shape(sourcedataorig), dtype='int')\n sourcedata[np.where(sourcedataorig > cutoff)] = 255\n sourcedata[np.where(sourcedataorig <= cutoff)] = 0\n\n #Remove small buildings\n if minbuildingsize>0:\n regionlabels, regioncount = skimage.measure.label(sourcedata, background=0, connectivity=1, return_num=True)\n regionproperties = skimage.measure.regionprops(regionlabels)\n for bl in range(regioncount):\n if regionproperties[bl].area < minbuildingsize:\n sourcedata[regionlabels == bl+1] = 0\n\n #Save binary image\n destdata = driver.Create(destfile, sourcedata.shape[1], sourcedata.shape[0], 1, gdal.GDT_Byte)\n destdata.GetRasterBand(1).WriteArray(sourcedata)\n del destdata\n\n #Rotate source data back to real-world orientation before vectorizing\n if args.rotate:\n rotationflag = lookuprotation(filename, rotationdf)\n else:\n rotationflag = 0\n rotationflagbool = rotationflag == 1\n if rotationflag:\n sourcedatarotated = np.fliplr(np.flipud(sourcedata))\n else:\n sourcedatarotated = sourcedata\n\n #Save vector file (CSV)\n vectorname = '.'.join(filename.split('.')[:-1]) + '.csv'\n vectorfile = os.path.join(args.testvectordir, vectorname)\n referencefile = os.path.join(args.testprocdir, filename)\n vectordata = sol.vector.mask.mask_to_poly_geojson(\n sourcedatarotated,\n output_path=vectorfile,\n output_type='csv',\n min_area=0,\n bg_threshold=128,\n do_transform=False,\n simplify=True\n )\n\n #Add to the cumulative inference CSV file\n tilename = '_'.join(os.path.splitext(filename)[0].split('_')[-4:])\n csvaddition = pd.DataFrame({'ImageId': tilename,\n 'BuildingId': 0,\n 'PolygonWKT_Pix': vectordata['geometry'],\n 'Confidence': 1\n })\n csvaddition['BuildingId'] = range(len(csvaddition))\n if firstfile:\n proposalcsv = csvaddition\n firstfile = False\n else:\n proposalcsv = proposalcsv.append(csvaddition)\n\n proposalcsv.to_csv(args.outputcsv, index=False)\n\n\ndef evaluation(args):\n \"\"\"\n Compares infered test data vector labels to ground truth.\n \"\"\"\n truthpath = os.path.join(os.path.dirname(args.outputcsv), 'SN6_Test_Public_AOI_11_Rotterdam_Buildings.csv')\n proposalpath = args.outputcsv\n minevalsize = 80\n\n evaluator = sol.eval.base.Evaluator(truthpath)\n evaluator.load_proposal(proposalpath, proposalCSV=True, conf_field_list=[])\n report = evaluator.eval_iou_spacenet_csv(miniou=0.5, min_area=minevalsize)\n\n tp = 0\n fp = 0\n fn = 0\n for entry in report:\n tp += entry['TruePos']\n fp += entry['FalsePos']\n fn += entry['FalseNeg']\n f1score = (2*tp) / (2*tp + fp + fn)\n print('Vector F1: {}'.format(f1score))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='SpaceNet 6 Baseline Algorithm')\n #Which operations to carry out\n parser.add_argument('--pretrain', action='store_true',\n help='Whether to format training data')\n parser.add_argument('--train', action='store_true',\n help='Whether to train model')\n parser.add_argument('--pretest', action='store_true',\n help='Whether to format testing data')\n parser.add_argument('--test', action='store_true',\n help='Whether to test model')\n parser.add_argument('--eval', action='store_true',\n help='Whether to evaluate test output')\n #Training: Input file paths\n parser.add_argument('--sardir',\n help='Folder of SAR training imagery files')\n parser.add_argument('--opticaldir',\n help='Folder of optical imagery files')\n parser.add_argument('--labeldir',\n help='Folder of building footprint vector files')\n parser.add_argument('--rotationfile',\n help='File of data acquisition directions')\n #Training: Preprocessed file paths\n parser.add_argument('--rotationfilelocal',\n help='Where to save a copy of directions file')\n parser.add_argument('--maskdir',\n help='Where to save building footprint masks')\n parser.add_argument('--sarprocdir',\n help='Where to save preprocessed SAR training files')\n parser.add_argument('--opticalprocdir',\n help='Where to save preprocessed optical image files')\n #Training and inference: YAML and Reference CSV file paths\n parser.add_argument('--traincsv',\n help='Where to save reference CSV of training data')\n parser.add_argument('--validcsv',\n help='Where to save reference CSV of validation data')\n parser.add_argument('--opticaltraincsv',\n help='Where to save CSV of optical training data')\n parser.add_argument('--opticalvalidcsv',\n help='Where to save CSV of optical validation data')\n parser.add_argument('--testcsv',\n help='Where to save reference CSV of testing data')\n parser.add_argument('--yamlpath',\n help='Where to save YAML file')\n parser.add_argument('--opticalyamlpath',\n help='Where to save transfer learning YAML file')\n #Training and inference: Model weights file path\n parser.add_argument('--modeldir',\n help='Where to save model weights')\n #Inference (testing) file paths\n parser.add_argument('--testdir',\n help='Folder of SAR testing imagery files')\n parser.add_argument('--testprocdir',\n help='Where to save preprocessed SAR testing files')\n parser.add_argument('--testoutdir',\n help='Where to save test continuous segmentation maps')\n parser.add_argument('--testbinarydir',\n help='Where to save test binary segmentation maps')\n parser.add_argument('--testvectordir',\n help='Where to save test vector label output')\n parser.add_argument('--outputcsv',\n help='Where to save labels inferred from test data')\n #Algorithm settings\n parser.add_argument('--rotate', action='store_true',\n help='Rotate tiles to align imaging direction')\n parser.add_argument('--transferoptical', action='store_true',\n help='Train model on optical before training on SAR')\n parser.add_argument('--mintrainsize',\n help='Minimum building size (m^2) for training')\n parser.add_argument('--mintestsize',\n help='Minimum size to output during testing')\n parser.add_argument('--uselastmodel', action='store_true',\n help='Do not overwrite last model with best model')\n parser.add_argument('--earlycutoff',\n help='Limit tiles used, for debugging purposes')\n args = parser.parse_args(sys.argv[1:])\n\n if args.pretrain:\n pretrain(args)\n if args.train:\n train(args)\n if args.pretest:\n pretest(args)\n if args.test:\n test(args)\n if args.eval:\n evaluation(args)\n"
] | [
[
"numpy.flipud",
"pandas.read_csv",
"pandas.DataFrame",
"numpy.shape",
"numpy.where"
]
] |
anooptp/maml | [
"fdd95f3d60c9281d871d89b25b073e87b6ba4e52"
] | [
"maml/apps/pes/tests/test_gap.py"
] | [
"# coding: utf-8\n# Copyright (c) Materials Virtual Lab\n# Distributed under the terms of the BSD License.\n\nimport os\nimport shutil\nimport unittest\nimport tempfile\n\nimport numpy as np\nfrom pymatgen.core import Structure\nfrom monty.os.path import which\nfrom monty.serialization import loadfn\nfrom maml.apps.pes import GAPotential\n\nCWD = os.getcwd()\ntest_datapool = loadfn(os.path.join(os.path.abspath(os.path.dirname(__file__)), \"datapool.json\"))\n\n\nclass GAPotentialTest(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.this_dir = os.path.dirname(os.path.abspath(__file__))\n cls.test_dir = tempfile.mkdtemp()\n os.chdir(cls.test_dir)\n\n @classmethod\n def tearDownClass(cls):\n os.chdir(CWD)\n shutil.rmtree(cls.test_dir)\n\n def setUp(self):\n self.potential = GAPotential(name=\"test\")\n self.test_pool = test_datapool\n self.test_structures = []\n self.test_energies = []\n self.test_forces = []\n self.test_stresses = []\n for d in self.test_pool:\n self.test_structures.append(d[\"structure\"])\n self.test_energies.append(d[\"outputs\"][\"energy\"])\n self.test_forces.append(d[\"outputs\"][\"forces\"])\n self.test_stresses.append(d[\"outputs\"][\"virial_stress\"])\n self.test_struct = d[\"structure\"]\n\n def test_write_read_cfgs(self):\n self.potential.write_cfgs(\"test.xyz\", cfg_pool=self.test_pool)\n datapool, df = self.potential.read_cfgs(\"test.xyz\")\n self.assertEqual(len(self.test_pool), len(datapool))\n for data1, data2 in zip(self.test_pool, datapool):\n struct1 = data1[\"structure\"]\n struct2 = Structure.from_dict(data2[\"structure\"])\n self.assertTrue(struct1 == struct2)\n energy1 = data1[\"outputs\"][\"energy\"]\n energy2 = data2[\"outputs\"][\"energy\"]\n self.assertAlmostEqual(energy1, energy2)\n forces1 = np.array(data1[\"outputs\"][\"forces\"])\n forces2 = data2[\"outputs\"][\"forces\"]\n np.testing.assert_array_almost_equal(forces1, forces2)\n stress1 = np.array(data1[\"outputs\"][\"virial_stress\"])\n stress2 = data2[\"outputs\"][\"virial_stress\"]\n np.testing.assert_array_almost_equal(stress1, stress2)\n\n @unittest.skipIf(not which(\"gap_fit\"), \"No QUIP cmd found.\")\n def test_train(self):\n self.potential.train(\n train_structures=self.test_structures,\n train_energies=self.test_energies,\n train_forces=self.test_forces,\n train_stresses=self.test_stresses,\n )\n self.assertTrue(self.potential.param)\n\n @unittest.skipIf(not which(\"quip\"), \"No QUIP cmd found.\")\n def test_evaluate(self):\n self.potential.train(\n train_structures=self.test_structures,\n train_energies=self.test_energies,\n train_forces=self.test_forces,\n train_stresses=self.test_stresses,\n )\n df_orig, df_tar = self.potential.evaluate(\n test_structures=self.test_structures,\n test_energies=self.test_energies,\n test_forces=self.test_forces,\n test_stresses=self.test_stresses,\n )\n self.assertEqual(df_orig.shape[0], df_tar.shape[0])\n\n @unittest.skipIf(not which(\"gap_fit\"), \"No QUIP cmd found.\")\n @unittest.skipIf(not which(\"lmp_serial\"), \"No LAMMPS cmd found.\")\n def test_predict(self):\n self.potential.train(\n train_structures=self.test_structures,\n train_energies=self.test_energies,\n train_forces=self.test_forces,\n train_stresses=self.test_stresses,\n )\n energy, forces, stress = self.potential.predict_efs(self.test_struct)\n self.assertEqual(len(forces), len(self.test_struct))\n self.assertEqual(len(stress), 6)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] | [
[
"numpy.array",
"numpy.testing.assert_array_almost_equal"
]
] |
zheng-da/pyHGT | [
"b654495053c82edcc8a7e1e00b7873ac93e6e59d"
] | [
"conv.py"
] | [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch_geometric.nn import GCNConv, GATConv\nfrom torch_geometric.nn.conv import MessagePassing\nfrom torch_geometric.nn.inits import glorot, uniform\nfrom torch_geometric.utils import softmax\nimport math\n\nclass HGTConv(MessagePassing):\n def __init__(self, in_dim, out_dim, num_types, num_relations, n_heads, dropout = 0.2, **kwargs):\n super(HGTConv, self).__init__(aggr='add', **kwargs)\n\n self.in_dim = in_dim\n self.out_dim = out_dim\n self.num_types = num_types\n self.num_relations = num_relations\n self.total_rel = num_types * num_relations * num_types\n self.n_heads = n_heads\n self.d_k = out_dim // n_heads\n self.sqrt_dk = math.sqrt(self.d_k)\n self.att = None\n \n self.k_linears = nn.ModuleList()\n self.q_linears = nn.ModuleList()\n self.v_linears = nn.ModuleList()\n self.a_linears = nn.ModuleList()\n \n for t in range(num_types):\n self.k_linears.append(nn.Linear(in_dim, out_dim))\n self.q_linears.append(nn.Linear(in_dim, out_dim))\n self.v_linears.append(nn.Linear(in_dim, out_dim))\n self.a_linears.append(nn.Linear(out_dim, out_dim))\n \n '''\n TODO: make relation_pri smaller, as not all <st, rt, tt> pair exist in meta relation list.\n '''\n self.relation_pri = nn.Parameter(torch.ones(num_types, num_relations, num_types, self.n_heads))\n self.relation_att = nn.Parameter(torch.Tensor(num_relations, n_heads, self.d_k, self.d_k))\n self.relation_msg = nn.Parameter(torch.Tensor(num_relations, n_heads, self.d_k, self.d_k))\n self.skip = nn.Parameter(torch.ones(num_types))\n self.drop = nn.Dropout(dropout)\n self.emb = RelTemporalEncoding(in_dim)\n \n glorot(self.relation_att)\n glorot(self.relation_msg)\n \n def forward(self, node_inp, node_type, edge_index, edge_type, edge_time):\n return self.propagate(edge_index, node_inp=node_inp, node_type=node_type, \\\n edge_type=edge_type, edge_time = edge_time)\n\n def message(self, edge_index_i, node_inp_i, node_inp_j, node_type_i, node_type_j, edge_type, edge_time):\n '''\n j: source, i: target; <j, i>\n '''\n data_size = edge_index_i.size(0)\n '''\n Create Attention and Message tensor beforehand.\n '''\n res_att = torch.zeros(data_size, self.n_heads).to(node_inp_i.device)\n res_msg = torch.zeros(data_size, self.n_heads, self.d_k).to(node_inp_i.device)\n \n for source_type in range(self.num_types):\n sb = (node_type_j == int(source_type))\n k_linear = self.k_linears[source_type]\n v_linear = self.v_linears[source_type] \n for target_type in range(self.num_types):\n tb = (node_type_i == int(target_type)) & sb\n q_linear = self.q_linears[target_type]\n for relation_type in range(self.num_relations):\n '''\n idx is all the edges with meta relation <source_type, relation_type, target_type>\n '''\n idx = (edge_type == int(relation_type)) & tb\n if idx.sum() == 0:\n continue\n '''\n Get the corresponding input node representations by idx.\n Add tempotal encoding to source representation (j)\n '''\n target_node_vec = node_inp_i[idx]\n source_node_vec = self.emb(node_inp_j[idx], edge_time[idx])\n\n '''\n Step 1: Heterogeneous Mutual Attention\n '''\n q_mat = q_linear(target_node_vec).view(-1, self.n_heads, self.d_k)\n k_mat = k_linear(source_node_vec).view(-1, self.n_heads, self.d_k)\n k_mat = torch.bmm(k_mat.transpose(1,0), self.relation_att[relation_type]).transpose(1,0)\n res_att[idx] = (q_mat * k_mat).sum(dim=-1) * \\\n self.relation_pri[target_type][relation_type][source_type] / self.sqrt_dk\n '''\n Step 2: Heterogeneous Message Passing\n '''\n v_mat = v_linear(source_node_vec).view(-1, self.n_heads, self.d_k)\n res_msg[idx] = torch.bmm(v_mat.transpose(1,0), self.relation_msg[relation_type]).transpose(1,0) \n '''\n Softmax based on target node's id (edge_index_i). Store attention value in self.att for later visualization.\n '''\n self.att = softmax(res_att, edge_index_i)\n res = res_msg * self.att.view(-1, self.n_heads, 1)\n del res_att, res_msg\n return res.view(-1, self.out_dim)\n\n\n def update(self, aggr_out, node_inp, node_type):\n '''\n Step 3: Target-specific Aggregation\n x = W[node_type] * gelu(Agg(x)) + x\n '''\n aggr_out = F.gelu(aggr_out)\n res = torch.zeros(aggr_out.size(0), self.out_dim).to(node_inp.device)\n for target_type in range(self.num_types):\n idx = (node_type == int(target_type))\n if idx.sum() == 0:\n continue\n '''\n Add skip connection with learnable weight self.skip[t_id]\n '''\n alpha = F.sigmoid(self.skip[target_type])\n res[idx] = self.a_linears[target_type](aggr_out[idx]) * alpha + node_inp[idx] * (1 - alpha)\n return self.drop(res)\n\n def __repr__(self):\n return '{}(in_dim={}, out_dim={}, num_types={}, num_types={})'.format(\n self.__class__.__name__, self.in_dim, self.out_dim,\n self.num_types, self.num_relations)\n\n\nclass RelTemporalEncoding(nn.Module):\n '''\n Implement the Temporal Encoding (Sinusoid) function.\n '''\n def __init__(self, n_hid, max_len = 240, dropout = 0.2):\n super(RelTemporalEncoding, self).__init__()\n self.drop = nn.Dropout(dropout)\n position = torch.arange(0., max_len).unsqueeze(1)\n div_term = 1 / (10000 ** (torch.arange(0., n_hid * 2, 2.)) / n_hid / 2)\n self.emb = nn.Embedding(max_len, n_hid * 2)\n self.emb.weight.data[:, 0::2] = torch.sin(position * div_term) / math.sqrt(n_hid)\n self.emb.weight.data[:, 1::2] = torch.cos(position * div_term) / math.sqrt(n_hid)\n self.emb.requires_grad = False\n self.lin = nn.Linear(n_hid * 2, n_hid)\n def forward(self, x, t):\n return x + self.lin(self.drop(self.emb(t)))\n \n \n \nclass GeneralConv(nn.Module):\n def __init__(self, conv_name, in_hid, out_hid, num_types, num_relations, n_heads, dropout):\n super(GeneralConv, self).__init__()\n self.conv_name = conv_name\n if self.conv_name == 'hgt':\n self.base_conv = HGTConv(in_hid, out_hid, num_types, num_relations, n_heads, dropout)\n elif self.conv_name == 'gcn':\n self.base_conv = GCNConv(in_hid, out_hid)\n elif self.conv_name == 'gat':\n self.base_conv = GATConv(in_hid, out_hid // n_heads, heads=n_heads)\n def forward(self, meta_xs, node_type, edge_index, edge_type, edge_time):\n if self.conv_name == 'hgt':\n return self.base_conv(meta_xs, node_type, edge_index, edge_type, edge_time)\n elif self.conv_name == 'gcn':\n return self.base_conv(meta_xs, edge_index)\n elif self.conv_name == 'gat':\n return self.base_conv(meta_xs, edge_index)\n \n \n"
] | [
[
"torch.ones",
"torch.nn.Linear",
"torch.nn.functional.sigmoid",
"torch.cos",
"torch.nn.Embedding",
"torch.sin",
"torch.arange",
"torch.nn.ModuleList",
"torch.zeros",
"torch.nn.Dropout",
"torch.Tensor",
"torch.nn.functional.gelu"
]
] |
cparrarojas/epidemic-inference | [
"598e14bc434b846c0fb5f53f70db131d3928122d"
] | [
"app.py"
] | [
"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport pandas as pd\nimport plotly.graph_objs as go\n\nimport matplotlib\nfrom matplotlib import cm\nimport numpy as np\n\nlinecolours = ['rgba(0,114,178,1.)', 'rgba(230,159,0,1.)']\n\nmagma_cmap = cm.get_cmap('magma')\n\nmagma_rgb = []\n\nnorm = matplotlib.colors.Normalize(vmin=0, vmax=255)\n\nfor i in range(0, 255):\n k = matplotlib.colors.colorConverter.to_rgb(magma_cmap(norm(i)))\n magma_rgb.append(k)\n\ndef matplotlib_to_plotly(cmap, pl_entries):\n h = 1.0/(pl_entries-1)\n pl_colorscale = []\n\n for k in range(pl_entries):\n C = list(map(np.uint8, np.array(cmap(k*h)[:3])*255))\n pl_colorscale.append([k*h, 'rgb'+str((C[0], C[1], C[2]))])\n\n return pl_colorscale\n\nmagma = matplotlib_to_plotly(magma_cmap, 255)\n\napp = dash.Dash()\n\ndf = pd.read_csv('app_data.csv')\n\ndf_like = pd.read_csv('likelihood.csv')\n\ndata_ebov = pd.read_csv('https://raw.githubusercontent.com/calthaus/Ebola/master/DRC%20(GitHub%202018)/Ebola_outbreak_DRC2018_data.csv')['Cumulative'].values\n\nbest_params = [df.iloc[-1]['beta'], df.iloc[-1]['k']]\n\nvariables = ['cumulative', 'E', 'I']\nlabels = ['cumulative incidence', 'exposed individuals', 'infectious individuals']\n\napp.layout = html.Div([\nhtml.Div(children=[\n html.H1(children='2018 Ebola outbreak in the Democratic Republic of Congo')]),\nhtml.Div([\n#\n html.Div([\n dcc.Dropdown(\n id='variable',\n options=[{'label': labels[i], 'value': j} for i, j in enumerate(variables)],\n value='cumulative'\n ),\n ],\n style={'width': '49%', 'display': 'inline-block'}),\n ], style={\n 'borderBottom': 'thin lightgrey solid',\n 'backgroundColor': 'rgb(250, 250, 250)',\n 'padding': '10px 5px'\n }),\n\n html.Div([\n dcc.Graph(\n id='landscape',\n hoverData={'points': [{'x': best_params[0], 'y': best_params[1]}]},\n figure={\n 'data': [go.Scatter(\n x=df_like['beta'],\n y=df_like['k'],\n text=df_like['likelihood'],\n #customdata=dff[dff['Indicator Name'] == yaxis_column_name]['Country Name'],\n mode='markers',\n marker={\n 'size': 18,\n 'opacity': 0.8,\n #'line': {'width': 0.5, 'color': 'white'},\n 'color': df_like['likelihood'],\n 'colorscale': magma\n }\n )],\n 'layout': go.Layout(\n title='',\n titlefont=dict(\n family='Old Standard TT, serif',\n size=35\n ),\n xaxis={\n 'title': 'beta',\n 'type': 'linear',\n 'titlefont' : dict(\n family='Old Standard TT, serif',\n size=25\n ),\n 'automargin': True,\n 'fixedrange': True\n },\n yaxis={\n 'title': 'k',\n 'type': 'linear',\n 'titlefont' : dict(\n family='Old Standard TT, serif',\n size=25\n ),\n 'automargin': True,\n 'fixedrange': True\n },\n margin={'l': 40, 'b': 30, 't': 60, 'r': 0},\n height=800,\n hovermode='closest',\n annotations=[{\n 'x': 0.5, 'y': 1., 'xanchor': 'center', 'yanchor': 'bottom',\n 'xref': 'paper', 'yref': 'paper', 'showarrow': False,\n 'align': 'left', 'bgcolor': 'rgba(255, 255, 255, 1.)',\n 'text': 'likelihood', 'font': dict(color = \"black\", size = 35, family='Old Standard TT, serif')\n }]\n )\n }\n )\n ], style={'width': '45%', 'display': 'inline-block', 'padding': '0 20'}),\n html.Div([\n dcc.Graph(id='time-series'),\n dcc.Graph(id='R_t'),\n ], style={'display': 'inline-block', 'width': '45%'})#,\n])\n\ndef create_time_series(dff, variable, title):\n if variable == 'R_t':\n xtitle = 'days since 5 April 2018'\n xticklabels = True,\n thedata = [go.Scatter(\n x=dff['time'],\n y=dff[variable],\n mode='lines',\n line=dict(width=1.5, color=linecolours[0]),\n showlegend=False,\n hoverinfo='x+y'\n ),\n go.Scatter(\n x=dff['time'],\n y=np.ones(len(dff['time'])),\n mode='lines',\n line=dict(width=1.5, color=linecolours[1], dash='dash'),\n showlegend=False,\n hoverinfo='x+y'\n )]\n else:\n xtitle = ''\n xticklabels = False,\n thedata = [go.Scatter(\n x=dff['time'],\n y=dff[variable + ' m'],\n mode='lines',\n line=dict(width=1.5, color=linecolours[0]),\n showlegend=False,\n hoverinfo='x+y'\n ),\n go.Scatter(\n x=dff['time'],\n y=dff[variable + ' p'],\n mode='lines',\n line=dict(width=1.5, color=linecolours[0]),\n showlegend=False,\n fill='tonexty',\n hoverinfo='x+y'\n )]\n if variable=='cumulative':\n thedata.append(go.Scatter(\n x=dff['time'][:len(data_ebov)],\n y=data_ebov,\n name='data',\n mode='markers',\n marker=dict(size=10,color=linecolours[1], opacity=0.8),\n showlegend=True,\n hoverinfo='x+y'\n ))\n return {\n 'data': thedata,\n 'layout': {\n 'height': 390,\n 'margin': {'l': 20, 'b': 30, 'r': 10, 't': 20},\n 'yaxis': {'type': 'linear', 'title': title, 'titlefont' : dict(family='Old Standard TT, serif', size=25), 'automargin': True, 'fixedrange': True},\n 'xaxis': {'type': 'linear', 'title': xtitle, 'titlefont' : dict(family='Old Standard TT, serif', size=25), 'showgrid': False, 'showticklabels': xticklabels, 'automargin': True, 'fixedrange': True},\n 'legend': dict(font=dict(family='Old Standard TT, serif', size=18, color='black'))\n }\n }\n\n\[email protected](\n dash.dependencies.Output('time-series', 'figure'),\n [dash.dependencies.Input('landscape', 'hoverData'),\n dash.dependencies.Input('variable', 'value')])#,\ndef update_x_timeseries(hoverData, variable):\n beta = hoverData['points'][0]['x']\n k = hoverData['points'][0]['y']\n dff = df[(df['beta'] == beta) & (df['k'] == k)]\n dff = dff[['time', variable, variable+' m', variable+' p']]\n if variable == 'cumulative':\n title = 'cumulative incidence'\n elif variable == 'E':\n title = 'exposed individuals'\n else:\n title = 'infectious individuals'\n return create_time_series(dff, variable, title)\n\n\[email protected](\n dash.dependencies.Output('R_t', 'figure'),\n [dash.dependencies.Input('landscape', 'hoverData')])\ndef update_y_timeseries(hoverData):\n beta = hoverData['points'][0]['x']\n k = hoverData['points'][0]['y']\n dff = df[(df['beta'] == beta) & (df['k'] == k)]\n dff = dff[['time', 'R_t']]\n return create_time_series(dff, 'R_t', 'reproductive number')\n\n\nif __name__ == '__main__':\n app.run_server()\n"
] | [
[
"pandas.read_csv",
"matplotlib.cm.get_cmap",
"matplotlib.colors.Normalize"
]
] |
DPBayes/DP-HMC-Neurips2021 | [
"ff8b828e8fc150ee59a3a271ef33dd75dd17bfe5"
] | [
"result.py"
] | [
"import metrics\nimport jax.numpy as np\nimport pandas as pd\n\nclass MCMCMetrics:\n def __init__(self, result, true_posterior):\n chains = result.get_final_chain()\n self.samples, self.dim, self.num_chains = chains.shape\n self.epsilon = result.epsilon\n self.delta = result.delta\n\n self.indiv_acceptance = result.accepts / result.iters\n self.indiv_clipped_r = result.clipped_r\n self.indiv_clipped_grad = result.clipped_grad\n\n # The denominator for each percentage is the same, so taking the\n # mean results in the aggregate acceptance of the chain, and the\n # same holds for the clip fractions\n self.agg_acceptance = np.mean(self.indiv_acceptance).item()\n self.agg_clipped_r = np.mean(self.indiv_clipped_r).item()\n self.agg_clipped_grad = np.mean(self.indiv_clipped_grad).item()\n\n self.r_clip_bound = getattr(result.params, \"r_clip\", np.nan)\n\n if self.samples > 1:\n self.indiv_mmd = metrics.mmd(chains, true_posterior)\n self.indiv_total_mean_error = metrics.total_mean_error(chains, true_posterior)\n\n agg_chain = result.get_aggregate_final_chain()\n self.agg_mmd = metrics.mmd(agg_chain, true_posterior)[0]\n self.agg_total_mean_error = metrics.total_mean_error(agg_chain, true_posterior)[0]\n self.agg_component_mean_error = metrics.component_mean_error(agg_chain, true_posterior)\n self.agg_component_mean_error = self.agg_component_mean_error.reshape((-1,))\n self.agg_component_var_error = metrics.component_var_error(agg_chain, true_posterior)\n self.agg_component_var_error = self.agg_component_var_error.reshape((-1,))\n\n self.r_hat = metrics.split_r_hat(chains)\n self.max_r_hat = np.max(self.r_hat).item()\n else:\n raise Exception(\"1 iterations chains not supported\")\n\n def as_pandas_row(self):\n data = {\n \"agg_acceptance\": [self.agg_acceptance],\n \"agg_component_mean_error\": [self.agg_component_mean_error],\n \"agg_total_mean_error\": [self.agg_total_mean_error],\n \"agg_component_var_error\": [self.agg_component_var_error],\n \"agg_mmd\": [self.agg_mmd],\n \"r_hat\": [self.r_hat],\n \"max_r_hat\": [self.max_r_hat],\n \"agg_clipped_r\": [self.agg_clipped_r],\n \"agg_clipped_grad\": [self.agg_clipped_grad],\n \"epsilon\": [self.epsilon],\n \"delta\": [self.delta],\n \"samples\": [self.samples],\n \"clip_bound\": [self.r_clip_bound]\n }\n return pd.DataFrame(data)\n\n def __str__(self):\n metric_str = lambda heading, value: \"{}: {}\".format(heading, value)\n metrics = [\n metric_str(\"Individual Acceptance\", self.indiv_acceptance),\n metric_str(\"Aggregate Acceptance\", self.agg_acceptance),\n \"\",\n metric_str(\"Indiv Total Mean Error\", self.indiv_total_mean_error),\n metric_str(\"Aggregate Componentwise Mean Error\", self.agg_component_mean_error),\n metric_str(\"Aggregate Total Mean Error\", self.agg_total_mean_error),\n metric_str(\"Aggregate Componentwise Variance Error\", self.agg_component_var_error),\n \"\",\n metric_str(\"Indiv MMD\", self.indiv_mmd),\n metric_str(\"Aggregate MMD\", self.agg_mmd),\n metric_str(\"R-hat\", self.r_hat),\n \"\",\n metric_str(\"Indiv Clipped R\", self.indiv_clipped_r),\n metric_str(\"Aggregate Clipped R\", self.agg_clipped_r),\n metric_str(\"Indiv Clipped Grad\", self.indiv_clipped_grad),\n metric_str(\"Aggregate Clipped Grad\", self.agg_clipped_grad),\n \"\",\n ]\n return \"\\n\".join(metrics)\n\ndef split_results(chain, accepts, clipped_r, clipped_grad, repeats, epsilon, delta, params):\n \"\"\"\n Split multiple repeats into separate MCMCResult objects.\n\n Parameters\n ----------\n chain : ndarray\n The resulting chain as an array of shape (num_samples, num_dimensions, num_chains * repeats).\n accepts : ndarray\n The number of accepts for each chain.\n clipped_r : ndarray\n The number of clipped log-likelihood ratios for each chain.\n clipped_grad : ndarray\n The number of clipped gradients for each chains.\n repeats : int\n The number of repeats.\n epsilon : float\n delta : float\n params : object\n Parameters of the algorithm that produced the result.\n\n Returns\n -------\n MCMCResult or list of MCMCResult\n If `repeats` is 1, return a single MCMCResult, otherwise return\n a MCMCResult for each repeat as a list.\n \"\"\"\n n_iters, dim, chains = chain.shape\n chains = int(chains / repeats)\n\n r_val = [\n MCMCResult(\n chain[:, :, i*chains:i*chains+chains], accepts[i*chains:(i+1)*chains],\n clipped_r[i*chains:i*chains+chains], clipped_grad[i*chains:i*chains+chains],\n epsilon, delta, params\n )\n for i in range(repeats)\n ]\n if repeats == 1:\n return r_val[0]\n else:\n return r_val\n\nclass MCMCResult:\n \"\"\"\n Result of an MCMC run.\n\n Parameters\n ----------\n chain : ndarray\n The resulting chain as an array of shape (num_samples, num_dimensions, num_chains).\n accepts : ndarray\n The number of accepts for each chain.\n clipped_r : ndarray\n The number of clipped log-likelihood ratios for each chain.\n clipped_grad : ndarray\n The number of clipped gradients for each chains.\n epsilon : float\n delta : float\n params : object\n Parameters of the algorithm that produced the result.\n \"\"\"\n def __init__(self, chain, accepts, clipped_r, clipped_grad, epsilon, delta, params):\n n_iters, dim, chains = chain.shape\n self.iters = n_iters - 1\n self.accepts = accepts\n self.chain = chain\n self.clipped_r = clipped_r\n self.clipped_grad = clipped_grad\n self.epsilon = epsilon\n self.delta = delta\n self.params = params\n\n def compute_metrics(self, posterior):\n \"\"\"\n Compute evaluation metrics compared to a reference posterior.\n\n Parameters\n ----------\n posterior : ndarray\n The reference posterior as an array of shape (num_samples, num_dimensions).\n\n Returns\n -------\n MCMCMetrics\n \"\"\"\n return MCMCMetrics(self, posterior)\n\n def get_final_chain(self):\n \"\"\"\n Return each chain with the first half removed.\n \"\"\"\n burn_in = 0.5\n return self.chain[int((self.iters - 1) * (1 - burn_in)) + 1:, :, :]\n\n def get_aggregate_final_chain(self):\n \"\"\"\n Return the aggregate sample from all chains with the first half removed.\n \"\"\"\n chains = self.get_final_chain()\n agg_chain = np.stack((np.concatenate(np.transpose(chains, axes=(2, 0, 1)), axis=0),), axis=2)\n return agg_chain\n"
] | [
[
"pandas.DataFrame"
]
] |
soerenwolfers/scilog | [
"ca66a6a7b8d267c8f2998b2a935b35b8f95b7558"
] | [
"scilog/scilog.py"
] | [
"import timeit\nimport pickle\nimport os\nimport errno\nimport datetime\nimport shutil\nimport warnings\nimport traceback\nimport pstats\nimport io\nimport sys\nimport gc\nimport inspect\nimport importlib\nimport re\nimport pathlib\nimport types\nimport operator\nimport subprocess\nimport shlex\nimport json\nimport contextlib\nimport stat\nimport itertools\nimport ast\nimport builtins\nimport signal\nfrom collections import OrderedDict\nfrom string import Formatter\n\nimport numpy as np\nfrom matplotlib import pyplot\nfrom IPython.utils.capture import capture_output\n\nfrom swutil import sys_info, np_tools, plots, misc\nfrom swutil.validation import Positive, Integer, String, List, Tuple,Iterable\nfrom swutil.logs import Log\nfrom swutil.hpc import Locker\nfrom swutil.misc import string_dialog, no_context, random_word,\\\n string_from_seconds,input_with_prefill,is_identifier,smart_range\nfrom swutil.files import append_text, delete_empty_files,\\\n delete_empty_directories, find_directories, path_from_keywords\nfrom swutil.decorators import print_peak_memory, add_runtime\nfrom swutil.collections import unique\n\nclass GitError(Exception):\n def __init__(self, message, git_log):\n super(GitError, self).__init__(message)\n self.git_log = git_log\n \nGRP_WARN = 'Warning'\nGRP_ERROR = 'Error'\nFILE_DEBUG = '.debug'\nFILE_OUTPUT = 'output.pkl'\nFILE_INPUT = 'input.pkl'\nFILE_INFO = 'summary.txt'\nFILE_AUX = 'aux_data.pkl'\nFILE_RUNTIME = 'runtime.txt'\nFILE_MEMORY = 'memory.txt'\nFILE_LOAD = 'load.sh'\nFILE_EXP_ERR = 'stderr.txt'\nFILE_EXP_OUT = 'stdout.txt'\nFILE_LOG = 'log.txt'\nFILE_GITLOG = 'git.txt'\nFILE_ERR = 'err.txt'\nFILE_SOURCE = 'source.txt'\nFILE_WD = 'working_directory'\nFILE_ANALYSIS = 'analysis'\nFILE_EXP = lambda i: f'experiment{i}'\nFILE_RANDOMSTATE = 'randomstate.pkl'\nSTR_GIT_TAG = lambda ID: f'scilog_{ID}'\nSTR_GIT_LOG = lambda sha1, log: f'#Created git commit {sha1} as snapshot of current state of git repository using the following commands:\\n{log}'\nSTR_GIT_COMMIT_TITLE = lambda branch: f'Snapshot of working directory of branch {branch}'\nSTR_GIT_COMMIT_BODY = lambda name, ID, directory: f'Created for scilog entry {ID} in {directory}'\nSTR_LOADSCRIPT = ('#!/bin/sh \\n '\n + f' xterm -e {sys.executable} -i -c '\n + r'''\"\nprint('>>> import scilog'); \nimport scilog;\nprint('>>> entry = scilog.load()');\nentry = scilog.load();\ntry:\n import pandas as pd;\n print('>>> import pandas as pd');\n print('>>> experiments = pd.DataFrame(entry[\\'experiments\\'])');\n experiments = pd.DataFrame(entry['experiments']);\n print(experiments);\nexcept:\n pass;\"''')\nSTR_MEMFILE = lambda value,memory_profile: value + (\n '' if memory_profile == 'detail' \n else 'MB (Use `memory_profile==\\'detail\\'` for a more detailed breakdown)'\n )\nSTR_SOURCE = lambda n, func, module,source: (('#Experiments were conducted with' if n != 1 else '#Experiment was conducted with ')\n + ('class' if inspect.isclass(func) else \n (f'{func.__class__.__name__}' if isinstance(func,(types.MethodType,types.FunctionType)) else \n f'instance of {func.__class__.__name__}'))\n + (f' called {func.__name__}' if hasattr(func, '__name__') else '')\n + f' from the module {module} whose source code is given below:\\n{source}')\nSTR_TIME = '%y-%m-%d %H:%M:%S'\ndef STR_PARAMETERS_PROMPT(func,external,current_parameters,known_parameters,allow_variables,class_instance,allow_all_keys):\n if class_instance:\n why= f'to pass to instance of {func.__class__.__name__}'\n else:\n if external:\n why = f'to fill in `{external}`'\n else:\n name = _get_name(func)\n if inspect.isclass(func):\n why= f'to initialize class {name}'\n else:\n why = f'to pass to {name}'\n parameters_string = ', '.join(f'{key}={value!r}' for key,value in current_parameters.items())\n require_parameters=[key for key in known_parameters if key not in current_parameters]\n if require_parameters:\n parameters_string += (', ' if parameters_string else '') + ', '.join(f'{key}=' for key in require_parameters)\n if allow_all_keys:\n parameters_string += '[, <kwarg>=<value>]*'\n return f'>> Specify {\"variables or \" if allow_variables else \"\"}parameters {why} ({parameters_string}):\\n\\t'\ndef STR_PARAMETERS_ALLOWED(passed_keys,known_parameters):\n forbidden = [key for key in passed_keys if key not in known_parameters]\n if len(forbidden)>1:\n out = '!! Cannot specify parameters'+', '.join(f'`{key}`' for key in forbidden[:-1]) + f', and `{forbidden[-1]}`'\n else:\n out = '!! Cannot specify parameter '+f'`{forbidden[0]}`'\n return out\nSTR_PARAMETERS_FORMAT = '!! Input must have form `<key>=<value>[,<key>=<value>]*`\\n!! Enter `help` for more information'\nSTR_PARAMETERS_HELP = lambda allow_variables: (\n '?? Parameters are specified by `<key>=<value>` with <key> a Python identifier and <value> a Python expression.'\n +(\n (\n '\\n?? Variables have the same syntax, except <value> has the form var(<iterable>).\\n'\n '?? Variables are used to specify arguments that are varied in a specified range.\\n'\n '?? Note the difference between <key>=[0,1] and <key>=var([0,1]):\\n'\n '?? In the first case, `[0,1]` is passed at once; in the second case it is iterated over.'\n ) if allow_variables else ''\n )\n )\nMSG_DEBUG = 'Debug mode. Entry is not stored permanently, stdout and stderr are not captured, no git commit is created'\nMSG_NOGIT = 'Could not find git repository. No snapshot commit will be created'\nMSG_START_ANALYSIS = 'Updating analysis'\nMSG_START_EXPERIMENT = lambda i,n_experiments,inp: (f'Running experiment {i}' + \n (' with variable values {}{}'.format('\\n\\t' if '\\n' in repr(inp) else '',repr(inp))\n if inp != {} else ''))\nMSG_START_GIT = lambda repo:'Creating snapshot of current working tree of repository \\'{}\\'. Check {}'.format(repo,FILE_GITLOG)\ndef MSG_START_EXPERIMENTS(name,variables,parameters):\n msg = f'Will call `{name}`'\n extend=''\n new_line=False\n if parameters:\n new_line='\\n' in str(parameters) \n extend= ' with parameters {}{}'.format(\"\\n\\t\" if new_line else \"\",parameters)\n if variables:\n s_var = 'variables' if len(variables)>1 else 'variable'\n variable_strings = [(variable[0],str(variable[1])) for variable in variables]\n newline_in_vs = any('\\n' in vs[1] for vs in variable_strings)\n sep = '\\n\\t' if (len(variables)>1 or newline_in_vs) else ', '\n strings = [('' if sep == ', ' else '-') +f'`{vs[0]}`'+ (f' varying in `{vs[1]}`' if not newline_in_vs else '') for vs in variable_strings]\n extend += (\" \\n\" if new_line else \" \") +(f'and {s_var}' if extend else f' with {s_var}')+(' ' if sep==', ' else sep)+sep.join(strings)\n if not extend:\n extend =' once'\n return msg + extend\nMSG_START_ENTRY = lambda directory: f'Created scilog entry {directory}'\nMSG_FINISH_EXPERIMENT = lambda i,n_experiments,runtime,result,external: 'Finished experiment {} in {}{}'.format(i,string_from_seconds(runtime),\n '' if ('\\n' in f'{result}') else (f'. Check {os.path.join(FILE_EXP(i),FILE_EXP_OUT)}' if external else f'. Output: {result}'))\nMSG_FINISH_ENTRY=lambda directory: f'Completed scilog entry {directory}'\nMSG_SUCCESS = 'All experiments finished successfully'\nMSG_FAIL = 'Some experiments failed'\nMSG_FINISH_GIT = lambda sha1: f'Successfully created git commit {sha1}'\nMSG_ERROR_NOMATCH = 'Could not find matching scilog entry'\nMSG_ERROR_MULTIMATCH = lambda entries:'Multiple matching scilog entries (to iterate through all use need_unique=False):\\n{}'.format('\\n'.join(entries))\nMSG_ERROR_LOAD = lambda name: f'Error loading {name}. Are all required modules in the Python path?'\nMSG_ERROR_INSTANTIATION = lambda name:f'Could not instantiate class {name} with given parameters'\nMSG_ERROR_PARALLEL = 'Error during parallel execution. Try running with `parallel=False`'\nMSG_ERROR_BASH_ANALYSIS = 'Cannot analyze output in bash mode'\nMSG_ERROR_GIT = lambda file:f'Error during git snapshot creation. Check {file}'\nMSG_ERROR_EXPERIMENT = lambda i:f'Experiment {i} failed. Check {os.path.join(FILE_EXP(i),FILE_EXP_ERR)}'\nMSG_ERROR_ANALYSIS = lambda file: f'Analysis could not be completed. Check {file}'\nMSG_ERROR_DIR = 'Could not create scilog entry directory'\nMSG_EXCEPTION_STORE = lambda file: f'Could not store {file}'\nMSG_EXCEPTION_ANALYSIS = 'Exception during online analysis'\nMSG_EXCEPTION_EXPERIMENT = lambda i: f'Exception during handling of experiment {i}. Check {FILE_ERR}'\nMSG_WARN_SOURCE = 'Could not find source code'\nMSG_WARN_LOADSCRIPT = 'Error during load script creation'\nMSG_WARN_PARALLEL = ('Could not find pathos. This might cause problems with parallel execution.'\n + 'Install pathos via `pip install pathos`.')\nMSG_WARN_MEMPROF = 'Could not find memory_profiler. Install memory_profiler via `pip install memory_profiler`.'\nMSG_WARN_DILL = ('Could not find dill. Some items might not be storable. '\n + 'Storage of numpy arrays will be slow'\n + 'Install dill via `pip install dill`.')\nMSG_INTERRUPT = f'Kill signal received. Stored {FILE_INFO}, closing now.'\nLEN_ID = 8\n\n#TODO(low,high) think about using inspect.formatargspec(inspect.getargspec(func)) to directly parse args and kwargs of user input even without named argument\n#TODO(med,high) understand ellipses in variable input: Do this at the string input level, so 2**3,...,2**6 can be understood. \n#TODO(med,low) make scilog --show work for all scilog entries in current git repo even outside of cwd\n#TODO(high,low) make scilog --show smarter: if FUNC doesn't match any scilog entry path, try if it matches a scilog entry ID\n#TODO(high,high) remove analysis functionality from scilog.py and add scilog --analyze working as follows: provide a list of entry identifiers (ID or paths) as well as a function that accepts scilog entries (i.e. the summary dicts). the source code file (foo.py) of that function (foo.func) is copied in the analysis subsubdirectories `foo_x` of each scilog entry \n#TODO technically: `scilog --analyze X3DH,UH1X --parameters [...] --variables [...] foo.func` starts a scilog run with arguments func=foo.func, analysis = True[effects that git=False, base_directory =tempfile.mktemp(), func is called with parameters={**parameters, entries=[scilog.load(identifier) for identifier in analzsis]} log does not say 'created scilog entry' but instead says which entries will be analyzed with what, and finishes with \"added analysis <classification_x to X3DH and <classification>_y to UH1X, and entry is copied into subdireoctry analyze/<classificatoin>_x of X3DH and UH1X with x possibly being adapted to what is already in the analysis of X3DH and UH1X ]\n#TODO make load ignore subdirectories of scilog entries (to avoid listing analysis entries)\n#TODO(?,?) comunicate to plots.save \n#TODO(low,med) understand <param>=<string> without quotes around <string> (simple and stupid: fail, add unrecognized variable to locals, repeat...)\n#TODO(low,med) understand scilog foo(a=1)(b=var()) by defining foo in locals() and have it return another function that takes yet more arguments \n#TODO(med,low) if copy_output is a path, try to copy that path and only terminate when succeeded (e.g. when it starts existing) also, add argument check_done and if it is provided only try copying as soon as it returns True\n#TODO(low,low) store completion flag\n#TODO(high,low) make scilog --show show [log, current-stdout,current-stderr] if entry not completed, (so you can avoid screen -r and navigation to the filesystem directory)\n#TODO(low,low) make scilog --show show scilog-stderr if it exists and, if all experiments failed, also show current-stderr of last experiment in that case (if at least one succeeded leave it to user to navigate to the failed experiment) \n#TODO(med,low) make scilog --show default to no-git (add --git)\n#TODO(?,?) make scilog --show first look through screen sessions\n#TODO(low,med) Store final note in notes.txt, add --update <REASON> to scilog which then flags all previous runs with same config as outdated in their notes.txt \n#TODO(low,low) add --note flag\n#TODO(med,low) extend scilog ls output by scilog status (running, terminated, error,n_experiments) (store log files)\n#TODO(med,low) include no-shutdown script\ndef record(func, variables=None, name=None, base_directory=None, aux_data=None,\n analysis=None, runtime_profile=False, memory_profile=False,\n git=True, no_date=False, parallel=False,\n copy_output = None, parameters=None,debug = None,classification= None,dry_run=False):\n '''\n Call :code:`func` once or multiple times and store results along with auxiliary information\n about runtime and memory usage, installed modules, source code, hardware, etc.\n \n code:`func` is called once for each combination of variable values as \n specified by the variable ranges in :code:`variables`.\n For example, :code:`func` can be a numerical algorithm and :code:`variables`\n can be used to specify different mesh resolutions as follow\n `variables = {h:[2**(-l) for l in range(10)}` \n with the goal to assess the rate of convergence.\n Another example would be to specify a list of subroutines with the goal to find\n the best subroutine in terms of runtime/memory consumption/....\n\n In the following, each call of :code:`func` is called an 'experiment'.\n\n Scilog creates a directory -- specified by :code:`directory`, :code:`name`, \n and optional parameters or a randomly generated ID -- with the following content:\n *summary.txt:\n *name: Name of scilog entry\n *ID: Alphanumeric string identifying the entry\n *modules: Module versions\n *time: Time of execution\n *experiments: For each experiment\n *string representation of input, \n *string representation of output,\n *runtime\n *status\n *(optional)memory usage\n *(optional)parameters: Parameters that are equal for all experiments\n *(optional)git_commit: SHA1 of git commit \n *(optional)aux_data: Argument :code:`aux_data`\n *log.txt\n *(optional)err.txt\n *(optional)git.txt: stdout of git snapshot creation \n *source.txt: Source code of the module containing :code:`func`\n *For each experiment a subdirectory 'experiment<i>' with:\n *output.pkl: Output of :code:`func`\n *(optional)input.pkl: Argument passed to :code:`func`\n *(optional)working_directory/: Working directory for call of :code:`func`, \n unless parameter :code:`copy_output` is specified\n *(optional)stderr.txt:\n *(optional)stdout.txt:\n *(optional)runtime_profile.txt: Extensive runtime information for each experiment\n *(optional)memory_profile.txt: Memory usage information for each experiment\n *(optional) analysis/: output of function :code:`analysis`\n *(optional)stderr.txt\n *(optional)stdout.txt\n *(optional)working_directory/: Working directory for call of :code:`analysis`\n\n To load a scilog entry, use the function :code:`scilog.load`.\n This function loads summary.txt and replaces the string representations of outputs and inputs\n by the actual Python objects. \n\n :param func: Function to be called with different experiment configurations\n :type func: function\n :param variables: Arguments for call of :code:`func` that are varied. \n If not specified, then :code:`func` is called once, without arguments\n :type variables: List(-like) if single variable or dictionary of lists\n :param name: Name of scilog entry. \n If not specified, :code:`func.__name__` is used\n :type name: String\n :param base_directory: Root directory for storage\n :type base_directory: String\n :param aux_data: Auxiliary data that should be stored along with the results\n :type aux_data: Any\n :param analysis: Function that is called after each experiment \n Can be used, e.g., for plotting\n :param runtime_profile: Store extensive runtime information\n May slow down execution\n :type runtime_profile: Boolean\n :param memory_profile: Track memory usage\n May slow down execution\n :type memory_profile: Boolean\n :param git: Create git snapshot commit\n The resulting commit is tagged with the entry ID and resides outside the branch history\n The repository path may be specified, else it will be automatically detected\n Add 'scilog' to your .gitignore to avoid storing the scilog entries in each snapshot. \n (Should you ever want get rid of the snapshots, \n use `git tag --list 'scilog_*'|xargs -I % git tag -d %` to remove all scilog commits or \n use function `clean_git_repository` to remove all scilog commits whose scilog entry does not reside in repository anymore)\n :type git: Boolean or String\n :param no_date: Do not store outputs in sub-directories grouped by calendar week\n :type no_date: Boolean\n :param parameters: Parameters that are equal for all experiments\n If :code:`func` is a class, these are used to instantiate this class\n :type parameters: Dictionary\n :param debug: Force debug mode (otherwise detected automatically)\n :param debug: Boolean\n :param copy_output: The contents of this directory will be copied into the scilog entry directory\n :type copy_output: String\n :param classification: Short, human readable description of entry\n :type classification: String\n :param dry_run: Only setup directory and experiments, don't execute anything\n :type dry_run: Boolean\n :return: Path of scilog entry\n :rtype: String\n '''\n ########################### FIX ARGUMENTS ###########################\n variables,parameters,func_initialized,classification_t = _setup_experiments(variables,parameters,func)\n classification = classification or classification_t\n name = name or _get_name(func)\n if dry_run:\n return variables,parameters,classification,name\n external = _external(func)\n debug = debug if debug is not None else aux.isdebugging()\n if debug: \n git = False\n log_nogit = False\n if git is not False:\n if git is True:\n git = _get_func_directory(func)\n if not _has_git(git):\n log_nogit = True\n git = False\n ########################### SETUP INPUTS ##############################\n if len(variables)!=1:#Will result in infinite loop if one variable is infinite. \n t = itertools.product(*[variable[1] for variable in variables])\n else:\n t = ([x] for x in variables[0][1])\n inputs = ({variable[0]:tt[i] for i,variable in enumerate(variables)} for tt in t)\n try:\n n_experiments = int(np.prod([len(variable[1]) for variable in variables]))\n except TypeError:\n n_experiments = None\n ########################### CREATE SCILOG ENTRY ########################\n entry_directory,ID = _get_directory(base_directory,func,name,no_date,debug,git,classification)\n log_file = os.path.join(entry_directory, FILE_LOG)\n err_file = os.path.join(entry_directory, FILE_ERR)\n info_file = os.path.join(entry_directory, FILE_INFO)\n load_file = os.path.join(entry_directory, FILE_LOAD)\n aux_data_file = os.path.join(entry_directory, FILE_AUX)\n source_file_name = os.path.join(entry_directory, FILE_SOURCE)\n git_file = os.path.join(entry_directory, FILE_GITLOG)\n locker = Locker()\n _log = Log(write_filter=True, print_filter=True, file_name=log_file,lock = locker.get_lock()) # Logging strategy: 1) Redirect out and err of user functions (analysis and experiment) to their own files\n _err = Log(write_filter=True, print_filter=False, file_name=err_file,lock = locker.get_lock()) # 2) Log errors outside user functions in _err 3) Log everything (user-err and _err, as well as other info) in _log \n _log.log(MSG_START_ENTRY(entry_directory))\n if log_nogit:\n _log.log(group = GRP_WARN,message = MSG_NOGIT)\n if debug:\n _log.log(group =GRP_WARN,message = MSG_DEBUG)\n info = {\n 'parameters' : {key:repr(parameters[key]) for key in parameters},\n 'variables' : [repr(variable) for variable in variables],\n 'name' : name,\n 'ID' : ID,\n 'time' : datetime.datetime.now().strftime(STR_TIME),\n 'func' : external or repr(func),\n 'parallel' : parallel,\n 'hardware' : sys_info.hardware(),\n 'gitcommit' : None,\n 'modules' : None,\n 'note': None,\n 'experiments' : {\n 'runtime':[],\n 'memory':[],\n 'status':[],\n 'input':[],\n 'output':[] \n }\n }\n if not external:\n info['modules'] = sys_info.modules()\n try:\n source = STR_SOURCE(n_experiments,func,sys.modules[func.__module__].__file__, ''.join(inspect.getsourcelines(sys.modules[func.__module__])[0]))\n append_text(source_file_name, source)\n except Exception: # TypeError only?\n _err.log(traceback.format_exc())\n _log.log(group=GRP_WARN, message=MSG_WARN_SOURCE)\n if memory_profile is not False:\n if memory_profile == 'detail':\n try:\n import memory_profiler # @UnusedImport, just to check if this will be possible in _run_single_experiment\n except ImportError:\n _log.log(group=GRP_WARN, message=MSG_WARN_MEMPROF)\n memory_profile = True\n else:\n memory_profile = True\n try: \n with open(load_file, 'w') as fp:\n fp.write(STR_LOADSCRIPT)\n st = os.stat(load_file)\n os.chmod(load_file, st.st_mode | stat.S_IEXEC)\n except Exception:\n _err.log(message=traceback.format_exc())\n _log.log(group=GRP_WARN, message=MSG_WARN_LOADSCRIPT)\n if git:\n try:\n _log.log(message=MSG_START_GIT(os.path.basename(os.path.normpath(git))))\n with (capture_output() if not debug else no_context()) as c:\n snapshot_id, git_log, _ = _git_snapshot(path=git,commit_body=STR_GIT_COMMIT_BODY(name, ID, entry_directory), ID=ID)\n append_text(git_file, STR_GIT_LOG(snapshot_id, git_log))\n _log.log(message=MSG_FINISH_GIT(snapshot_id))\n info['gitcommit'] = snapshot_id\n except GitError as e:\n _log.log(group=GRP_ERROR, message=MSG_ERROR_GIT(git_file))\n _err.log(message=str(e)+'\\n'+c.stderr)\n append_text(git_file, e.git_log)\n raise\n try:\n import dill\n serializer = dill\n except ImportError:\n serializer = pickle\n _log.log(group=GRP_WARN, message=MSG_WARN_DILL)\n _try_store(aux_data,serializer,aux_data_file,_log,_err)\n def _update_info(i, runtime, status, memory, input_str, output_str):\n for (key,val) in [('runtime',runtime),\n ('memory',memory if memory_profile is not False else None),\n ('status',status),\n ('input',input_str),\n ('output',output_str),\n ]:\n info['experiments'][key].append(val)\n store_info()\n def store_info():\n with open(info_file,'w') as fp:\n json.dump(info,fp,indent = 1,separators = (',\\n', ': '))\n store_info()\n old_wd = os.getcwd()\n ########################### RUN EXPERIMENTS ###############################\n args = (\n (\n i, input, entry_directory, func_initialized, memory_profile,\n runtime_profile, _log,_err,\n 'pickle' if serializer == pickle else 'dill',\n external, debug, copy_output,n_experiments\n )\n for i, input in enumerate(inputs)\n )\n _log.log(message=MSG_START_EXPERIMENTS(name,variables,parameters))\n def close_entry():\n try:\n os.chdir(old_wd)\n except Exception:\n pass\n success = all(s=='finished' for s in info['experiments']['status'])\n try:\n _log.log(MSG_FINISH_ENTRY(entry_directory))\n if not success:\n _log.log(MSG_FAIL)\n except Exception:\n pass\n if not debug:\n note = input('You may add a short note to this entry or simply press Enter to exit:') \n if note:\n info['note'] = note\n store_info()\n return entry_directory\n if parallel and not debug:\n try:\n from pathos.multiprocessing import ProcessingPool as Pool\n pool = Pool(nodes=n_experiments)\n except ImportError:\n _err.log(message=traceback.format_exc())\n _log.log(group=GRP_WARN, message=MSG_WARN_PARALLEL)\n from multiprocessing import Pool\n pool = Pool(processes=n_experiments)\n try:\n outputs = pool.map(_run_single_experiment, args)\n except pickle.PicklingError: # @UndefinedVariable\n _err.log(message=traceback.format_exc())\n _log.log(group=GRP_ERROR, message=MSG_ERROR_PARALLEL)\n raise\n for output in outputs:\n _update_info(*output)\n pool.close()\n pool.join()\n else:\n for arg in args:\n try:\n output = _run_single_experiment(arg)\n except Exception:#These come from errors in the code of _run_single_experiments. The user function errors are caught within there\n _err.log(message=traceback.format_exc())\n _log.log(group=GRP_ERROR, message=MSG_EXCEPTION_EXPERIMENT(arg[0]))\n else:\n _update_info(*output)\n if analysis:\n try:\n _log.log(message=MSG_START_ANALYSIS)\n except BrokenPipeError:#locks raise BrokenPipeError when experiments are terminated using <C-c>\n sys.exit(1)\n try:\n with capture_output():\n entry = load(path=entry_directory, need_unique=True, no_objects=False)\n analyze(func=analysis, entry=entry, _log=_log, _err=_err, debug=debug)\n except Exception:\n _err.log(message=traceback.format_exc())\n _log.log(group=GRP_ERROR, message=MSG_EXCEPTION_ANALYSIS)\n return close_entry()\n\ndef _has_git(git):\n cwd = os.getcwd()\n try:\n os.chdir(git)\n #subprocess.check_call(['git','status'],stdout = subprocess.PIPE,stderr=subprocess.PIPE)\n subprocess.check_call(['git','rev-parse','HEAD',],stdout = subprocess.PIPE,stderr=subprocess.PIPE)#Sometimes git status works but rev-parse, which is used later, fails; e.g. on repos without initial commit\n return True\n except subprocess.CalledProcessError:\n return False\n finally:\n os.chdir(cwd)\n\ndef _external(func):\n return func if isinstance(func,str) else False\n\ndef _get_func_directory(func):\n return os.getcwd() if _external(func) else os.path.dirname(sys.modules[func.__module__].__file__) \n\ndef _get_base_directory(directory,func,name,no_date):\n directory = directory or _get_func_directory(func)\n directory = os.path.join(directory,'scilog')\n if no_date:\n basepath = os.path.join(directory, name)\n else:\n date = datetime.date.today()\n basepath = os.path.join(directory, date.strftime('w%Wy%y'), name)\n return os.path.abspath(basepath)\n\ndef _get_name(func):\n if _external(func): \n nowhite = re.compile('\\S*')\n path = nowhite.match(func).group(0)\n name = os.path.basename(path)\n else:\n try:#func is a function or a class\n name = func.__name__\n except AttributeError:#func is an object with __call__ method\n name = func.__class__.__name__\n return name\n\ndef _evaluator(what,locals_dict = None):\n locals_dict = locals_dict or {}\n return eval(f'(lambda **kwargs: kwargs)({what})',{'range':range,'count':itertools.count,'np':np,'__builtins__':{}},locals_dict)\n\nclass _var:\n def __init__(self,*obj):\n if len(obj)>1:#e.g. var('ab','cd','ef')\n self.obj = obj\n elif len(obj)==1:#e.g. var(range(3))\n if Iterable.valid(obj[0]):\n self.obj = list(obj[0])#turn into list so that numpy arrays go through later on (if you leave them as arrays, they will make problems in = comparison, for example)\n else:#Allows for --variables p=3 instead of --variables p=[3]\n self.obj = [obj[0]]\n elif len(obj)==0:\n raise ValueError()\n def __repr__(self):\n return 'var('+repr(self.obj)+')'\n\ndef _setup_experiments(variables,parameters,func):\n '''\n Note: input and output `variables` have iterator type, not _var. \n _var only occurs in the processing \n '''\n external = _external(func)\n def _get_kwargs(func,external,variables,parameters,class_instance=False):\n if inspect.isclass(func):\n allow_variables =False\n variables = None\n else:\n allow_variables=True\n parameters_passed = parameters is not None\n variables_passed = variables is not None\n if parameters is None:\n parameters = {}\n if variables is None:\n variables = {}\n if external:\n field_names = [fname for _, fname, _, _ in Formatter().parse(external) if fname is not None]\n new_var_n = 0\n new_names = []\n for i,fname in enumerate(field_names):\n if fname == '':\n while True:\n if f'arg{new_var_n}' not in field_names:\n new_names.append(f'arg{new_var_n}')\n break\n else:\n new_var_n+=1\n external = external.format(\n *[f'{{{new_name}}}' for new_name in new_names],\n **{fname:f'{{{fname}}}' for fname in field_names if fname !='' }\n )\n known_parameters = OrderedDict((fname,inspect._empty) for _, fname, _, _ in Formatter().parse(external) if fname is not None)\n if len(known_parameters)==1 and list(known_parameters.keys())[0] == None:\n known_parameters = []\n allow_all_keys = False\n default_parameters = {}\n else:\n func_parameters = inspect.signature(func).parameters\n default_parameters = {\n key:value.default for key,value in func_parameters.items() \n if (value.default != inspect._empty)\n }\n allow_all_keys = any(value.kind ==4 for key,value in func_parameters.items())\n known_parameters = OrderedDict(\n (key,value.default) for key,value in func_parameters.items()\n if (value.kind not in [2,4])\n )\n kwargs=default_parameters.copy()\n free_keys=lambda : allow_all_keys or any(key not in variables and key not in parameters for key in known_parameters)\n required_keys=lambda : [key for key in known_parameters if key not in kwargs]\n is_allowed_key=lambda key: allow_all_keys or key in known_parameters\n if variables:\n if not isinstance(variables,dict):#allow for single range instead of var dictionary\n non_default_parameters = [key for key in known_parameters if key not in default_parameters]\n if len(non_default_parameters) == 1:\n variables={non_default_parameters[0]:variables}\n elif len(known_parameters) ==1:\n variables = {list(known_parameters.keys())[0]:variables}\n else:\n raise ValueError(f'Must specify name for variable {variables}')\n if any(not is_allowed_key(key) or not is_identifier(key) for key in variables):\n raise ValueError('Invalid variable names for function {}: {}'.format(external or func,{key for key in variables if not is_allowed_key(key)}))\n variables_update = {key:_var(value) for key,value in variables.items()}\n else:\n variables_update = {}\n if parameters:\n if any(key in variables_update for key in parameters):\n raise ValueError('Parameter names already defined as variables: {}'.format({key for key in parameters if key in kwargs}))\n if any(not is_allowed_key(key) or not is_identifier(key) for key in parameters):\n raise ValueError('Invalid parameter names for function {}: {}'.format(external or func,{key for key in parameters if not is_allowed_key(key)}))\n parameters_update = parameters\n else:\n parameters_update = parameters\n kwargs.update(**variables_update,**parameters_update)\n if (((not parameters_passed and not class_instance) or (not variables_passed and allow_variables)) and free_keys()) or required_keys(): \n while True:\n prefill=', '.join([key+'=' for key in required_keys()])\n parameters_string = input_with_prefill(STR_PARAMETERS_PROMPT(func,external,kwargs,known_parameters,allow_variables,class_instance,allow_all_keys),prefill)\n if parameters_string in ['?','help','--help','??']:\n print(STR_PARAMETERS_HELP(allow_variables))\n continue\n try:\n update_kwargs = _evaluator(parameters_string,{'var':_var} if allow_variables else {})\n except Exception:#(ValueError,SyntaxError):\n if '=help' in parameters_string:\n print(STR_PARAMETERS_HELP(allow_variables))\n else:\n print(STR_PARAMETERS_FORMAT)\n else:\n kwargs.update({key: value for key,value in update_kwargs.items() if is_allowed_key(key)})\n done = True\n if not all(key in kwargs for key in known_parameters):\n if parameters_string =='':\n print(STR_PARAMETERS_FORMAT)\n done = False\n if any(not is_allowed_key(key) for key in update_kwargs):\n print(STR_PARAMETERS_ALLOWED(update_kwargs,known_parameters))\n done = False\n if done:\n break\n return kwargs,external,default_parameters,known_parameters\n if external:\n def func(**kwargs):\n subprocess.check_call(external.format(**kwargs), stdout=sys.stdout, stderr=sys.stderr, shell=True)\n classification_variables = {}#variables.copy() if isinstance(variables,dict) else {}#can be None or a single unnamed iterable whose name will be found out only later \n classification_parameters = {}#parameters.copy() if isinstance(parameters,dict) else {}# can be None\n if inspect.isclass(func):# in this case, parameters are for initialization and variables for function call\n parameters,_,default_parameters,_ = _get_kwargs(func,False,None,parameters)\n func_initialized=func(**parameters)\n variables,_,default_parameters_2,known_parameters_2 = _get_kwargs(func_initialized,False,variables,None,class_instance=True)\n real_variables = {key:value for key,value in variables.items() if isinstance(value,_var)}\n classification_parameters.update({key:value for key,value in parameters.items() if key not in default_parameters or (key in default_parameters and value !=default_parameters[key])})\n if len(variables)<=1:#nothing possibly interesting can be said if there is only one variable except if variable was not known (i.e. keyword argument) \n if not classification_parameters:#If not any classification yet take what you have\n classification_variables.update({key:value for key,value in variables.items()})\n else:\n classification_variables.update({key:value for key,value in variables.items() if key not in known_parameters_2})\n else:\n classification_variables.update({key:value for key,value in variables.items() if key not in known_parameters_2 or (key in default_parameters_2 and value!=default_parameters_2[key])})\n if any(key not in real_variables for key in variables if not key in default_parameters_2):#Not all nondefault parameters actually vary, so list those that do\n classification_variables.update({key:value for key,value in real_variables.items() if key not in default_parameters_2})\n variables = {key:(value.obj if isinstance(value,_var) else [value]) for key,value in variables.items()}#Users are prompeted vor variables or parameters, but if they enter parameters, i.e. a single value, the willy still be handled as variables taking only one value\n else:\n kwargs,external,default_parameters,_ =_get_kwargs(func,external,variables,parameters)#use all as name, first params as usual (all hand selected, fill to 5), then __var_l_h\n variables = {key:value.obj for key,value in kwargs.items() if isinstance(value,_var)}\n parameters ={key:value for key,value in kwargs.items() if not isinstance(value,_var)}\n #use classification even if only one known parameter, this helps if the braces in a bash command string are changed and suddenly control something very different \n classification_parameters.update({key:value for key,value in parameters.items() if key not in default_parameters or (key in default_parameters and value!=default_parameters[key])})\n classification_variables.update({key:value for key,value in variables.items() if key not in default_parameters or (key in default_parameters and value!=default_parameters[key])})\n def func_initialized(**experiment):\n return func(**experiment,**parameters)\n variables = list(variables.items())\n classification_p = path_from_keywords(classification_parameters,into='file')\n classification_v = '_'.join(s.replace('_','') for s in classification_variables.keys())\n classification = classification_p+('+' if classification_v else '') +classification_v \n for j,variable in enumerate(variables):\n if (List|Tuple).valid(variable[1]) and Ellipsis in variable[1]:\n variables[j] = (variable[0],smart_range(*[e for e in variable[1] if e != Ellipsis]))\n return variables,parameters,func_initialized,classification\n\ndef _run_single_experiment(arg):\n (i, input, directory, func, memory_profile,\n runtime_profile, _log,_err, serializer,\n external, debug, copy_output,n_experiments) = arg\n experiment_directory = os.path.join(directory, FILE_EXP(i))\n stderr_file = os.path.join(experiment_directory, FILE_EXP_ERR)\n stdout_file = os.path.join(experiment_directory, FILE_EXP_OUT)\n input_file = os.path.join(experiment_directory, FILE_INPUT)\n output_file = os.path.join(experiment_directory, FILE_OUTPUT)\n randomstate_file = os.path.join(experiment_directory, FILE_RANDOMSTATE)\n runtime_profile_file = os.path.join(experiment_directory, FILE_RUNTIME)\n memory_profile_file = os.path.join(experiment_directory, FILE_MEMORY)\n experiment_working_directory = os.path.join(experiment_directory, FILE_WD)\n if serializer == 'pickle':\n serializer = pickle\n else:\n import dill\n serializer = dill\n _log.log(MSG_START_EXPERIMENT(i,n_experiments,input))\n runtime = None\n output = None\n input_str = repr(input)\n memory = None\n status = 'failed'\n randomstate = None\n if not external:\n randomstate = np.random.get_state()\n if hasattr(func, '__name__'):#func is function\n temp_func = func\n else:#func is object\n temp_func = func.__call__\n if copy_output is None:\n os.makedirs(experiment_working_directory)\n os.chdir(experiment_working_directory)\n else:\n os.makedirs(experiment_directory)\n try:\n _try_store(input,serializer,input_file,_log,_err)\n _try_store(randomstate,serializer,randomstate_file,_log,_err)\n if memory_profile == 'detail':#Needs to be before runtime decorator so it gets the full view (otherwise it will profile the runtime decorator)\n m = io.StringIO()\n import memory_profiler\n temp_func = memory_profiler.profile(func = temp_func,stream =m ,precision = 4)\n if runtime_profile:\n temp_func = add_runtime(temp_func)\n if memory_profile is True:#Needs to be after runtime decorator so runtime gets the full view (since peak_memory is threaded)\n m = io.StringIO()\n temp_func = print_peak_memory(func=temp_func, stream=m)\n stderr_append = ''\n with open(stderr_file, 'a', 1) as err:\n with open(stdout_file, 'a', 1) as out:\n with contextlib.redirect_stdout(out) if not debug else no_context():\n with contextlib.redirect_stderr(err) if not debug else no_context():\n tic = timeit.default_timer()\n try:\n output = temp_func(**input)\n except Exception:\n status = 'failed'\n if debug:\n traceback.print_exc()\n try:\n import ipdb as debugger\n except ModuleNotFoundError:\n import pdb as debugger\n debugger.post_mortem(sys.exc_info()[2])\n stderr_append = traceback.format_exc()\n else:\n status = 'finished'\n runtime = timeit.default_timer() - tic\n delete_empty_files([stderr_file, stdout_file])\n if status == 'failed':\n append_text(stderr_file, stderr_append)\n _log.log(group=GRP_ERROR, message=MSG_ERROR_EXPERIMENT(i),use_lock = False)#locks are often broken already which leads to ugly printouts, also errors don't matter at this point anyway\n else:\n if runtime_profile:\n profile, output = output\n s = io.StringIO()\n ps = pstats.Stats(profile, stream=s)\n ps.sort_stats('cumulative')\n ps.print_stats()\n append_text(runtime_profile_file, s.getvalue())\n s.close()\n if memory_profile:\n append_text(memory_profile_file,STR_MEMFILE(m.getvalue(),memory_profile))\n memory = _max_mem(m.getvalue(), type=memory_profile)\n except Exception:\n _err.log(message=traceback.format_exc())\n _log.log(group=GRP_ERROR, message=MSG_EXCEPTION_EXPERIMENT(i))\n if copy_output is None:\n os.chdir(directory)\n else:\n shutil.copytree(copy_output, experiment_working_directory, symlinks=False, ignore_dangling_symlinks=True)\n delete_empty_directories([experiment_working_directory])\n output_str = str(output)\n _try_store(output,serializer,output_file,_log,_err)\n del output\n if status == 'finished':\n _log.log(MSG_FINISH_EXPERIMENT(i, n_experiments, runtime, output_str,external))\n gc.collect()\n return (i, runtime, status, memory, input_str, output_str)\n\nclass ConvergencePlotter():\n def __init__(self, *qois, cumulative=False, work=None, extrapolate=0,reference = 'self'):\n '''\n Create convergence plots (of given quantities of interest (qois))\n \n This is an auxiliary class that may be used as argument for parameter \n `analyze` of scilog.record or parameter `func` of scilog.analyze\n \n :param qois: List of functions that can be applied to the outputs of an experiment\n :param cumulative: Specify whether work is cumulative across the experiments\n :param work: If a measure other than runtime should be used, this must be a function taking integers and returning reals\n :param extrapolate: Degree of Richardson extrapolation \n extrapolate = -1 uses exponential extrapolation, whereas \n positive values merely improve algebraic convergence orders\n '''\n self.qois = qois\n self.cumulative = cumulative\n self.work = work\n self.extrapolate = extrapolate\n self.reference = reference\n def __call__(self, entry):\n experiments = entry['experiments']\n single_reference = (self.reference == 'self')\n ind_finished = [j for (j, s) in enumerate(experiments['status']) if s == 'finished']\n if len(ind_finished) > 2 + (self.extrapolate if self.extrapolate >= 0 else 0):\n if self.work is None:\n times = experiments['runtime'][ind_finished]\n else:\n times = [self.work(i) for i in ind_finished]\n results = experiments[i]['output'][ind_finished]\n if self.cumulative:\n times = np.cumsum(times)\n if not self.qois:\n if hasattr(results[0], '__len__') and not isinstance(results[0], np.ndarray):\n self.qois = [lambda x,k = k: x[k] for k in range(len(results[0]))]\n else:\n self.qois = [lambda x:x]\n single_reference = True\n if single_reference:\n self.reference = [self.reference]*len(self.qois)\n for (k, qoi) in enumerate(self.qois):\n try:\n pyplot.figure(k).clf()\n qoi_values = np.array([qoi(result) for result in results])\n qoi_times = np.array(times)\n if self.extrapolate:\n qoi_values, qoi_times = np_tools.extrapolate(qoi_values, qoi_times, self.extrapolate)\n plots.plot_convergence(qoi_times, qoi_values,reference = self.reference[k]) \n plots.save('convergence')\n except Exception:\n traceback.print_exc()\n \ndef _try_store(what,serializer,file,_log,_err):\n if what is not None:\n try:\n with open(file, 'wb') as fp:\n serializer.dump(what, fp)\n except (TypeError, pickle.PicklingError):\n _err.log(message=traceback.format_exc())\n _log.log(group=GRP_WARN, message=MSG_EXCEPTION_STORE(os.path.split(file)[-1]))\n\ndef clean_git_repository(directory=None,dry_run = True):\n '''\n Delete all commits in repository specified by :code:`directory` which do not have matching\n scilog entry in repository directory. \n :param directory: Path that is under version control\n :type directory: String\n :param dry_run: Actually go ahead and delete commits, else just list them\n :type dry_run: Bool\n '''\n directory = directory or os.getcwd()\n os.chdir(directory)\n scilog_tag = re.compile('scilog_.*')\n tags = [tag for tag in _git_command('tag --list',add_input = False).splitlines() if scilog_tag.match(tag)]\n git_directory = _git_command('rev-parse --show-toplevel', add_input=False).rstrip()\n os.chdir(git_directory)\n entries = load(need_unique=False,no_objects=True)\n IDs = [entry['ID'] for entry in entries]\n unmatched = [tag for tag in tags if tag[7:] not in IDs]\n if unmatched:\n print(f'The following scilog git commits have no matching scilog entry in {directory}:')\n [print(tag) for tag in unmatched]\n if dry_run:\n print('Specify `dry_run=False` to remove unmatched commits')\n else:\n print('Removing unmatched commits...',end='')\n [_git_command(f'tag -d {tag}') for tag in unmatched]\n print('done')\n else:\n print(f'All scilog git commits have matching scilog entries in {directory}')\n\ndef analyze(entry,func, _log=None, _err=None, debug=False):\n '''\n Add analysis to scilog entry or entries\n \n :param func: Function that performs analysis\n :param entry: scilog entry or entries (as returned by scilog.load)\n :param _log: Log object to be used instead of writing to standard stdout\n :param _err: Log object to be used instead of writing to standard stderr\n :param debug: If True, output is printed instead of being redirected into files\n '''\n if not _log:\n _log = Log(print_filter=True)\n if not _err:\n _err = Log(print_filter=True)\n try:\n import dill\n serializer = dill\n except ImportError:\n serializer = pickle\n _log.log(group=GRP_WARN, message=MSG_WARN_DILL)\n cwd = os.getcwd()\n try:\n if not inspect.isgenerator(entry):\n entries = [entry]\n else:\n entries = entry\n for entry in entries:\n analysis_directory_tmp = os.path.join(entry['path'], 'tmp',FILE_ANALYSIS)\n working_directory = os.path.join(analysis_directory_tmp, FILE_WD)\n stderr_file = os.path.join(analysis_directory_tmp, FILE_EXP_ERR)\n stdout_file = os.path.join(analysis_directory_tmp, FILE_EXP_OUT)\n output_file = os.path.join(analysis_directory_tmp, FILE_OUTPUT)\n os.makedirs(analysis_directory_tmp)\n os.mkdir(working_directory)\n os.chdir(working_directory)\n output = None\n stderr_append = ''\n with open(stderr_file, 'a', 1) as err:\n with open(stdout_file, 'a', 1) as out:\n with contextlib.redirect_stdout(out) if not debug else no_context():\n with contextlib.redirect_stderr(err) if not debug else no_context():\n try:\n output = func(entry)\n except Exception:\n stderr_append = traceback.format_exc()\n delete_empty_files([stderr_file, stdout_file])\n delete_empty_directories([working_directory])\n if stderr_append:\n append_text(stderr_file, stderr_append)\n _log.log(group=GRP_ERROR, message=MSG_ERROR_ANALYSIS(stderr_file))\n _try_store(output,serializer,output_file,_log,_err)\n os.chdir(cwd)\n analysis_directory = os.path.join(entry['path'], FILE_ANALYSIS)\n shutil.rmtree(analysis_directory, ignore_errors=True)\n shutil.move(analysis_directory_tmp, entry['path'])\n shutil.rmtree(os.path.split(analysis_directory_tmp)[0], ignore_errors=True)\n except Exception:\n os.chdir(cwd)\n \nclass RE:\n def __init__(self,s):\n self.s=s\n\ndef load(search_pattern='*', path='', ID=None, no_objects=False, need_unique=True,include_modules=False,parameters=None,fix_broken_summary_txt=False):#TODO remove fix_borken_summary_txt\n '''\n Load scilog entry/entries.\n \n :param search_pattern: Shell-style glob/search pattern using wildcards\n If there are multiple entries of the same name (those are stored as\n <name>/v0 <name>/v1 ... in the filesystem) and they should all be returned, \n use `search_pattern=<name>/v*` and `need_unique=False`\n :type search_pattern: String, e.g. search_pattern='foo*' matches `foobar`\n :param path: Path of exact location if known (possibly only partially), relative or absolute\n :type path: String, e.g. '/home/username/<project>' or '<project>'\n :param no_objects: To save time, only load information about scilog entry, not results\n :type no_objects: Boolean\n :param need_unique: Require unique identification of scilog entry.\n :type need_unique: Boolean\n :param parameters: Search pattern that is applied to the scilog parameters\n :type parameters: Dictionary of regular expression strings or objects (which will be converted to strings)\n :return: Scilog entry\n :rtype: If need_unique=True, a single Namespace obejct\n If need_unique=False, a generator of such objects\n '''\n deserializer = pickle\n try:\n import dill\n deserializer = dill\n except ImportError:\n warnings.warn(MSG_WARN_DILL)\n if os.sep in search_pattern and path == '':#Use absolute path part of search pattern as path, if existent\n temp_path, temp_search_pattern = search_pattern.rsplit(os.sep, 1)\n if os.path.isabs(temp_path):\n path, search_pattern = temp_path, temp_search_pattern\n if search_pattern[-1]!='*':\n search_pattern = search_pattern+'*'\n entries = []\n entries.extend(find_directories(search_pattern, path=path))\n entries.extend(find_directories('*/' + search_pattern, path=path))\n entries = [entry for entry in entries if _is_experiment_directory(entry)]\n def get_output(entry, no_objects):\n file_name = os.path.join(entry, FILE_INFO)\n with open(file_name, 'r') as fp:\n try:\n info = json.load(fp)\n except Exception:\n raise ValueError(f'Problem with {file_name}') \n info['path'] = entry\n if not include_modules:\n del info['modules']\n if not no_objects:\n #if isinstance(info['experiments'],dict):#Old version of scilog:\n # DL = info['experiments']\n # info['experiments'] = [dict(zip(DL,t)) for t in zip(*DL.values())]\n for j,s in enumerate(info['experiments']['status'] if not fix_broken_summary_txt else ('finished' for i in itertools.count())):\n if s == 'finished':\n try:\n output_file_name = os.path.join(entry, FILE_EXP(j), FILE_OUTPUT)\n with open(output_file_name, 'rb') as fp:\n output = deserializer.load(fp)\n if fix_broken_summary_txt:\n info['experiments']['output'].append(output)\n else:\n info['experiments']['output'][j] = output\n except Exception:\n warnings.warn(MSG_ERROR_LOAD('file ' + output_file_name))\n if fix_broken_summary_txt:\n break\n traceback.print_exc()\n if not fix_broken_summary_txt: \n try:\n input_file_name = os.path.join(entry,FILE_EXP(j),FILE_INPUT)\n with open(input_file_name,'rb') as fp:\n input = deserializer.load(fp)\n info['experiments']['input'][j] = input\n except Exception:\n warnings.warn(MSG_ERROR_LOAD('file ' + input_file_name))\n traceback.print_exc()\n for key in info['experiments']:\n try:\n info['experiments'][key] = np.array(info['experiments'][key])\n except Exception:\n pass\n return info\n if ID:\n partial_id = re.compile(ID)\n entries = [entry for entry in entries if partial_id.match(get_output(entry, no_objects = True)['ID'])]\n if parameters:\n parameters = {key:(repr(value) if not isinstance(value,RE) else value) for (key,value) in parameters.items()}\n def matches_parameters(entry):\n out = get_output(entry,no_objects=True)\n if not 'parameters' in out:\n return False\n else:\n test = out['parameters']\n for key,value in parameters.items():\n if key not in test:\n return False\n if isinstance(value,RE):\n if not re.match(value.s,test[key]):\n return False\n else:\n if not value == test[key]:\n return False \n return True\n entries = [entry for entry in entries if matches_parameters(entry)]\n if len(entries)>1 and need_unique:\n basenames = [os.path.basename(get_output(entry,no_objects=True)['path']).rsplit('_',1) for entry in entries]\n if len(set(bn[0] for bn in basenames))==1:\n entries = [max(entries,key = lambda entry: get_output(entry,no_objects=True)['time'])]\n entries = unique(entries)\n if not need_unique:\n return (get_output(entry, no_objects=no_objects) for entry in entries)\n else:\n if len(entries) == 0:\n raise ValueError(MSG_ERROR_NOMATCH)\n if len(entries) > 1:\n raise ValueError(MSG_ERROR_MULTIMATCH(entries))\n return get_output(entries[0], no_objects=no_objects)\n\ndef _is_experiment_directory(directory):\n return os.path.isfile(os.path.join(directory, FILE_INFO))\n\ndef _max_mem(m, type): # @ReservedAssignment\n if m == '':\n return -1\n if type == 'detail': # Output of memory_profiler package\n find = re.compile('.*?(\\d{1,}\\.\\d{4}) MiB.*')\n matches = [find.match(line) for line in m.splitlines()]\n values = [float(match.groups()[0]) for match in matches if match is not None]\n return max(values) - min(values)\n else: # Output of print_peak_memory\n return float(m)\n \ndef _get_directory(directory,func,name,no_date, debug, git, classification):\n basepath = _get_base_directory(directory,func,name,no_date)\n if debug:\n directory = os.path.join(basepath, FILE_DEBUG)\n try:\n shutil.rmtree(directory)\n except FileNotFoundError:\n pass\n os.makedirs(directory)\n return directory, FILE_DEBUG\n try_classification_based_directory = 1 if classification else 0\n for attempt in range(20): # Try keyword format, then random words, fail if cannot find unused\n ID = random_word(length = LEN_ID,dictionary = (attempt<10))\n if try_classification_based_directory:\n directory = os.path.join(basepath,classification+f'_{try_classification_based_directory-1}')\n else:\n directory = os.path.join(basepath,ID)\n try:\n os.makedirs(directory)\n if git and _git_has_tag(git,STR_GIT_TAG(ID)):\n delete_empty_directories([directory])\n else:\n return directory,ID\n except OSError as exc:\n if exc.errno == errno.EEXIST:\n if try_classification_based_directory:\n try_classification_based_directory += 1\n else:\n if try_classification_based_directory:#There was a problem creating a directory with the keyword format\n try_classification_based_directory = 0#Maybe illegal characters in parameters, try it with random words\n else:#Already tried random words, something else is wrong\n raise\n raise ValueError(MSG_ERROR_DIR)\n\ndef _git_command(string, add_input=True):\n string = 'git ' + string\n output = '$ ' + string + '\\n' if add_input else ''\n args = shlex.split(string)\n output += subprocess.check_output(args, stderr=subprocess.STDOUT).decode('UTF8')\n return output\n\ndef _git_id():\n return _git_command('log --format=\"%H\" -n 1', add_input=False).rstrip()\n\ndef _git_has_tag(path,tag):\n initial_directory = os.getcwd()\n os.chdir(path)\n try:\n out = _git_command('tag --list',add_input = False)\n return tag in out.splitlines() \n except subprocess.CalledProcessError:\n os.chdir(initial_directory)\n raise\n\ndef _git_snapshot(path, commit_body, ID):\n initial_directory = os.getcwd()\n os.chdir(path)\n git_directory = _git_command('rev-parse --show-toplevel', add_input=False).rstrip()\n os.chdir(git_directory)\n active_branch = _git_command('rev-parse --abbrev-ref HEAD', add_input=False)\n try:\n out = ''\n out += _git_command('add --all')\n out += _git_command('rm -r --cached .')\n out += _git_command('add --all')\n out += _git_command('commit --allow-empty -m \"{0} \\n {1}\"'.format(STR_GIT_COMMIT_TITLE(active_branch), commit_body))\n out += _git_command('tag {}'.format(STR_GIT_TAG(ID)))\n snap_id = _git_id()\n out += _git_command('reset HEAD~1')\n except subprocess.CalledProcessError as e:\n raise GitError(traceback.format_exc(), out + '\\n' + str(e.output))\n except Exception:\n raise GitError(traceback.format_exc(), out)\n os.chdir(initial_directory)\n return snap_id, out, git_directory\n"
] | [
[
"numpy.array",
"matplotlib.pyplot.figure",
"numpy.cumsum",
"numpy.random.get_state"
]
] |
goncaloperes/mcdm | [
"2316d06adee76c4d82aef43522d31505d0f431e6"
] | [
"mcdm/tests/test_correlate.py"
] | [
"#!/usr/bin/env python3\n\n# Copyright (c) 2020 Dimitrios-Georgios Akestoridis\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport mcdm\nimport numpy as np\nimport unittest\n\n\nclass TestCorrelate(unittest.TestCase):\n def test_pearson_linear(self):\n \"\"\"Test the Pearson method with a linear association.\"\"\"\n z_matrix = np.array(\n [[0.0, 0.0, 1.0],\n [0.1, 0.2, 0.8],\n [0.2, 0.4, 0.6],\n [0.3, 0.7, 0.3],\n [0.6, 0.8, 0.2],\n [0.8, 0.9, 0.1],\n [1.0, 1.0, 0.0]],\n dtype=np.float64)\n obtained_corr_matrix = mcdm.correlate(z_matrix, \"Pearson\")\n expected_corr_matrix = np.array(\n [[ 1.0000000, 0.9314381, -0.9314381], # noqa: E201\n [ 0.9314381, 1.0000000, -1.0000000], # noqa: E201\n [-0.9314381, -1.0000000, 1.0000000]], # noqa: E201\n dtype=np.float64)\n np.testing.assert_allclose(obtained_corr_matrix,\n expected_corr_matrix)\n self.assertEqual(obtained_corr_matrix.dtype,\n expected_corr_matrix.dtype)\n\n def test_pearson_nonlinear(self):\n \"\"\"Test the Pearson method with a non-linear association.\"\"\"\n z_matrix = np.array(\n [[0.0, 0.0, 0.0],\n [0.0, 0.0, 1.0],\n [0.2, 0.5, 0.0],\n [0.2, 0.5, 1.0],\n [0.4, 1.0, 0.0],\n [0.4, 1.0, 1.0],\n [0.6, 1.0, 0.0],\n [0.6, 1.0, 1.0],\n [0.8, 0.5, 0.0],\n [0.8, 0.5, 1.0],\n [1.0, 0.0, 0.0],\n [1.0, 0.0, 1.0]],\n dtype=np.float64)\n obtained_corr_matrix = mcdm.correlate(z_matrix, \"Pearson\")\n expected_corr_matrix = np.array(\n [[1.0, 0.0, 0.0],\n [0.0, 1.0, 0.0],\n [0.0, 0.0, 1.0]],\n dtype=np.float64)\n np.testing.assert_allclose(obtained_corr_matrix,\n expected_corr_matrix)\n self.assertEqual(obtained_corr_matrix.dtype,\n expected_corr_matrix.dtype)\n\n def test_pearson_float32(self):\n \"\"\"Test the Pearson method with a float32 NumPy array.\"\"\"\n z_matrix = np.array(\n [[0.0, 0.0, 1.0],\n [0.1, 0.2, 0.8],\n [0.2, 0.4, 0.6],\n [0.3, 0.7, 0.3],\n [0.6, 0.8, 0.2],\n [0.8, 0.9, 0.1],\n [1.0, 1.0, 0.0]],\n dtype=np.float32)\n obtained_corr_matrix = mcdm.correlate(z_matrix, \"Pearson\")\n expected_corr_matrix = np.array(\n [[ 1.0000000, 0.9314381, -0.9314381], # noqa: E201\n [ 0.9314381, 1.0000000, -1.0000000], # noqa: E201\n [-0.9314381, -1.0000000, 1.0000000]], # noqa: E201\n dtype=np.float64)\n np.testing.assert_allclose(obtained_corr_matrix,\n expected_corr_matrix)\n self.assertEqual(obtained_corr_matrix.dtype,\n expected_corr_matrix.dtype)\n\n def test_pearson_nested_list(self):\n \"\"\"Test the Pearson method with a nested list.\"\"\"\n z_matrix = [\n [0.0, 0.0, 1.0],\n [0.1, 0.2, 0.8],\n [0.2, 0.4, 0.6],\n [0.3, 0.7, 0.3],\n [0.6, 0.8, 0.2],\n [0.8, 0.9, 0.1],\n [1.0, 1.0, 0.0],\n ]\n obtained_corr_matrix = mcdm.correlate(z_matrix, \"Pearson\")\n expected_corr_matrix = np.array(\n [[ 1.0000000, 0.9314381, -0.9314381], # noqa: E201\n [ 0.9314381, 1.0000000, -1.0000000], # noqa: E201\n [-0.9314381, -1.0000000, 1.0000000]], # noqa: E201\n dtype=np.float64)\n np.testing.assert_allclose(obtained_corr_matrix,\n expected_corr_matrix)\n self.assertEqual(obtained_corr_matrix.dtype,\n expected_corr_matrix.dtype)\n\n def test_pearson_missing_element_exception(self):\n \"\"\"Test the Pearson method with a missing element.\"\"\"\n z_matrix = [\n [0.0, 0.0, 1.0],\n [0.1, 0.2, 0.8],\n [0.2, 0.4, 0.6],\n [0.3, 0.7, 0.3],\n [0.6, 0.8, 0.2],\n [0.8, 0.9],\n [1.0, 1.0, 0.0],\n ]\n self.assertRaises(ValueError, mcdm.correlate, z_matrix, \"Pearson\")\n\n def test_abspearson_linear(self):\n \"\"\"Test the AbsPearson method with a linear association.\"\"\"\n z_matrix = np.array(\n [[0.0, 0.0, 1.0],\n [0.1, 0.2, 0.8],\n [0.2, 0.4, 0.6],\n [0.3, 0.7, 0.3],\n [0.6, 0.8, 0.2],\n [0.8, 0.9, 0.1],\n [1.0, 1.0, 0.0]],\n dtype=np.float64)\n obtained_corr_matrix = mcdm.correlate(z_matrix, \"AbsPearson\")\n expected_corr_matrix = np.array(\n [[1.0000000, 0.9314381, 0.9314381],\n [0.9314381, 1.0000000, 1.0000000],\n [0.9314381, 1.0000000, 1.0000000]],\n dtype=np.float64)\n np.testing.assert_allclose(obtained_corr_matrix,\n expected_corr_matrix)\n self.assertEqual(obtained_corr_matrix.dtype,\n expected_corr_matrix.dtype)\n\n def test_abspearson_nonlinear(self):\n \"\"\"Test the AbsPearson method with a non-linear association.\"\"\"\n z_matrix = np.array(\n [[0.0, 0.0, 0.0],\n [0.0, 0.0, 1.0],\n [0.2, 0.5, 0.0],\n [0.2, 0.5, 1.0],\n [0.4, 1.0, 0.0],\n [0.4, 1.0, 1.0],\n [0.6, 1.0, 0.0],\n [0.6, 1.0, 1.0],\n [0.8, 0.5, 0.0],\n [0.8, 0.5, 1.0],\n [1.0, 0.0, 0.0],\n [1.0, 0.0, 1.0]],\n dtype=np.float64)\n obtained_corr_matrix = mcdm.correlate(z_matrix, \"AbsPearson\")\n expected_corr_matrix = np.array(\n [[1.0, 0.0, 0.0],\n [0.0, 1.0, 0.0],\n [0.0, 0.0, 1.0]],\n dtype=np.float64)\n np.testing.assert_allclose(obtained_corr_matrix,\n expected_corr_matrix)\n self.assertEqual(obtained_corr_matrix.dtype,\n expected_corr_matrix.dtype)\n\n def test_abspearson_float32(self):\n \"\"\"Test the AbsPearson method with a float32 NumPy array.\"\"\"\n z_matrix = np.array(\n [[0.0, 0.0, 1.0],\n [0.1, 0.2, 0.8],\n [0.2, 0.4, 0.6],\n [0.3, 0.7, 0.3],\n [0.6, 0.8, 0.2],\n [0.8, 0.9, 0.1],\n [1.0, 1.0, 0.0]],\n dtype=np.float32)\n obtained_corr_matrix = mcdm.correlate(z_matrix, \"AbsPearson\")\n expected_corr_matrix = np.array(\n [[1.0000000, 0.9314381, 0.9314381],\n [0.9314381, 1.0000000, 1.0000000],\n [0.9314381, 1.0000000, 1.0000000]],\n dtype=np.float64)\n np.testing.assert_allclose(obtained_corr_matrix,\n expected_corr_matrix)\n self.assertEqual(obtained_corr_matrix.dtype,\n expected_corr_matrix.dtype)\n\n def test_abspearson_nested_list(self):\n \"\"\"Test the AbsPearson method with a nested list.\"\"\"\n z_matrix = [\n [0.0, 0.0, 1.0],\n [0.1, 0.2, 0.8],\n [0.2, 0.4, 0.6],\n [0.3, 0.7, 0.3],\n [0.6, 0.8, 0.2],\n [0.8, 0.9, 0.1],\n [1.0, 1.0, 0.0],\n ]\n obtained_corr_matrix = mcdm.correlate(z_matrix, \"AbsPearson\")\n expected_corr_matrix = np.array(\n [[1.0000000, 0.9314381, 0.9314381],\n [0.9314381, 1.0000000, 1.0000000],\n [0.9314381, 1.0000000, 1.0000000]],\n dtype=np.float64)\n np.testing.assert_allclose(obtained_corr_matrix,\n expected_corr_matrix)\n self.assertEqual(obtained_corr_matrix.dtype,\n expected_corr_matrix.dtype)\n\n def test_abspearson_missing_element_exception(self):\n \"\"\"Test the AbsPearson method with a missing element.\"\"\"\n z_matrix = [\n [0.0, 0.0, 1.0],\n [0.1, 0.2, 0.8],\n [0.2, 0.4, 0.6],\n [0.3, 0.7, 0.3],\n [0.6, 0.8, 0.2],\n [0.8, 0.9],\n [1.0, 1.0, 0.0],\n ]\n self.assertRaises(ValueError, mcdm.correlate, z_matrix, \"AbsPearson\")\n\n def test_dcor_linear(self):\n \"\"\"Test the dCor method with a linear association.\"\"\"\n z_matrix = np.array(\n [[0.0, 0.0, 1.0],\n [0.1, 0.2, 0.8],\n [0.2, 0.4, 0.6],\n [0.3, 0.7, 0.3],\n [0.6, 0.8, 0.2],\n [0.8, 0.9, 0.1],\n [1.0, 1.0, 0.0]],\n dtype=np.float64)\n obtained_corr_matrix = mcdm.correlate(z_matrix, \"dCor\")\n expected_corr_matrix = np.array(\n [[1.0000000, 0.9369189, 0.9369189],\n [0.9369189, 1.0000000, 1.0000000],\n [0.9369189, 1.0000000, 1.0000000]],\n dtype=np.float64)\n np.testing.assert_allclose(obtained_corr_matrix,\n expected_corr_matrix)\n self.assertEqual(obtained_corr_matrix.dtype,\n expected_corr_matrix.dtype)\n\n def test_dcor_nonlinear(self):\n \"\"\"Test the dCor method with a non-linear association.\"\"\"\n z_matrix = np.array(\n [[0.0, 0.0, 0.0],\n [0.0, 0.0, 1.0],\n [0.2, 0.5, 0.0],\n [0.2, 0.5, 1.0],\n [0.4, 1.0, 0.0],\n [0.4, 1.0, 1.0],\n [0.6, 1.0, 0.0],\n [0.6, 1.0, 1.0],\n [0.8, 0.5, 0.0],\n [0.8, 0.5, 1.0],\n [1.0, 0.0, 0.0],\n [1.0, 0.0, 1.0]],\n dtype=np.float64)\n obtained_corr_matrix = mcdm.correlate(z_matrix, \"dCor\")\n expected_corr_matrix = np.array(\n [[1.0000000, 0.5186014, 0.0000000],\n [0.5186014, 1.0000000, 0.0000000],\n [0.0000000, 0.0000000, 1.0000000]],\n dtype=np.float64)\n np.testing.assert_allclose(obtained_corr_matrix,\n expected_corr_matrix)\n self.assertEqual(obtained_corr_matrix.dtype,\n expected_corr_matrix.dtype)\n\n def test_dcor_independence(self):\n \"\"\"Test the dCor method with independent criteria.\"\"\"\n z_matrix = np.array(\n [[0.0, 0.0],\n [0.0, 1.0]],\n dtype=np.float64)\n obtained_corr_matrix = mcdm.correlate(z_matrix, \"dCor\")\n expected_corr_matrix = np.array(\n [[1.0000000, 0.0000000],\n [0.0000000, 1.0000000]],\n dtype=np.float64)\n np.testing.assert_allclose(obtained_corr_matrix,\n expected_corr_matrix)\n self.assertEqual(obtained_corr_matrix.dtype,\n expected_corr_matrix.dtype)\n\n def test_dcor_float32(self):\n \"\"\"Test the dCor method with a float32 NumPy array.\"\"\"\n z_matrix = np.array(\n [[0.0, 0.0, 1.0],\n [0.1, 0.2, 0.8],\n [0.2, 0.4, 0.6],\n [0.3, 0.7, 0.3],\n [0.6, 0.8, 0.2],\n [0.8, 0.9, 0.1],\n [1.0, 1.0, 0.0]],\n dtype=np.float32)\n obtained_corr_matrix = mcdm.correlate(z_matrix, \"dCor\")\n expected_corr_matrix = np.array(\n [[1.0000000, 0.9369189, 0.9369189],\n [0.9369189, 1.0000000, 1.0000000],\n [0.9369189, 1.0000000, 1.0000000]],\n dtype=np.float64)\n np.testing.assert_allclose(obtained_corr_matrix,\n expected_corr_matrix)\n self.assertEqual(obtained_corr_matrix.dtype,\n expected_corr_matrix.dtype)\n\n def test_dcor_nested_list(self):\n \"\"\"Test the dCor method with a nested list.\"\"\"\n z_matrix = [\n [0.0, 0.0, 1.0],\n [0.1, 0.2, 0.8],\n [0.2, 0.4, 0.6],\n [0.3, 0.7, 0.3],\n [0.6, 0.8, 0.2],\n [0.8, 0.9, 0.1],\n [1.0, 1.0, 0.0],\n ]\n obtained_corr_matrix = mcdm.correlate(z_matrix, \"dCor\")\n expected_corr_matrix = np.array(\n [[1.0000000, 0.9369189, 0.9369189],\n [0.9369189, 1.0000000, 1.0000000],\n [0.9369189, 1.0000000, 1.0000000]],\n dtype=np.float64)\n np.testing.assert_allclose(obtained_corr_matrix,\n expected_corr_matrix)\n self.assertEqual(obtained_corr_matrix.dtype,\n expected_corr_matrix.dtype)\n\n def test_dcor_missing_element_exception(self):\n \"\"\"Test the dCor method with a missing element.\"\"\"\n z_matrix = [\n [0.0, 0.0, 1.0],\n [0.1, 0.2, 0.8],\n [0.2, 0.4, 0.6],\n [0.3, 0.7, 0.3],\n [0.6, 0.8, 0.2],\n [0.8, 0.9],\n [1.0, 1.0, 0.0],\n ]\n self.assertRaises(ValueError, mcdm.correlate, z_matrix, \"dCor\")\n\n def test_unknown_correlate_exception(self):\n \"\"\"Test the selection of an unknown correlation method.\"\"\"\n z_matrix = np.array(\n [[0.0, 0.0, 1.0],\n [0.1, 0.2, 0.8],\n [0.2, 0.4, 0.6],\n [0.3, 0.7, 0.3],\n [0.6, 0.8, 0.2],\n [0.8, 0.9, 0.1],\n [1.0, 1.0, 0.0]],\n dtype=np.float64)\n self.assertRaises(ValueError, mcdm.correlate, z_matrix, \"Unknown\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] | [
[
"numpy.array",
"numpy.testing.assert_allclose"
]
] |
chelini/iree-llvm-sandbox | [
"28978acb424bbac552f04856b28eb6c87478c289"
] | [
"python/examples/depthwise_conv/definitions.py"
] | [
"import itertools\n\nfrom typing import Any, List, Mapping, Optional, Sequence, Tuple, Union\n\nimport numpy as np\n\nfrom mlir.ir import *\nfrom mlir.dialects import arith, builtin, linalg, scf, std, tensor\n\nfrom ..core.compilation import attach_inplaceable_attributes, attach_passthrough\nfrom ..core.problem_definition import *\nfrom ..core.utils import *\n\nfrom . import ops\n\n# TODO: Orthogonal configuration object.\navx512 = True\n\nRANK_RELATED_DIMS = \"DHW\"\n\n\ndef find_contiguous_rank_dims(lst: str) -> Tuple[int, int]:\n \"\"\"Returns the positions of the rank-related dimensions in the list.\n\n Return a pair of values where the first value is the index of the first\n rank-related dimension and the second value is the index of the dimension\n immediately after the last rank-related dimension in the input format string.\n Expects rank-related dimensions to be contiguous in the format.\n\n Arguments:\n lst: convolution format string containing 'D', 'H' and 'W' to indicate\n rank-related dimensions.\n \"\"\"\n start, end = None, None\n for i, char in enumerate(lst):\n if char in RANK_RELATED_DIMS:\n if start is None:\n start = i\n end = i\n return start, end + 1\n\n\nclass DepthwiseConvolutionProblem(ProblemDefinition):\n \"\"\"Benchmarking problem definition for 1/2/3D depthwise convolutions.\n\n Supports various convolution formats, to be specified at construction time,\n as long as the \"image\" dimensions (depth, height, width) are contiguous and\n provided in the same order. For example, NCHW is supported but NHCW or NCWH\n are not. Note that in practice, \"image\" dimension names are interchangeable.\n \"\"\"\n\n def __init__(self, input_format: str, kernel_format: str,\n strides: Optional[List[int]], dilations: Optional[List[int]]):\n \"\"\"Creates a new Depthwise ConvolutionProblem definition with the given\n\n specification.\n\n The rank and kind of the convolution are specified by the formatting\n strings. Each character in the string corresponds to one dimension of the\n depthwise convolution, with the following characters supported:\n\n D: depth dimension of the image;\n H: height dimension of the image;\n W: width dimension of the image;\n N: number of the image (input only);\n C: common channels of the image and kernel;\n\n D and H characters may be missing to create a 2d or 1d depthwise\n convolution,\n respectively. The D, H, W characters must be provided in this order and be\n contiguous in the string. Other characters are mandatory and may appear\n anywhere in the format string.\n\n The format of the output is derived as:\n\n - all non-DHW dimensions of the input that precede DHW in the input format\n specification, in the same order, except C.\n - all non-DHW dimensions of the kernel hat precede DHW in the kernel\n format specification, in the same order, except C.\n - DHW dimensions;\n - all non-DHW dimensions of the input that follow DHW in the input format,\n in the same order, except C.\n - all non-DHW dimensions of the kernel that follow DHW in the kernel\n format, in the same order, except C.\n\n The convolution can have strides and dilations provided as extra arguments.\n\n The IR builder for the operation is expected to exist in the \"ops\" object\n (typically, module) visible in the scope under the name\n \"depthwise_conv_nd_ifmt_kfmt\" where n is the convolution rank, ifmt is the\n lowercased input format and kfmt is the lowercased kernel format.\n\n Arguments:\n input_format: format of the input as described above.\n kernel_format: format of the kernel as described above.\n strides: convolution strides, if None, assumed to be all 1.\n dilations: convolution dilations, if None, assumed to be all 1.\n \"\"\"\n rank = len(input_format) - 2\n assert len(kernel_format) == rank + 1\n\n if strides is None:\n strides = [1] * rank\n if dilations is None:\n dilations = [1] * rank\n\n assert len(strides) == rank\n assert len(dilations) == rank\n for char in input_format:\n assert char in \"NCDHW\", \"Unexpected input format specifier.\"\n for char in kernel_format:\n assert char in \"CDHW\", \"Unexpected kernel format specifier.\"\n\n name = format(\n f\"depthwise_conv_{len(input_format) - 2}d_{input_format.lower()}_{kernel_format.lower()}\"\n )\n assert name in ops.__dict__, f\"Operation not defined: {name}\"\n\n self.__strides = strides\n self.__dilations = dilations\n self.__input_format = input_format\n self.__kernel_format = kernel_format\n self.__op_builder = ops.__dict__[name]\n\n @property\n def keys(self) -> List[str]:\n \"\"\"Returns the list of parameter keys for the current problem definition.\"\"\"\n result = list(self.__input_format)\n result += [\n \"K\" + char if char in \"DHW\" else char\n for char in self.__kernel_format\n if char.upper() != \"C\"\n ]\n result += [\"strides\", \"dilations\"]\n return result\n\n def __infer_output_shape(self, sizes: Mapping[str, Any]) -> List[int]:\n \"\"\"Compute the output shape given the list of problem parameters.\"\"\"\n input_rank_dims_start, input_rank_dims_end = find_contiguous_rank_dims(\n self.__input_format)\n kernel_rank_dims_start, kernel_rank_dims_end = find_contiguous_rank_dims(\n self.__kernel_format)\n\n # 1. Non-DHW leading input dimensions.\n output_dims = [\n sizes[d] for d in self.__input_format[:input_rank_dims_start]\n ]\n\n # 2. Non-DHW leading kernel dimensions except C.\n for d in self.__kernel_format[:kernel_rank_dims_start]:\n if d == \"C\":\n continue\n output_dims.append(sizes[d])\n\n # 3. DHW dimensions.\n output_dims += [\n sizes[d]\n for d in self.__input_format[input_rank_dims_start:input_rank_dims_end]\n ]\n\n # 4. Non-DHW trailing input dimensions.\n output_dims += [sizes[d] for d in self.__input_format[input_rank_dims_end:]]\n\n # 5. Non-DHW trailing kernel dimensions except C.\n for d in self.__kernel_format[kernel_rank_dims_end:]:\n if d == \"C\":\n continue\n output_dims.append(sizes[d])\n return output_dims\n\n def shapes_builder(self, sizes: Mapping[str, Any]) -> List[List[int]]:\n \"\"\"Constructs the tensor shapes given problem parameters.\"\"\"\n strides, dilations = sizes[\"strides\"], sizes[\"dilations\"]\n rank = len(self.__input_format) - 2\n\n # The input size is computed by increasing its rank-related dimensions to\n # accommodate kernel sizes with eventual strides and dilations, e.g.:\n # dims(I) = [N,\n # (H - 1) * SH + 1 + (KH - 1) * DH + 1,\n # (W - 1) * SW + 1 + (KW - 1) * DW + 1,\n #. C]\n #\n # Shape relations on rank-related dimensions:\n # iw = [(ow - 1) * sw + 1] + [(kw - 1) * dw + 1] - 1\n # => iw = [(ow - 1) * sw] + [(kw - 1) * dw] + 1\n # => ow = [iw - (kw - 1) * dw - 1] / sw + 1\n input_shape = []\n for char in self.__input_format:\n if char in RANK_RELATED_DIMS[-rank:]:\n attribute_pos = RANK_RELATED_DIMS[-rank:].index(char)\n ow = sizes[char]\n sw = strides[attribute_pos]\n kw = sizes[\"K\" + char]\n dw = dilations[attribute_pos]\n input_shape.append(((ow - 1) * sw + 1) + ((kw - 1) * dw + 1) - 1)\n else:\n input_shape.append(sizes[char])\n\n # The kernel size is derived directly from the corresponding parameters,\n # e.g.:\n # dims(K) = [KH, KW, C].\n # C is provided for the input, take it there.\n kernel_shape = []\n for char in self.__kernel_format:\n if char not in RANK_RELATED_DIMS[-rank:]:\n kernel_shape.append(sizes[char])\n else:\n kernel_shape.append(sizes[\"K\" + char])\n\n return [input_shape, kernel_shape, self.__infer_output_shape(sizes)]\n\n def gflop_count_builder(self, sizes: Mapping[str, Any]) -> float:\n \"\"\"Returns the GFLOp count given problem parameters.\"\"\"\n return 2.0 * np.prod([\n sizes[k] for k in set(sizes.keys()) - set([\"strides\", \"dilations\"])\n ]) / 1.e9\n\n def gbyte_count_builder(self, sizes: Mapping[str, Any],\n types: Sequence[np.dtype]) -> float:\n \"\"\"Return the GByte count given problem parameters.\"\"\"\n shapes = self.shapes_builder(sizes)\n\n lhs_np_type, rhs_np_type, res_np_type = types\n ro_gbytes = 1.e-9 * sum(np.prod(s) * np.dtype(t).itemsize \\\n for s, t in zip(shapes[:2], [lhs_np_type, rhs_np_type]))\n rw_gbytes = 2.e-9 * np.prod(shapes[-1:]) * np.dtype(res_np_type).itemsize\n return ro_gbytes + rw_gbytes\n\n def tensors_np_builder(self, sizes: Mapping[str, Any],\n types: Sequence[np.dtype]) -> List[np.dtype]:\n \"\"\"Returns random NumPy suitable for calling the kernel.\"\"\"\n shapes = self.shapes_builder(sizes)\n tensors = [\n realign(np.random.rand(*s).astype(t), byte_alignment=64)\n for s, t in zip(shapes, types)\n ]\n # Uncomment to simplify debugging.\n # tensors = [\n # realign(np.arange(1, np.prod(s) + 1).reshape(s).astype(t), \\\n # byte_alignment=64) \\\n # for s, t in zip(shapes, types)\n # ]\n tensors[-1].fill(0.)\n return tensors\n\n def reference_np(self, I: np.dtype, K: np.dtype, O: np.dtype):\n \"\"\"Reference numpy implementation, used for checking and benchmarking \n against.\n\n Given the list of NumPy arrays, computes the expected result and compares it\n with the actual result. Raises ValueError on mismatch.\n \"\"\"\n\n input_rank_dims_start, input_rank_dims_end = find_contiguous_rank_dims(\n self.__input_format)\n kernel_rank_dims_start, kernel_rank_dims_end = find_contiguous_rank_dims(\n self.__kernel_format)\n\n # Compute the output rank-related dimensions by doing the computation\n # inverse to that of shape_builder. An alternative would be to extract them\n # from the shape of O but that requires knowing their position in the list.\n input_rank_dims = I.shape[input_rank_dims_start:input_rank_dims_end]\n kernel_rank_dims = K.shape[kernel_rank_dims_start:kernel_rank_dims_end]\n # Shape relations on rank-related dimensions:\n # iw = [(ow - 1) * sw + 1] + [(kw - 1) * dw + 1] - 1\n # => iw = [(ow - 1) * sw] + [(kw - 1) * dw] + 1\n # => ow = [iw - (kw - 1) * dw - 1] / sw + 1\n iw = np.array(input_rank_dims)\n kw = np.array(kernel_rank_dims)\n dw = np.array(self.__dilations)\n sw = np.array(self.__strides)\n ones = np.ones(iw.shape, dtype=int)\n output_rank_dims = tuple((iw - (kw - ones) * dw - ones) // sw + 1)\n input_parallel_dim = self.__input_format[::-1].index(\"N\")\n kernel_parallel_dim = self.__kernel_format[::-1].index(\"C\")\n\n # Compute the convolution by taking (overlapping) output-sized slices of the\n # input that start at 0,1,...,KH, 0,1,...KW offsets, computing their\n # tensordot-product with the corresponding slices of the kernel, and\n # accumulating the result by addition. For example, for the NHWC, HWC\n # convolution, the computation is\n # O += I[:, kh:kh+H, kw:kw+W, :] . K[kh, kw, :] for kh in 0..KH,\n # for kw in 0..KW.\n # with H and W dimensions being reduced by tensordot and N, C remaining.\n for ks in itertools.product(*map(range, kernel_rank_dims)):\n input_slices = []\n ranked_pos = 0\n for char in self.__input_format:\n if char in RANK_RELATED_DIMS:\n # slice(a,b) is just a flexible form of a:b.\n input_slices.append(\n slice(\n self.__dilations[ranked_pos] * ks[ranked_pos],\n self.__dilations[ranked_pos] * ks[ranked_pos] +\n output_rank_dims[ranked_pos]))\n ranked_pos += 1\n else:\n input_slices.append(slice(None))\n slice_input = I[tuple(input_slices)]\n\n input_strides = []\n ranked_pos = 0\n for i, char in enumerate(self.__input_format):\n if char in RANK_RELATED_DIMS:\n input_strides.append( \\\n slice_input.strides[i] * self.__strides[ranked_pos])\n ranked_pos += 1\n else:\n input_strides.append(slice_input.strides[i])\n slice_input.strides = input_strides\n\n kernel_slices = []\n ranked_pos = 0\n for char in self.__kernel_format:\n if char in RANK_RELATED_DIMS:\n kernel_slices.append(ks[ranked_pos])\n ranked_pos += 1\n else:\n kernel_slices.append(slice(None))\n slice_kernel = K[tuple(kernel_slices)]\n\n # Starting from: O(n, w, c) += I(n, w + kw, c) * K(kw, c)\n # Unrolling on KW just gives O(n, w, c) += I(n, w, c) * K(c)\n O += slice_input * slice_kernel\n\n # TODO: Here we have \"I(N, H, W, C), K(H, W, C) O(N, H, W, C)\" layout but\n # Pytorch wants \"I(N, C, H, W), K(C, 1, H, W) O(N, C, H, W)\".\n # Doing permute/reshape manipulations passes the assertions but perf is\n # abysmal as only a `at::TensorIteratorBase::loop_2d_from_1d` is called.\n # TODO: how do I pass a preallocated output?\n def reference_pt(self, I, K, O):\n import torch\n import torch.nn.functional as F\n if len(I.shape) == 3:\n I = torch.permute(I, (0, 2, 1))\n K = torch.reshape(K, (1, *K.shape))\n K = torch.permute(K, (2, 0, 1))\n F.conv1d(I,\n K,\n stride=tuple(self.__strides),\n dilation=tuple(self.__dilations),\n groups=K.shape[0])\n elif len(I.shape) == 4:\n I = torch.permute(I, (0, 3, 1, 2))\n K = torch.reshape(K, (1, *K.shape))\n K = torch.permute(K, (3, 0, 1, 2))\n F.conv2d(I,\n K,\n stride=tuple(self.__strides),\n dilation=tuple(self.__dilations),\n groups=K.shape[0])\n else:\n assert False, f'NYI depthwise conv for: I={I.shape} * K={K.shape} -> O={O.shape}'\n\n def check_np(self, I: np.dtype, K: np.dtype, O: np.dtype):\n \"\"\"Checks whether the computation results correspond to the reference\n implementation.\n\n Given the list of NumPy arrays, computes the expected result and compares it\n with the actual result. Raises ValueError on mismatch.\n \"\"\"\n\n reference_O = np.zeros(O.shape)\n self.reference_np(I, K, reference_O)\n\n if not np.allclose(O, reference_O):\n delta = O - reference_O\n max_abs_delta = max(delta.max(), delta.min(), key=abs)\n raise ValueError(f\"max_abs_delta: {max_abs_delta} -> FAILURE \")\n\n def types_mlir_builder(self, sizes: Mapping[str, Any],\n types: Sequence[Type]) -> List[Type]:\n \"\"\"Returns the list of MLIR types for arguments of this computation.\"\"\"\n shapes = self.shapes_builder(sizes)\n return [RankedTensorType.get(s, t) for s, t in zip(shapes, types)]\n\n def build_problem_under_context_manager(\n self, name: str, mlir_types: Sequence[Type]) -> builtin.FuncOp:\n \"\"\"Constructs MLIR that implements the current convolution.\n\n Expects to operate under MLIR's context manager.\n\n Arguments:\n name: name of the MLIR function to generate (must be unique in its parent\n module).\n mlir_types: types of arguments of this computation.\n \"\"\"\n global avx512\n\n output_type = mlir_types[-1]\n func = builtin.FuncOp(name, (mlir_types, [output_type]))\n # TODO: need something much more flexible to add func argument attributes.\n attach_inplaceable_attributes(func, inplaceable=[False, False, True])\n attach_passthrough(func, [StringAttr.get(\"noinline\")], avx512=avx512)\n\n with InsertionPoint(func.add_entry_block()):\n zero = arith.ConstantOp(output_type.element_type, 0.0)\n # Skip fill to emulate fusion.\n # tensor_zero = func.arguments[2]\n tensor_zero = linalg.FillOp(output=func.arguments[2], value=zero)\n conv = self.__op_builder(func.arguments[0],\n func.arguments[1],\n outs=[tensor_zero],\n strides=self.__strides,\n dilations=self.__dilations)\n std.ReturnOp([conv])\n\n return func\n"
] | [
[
"numpy.ones",
"numpy.allclose",
"numpy.zeros",
"numpy.dtype",
"torch.permute",
"torch.reshape",
"numpy.random.rand",
"numpy.prod",
"numpy.array"
]
] |
tontsam/audioset_tagging_cnn | [
"223f0a92fb753a34ac145a64c6713ee497fbda0c"
] | [
"pytorch/pytorch_utils.py"
] | [
"import numpy as np\nimport time\nimport torch\nimport torch.nn as nn\n\n\ndef move_data_to_device(x, device):\n if 'float' in str(x.dtype):\n x = torch.Tensor(x)\n elif 'int' in str(x.dtype):\n x = torch.LongTensor(x)\n else:\n return x\n\n return x.to(device)\n\n\ndef do_mixup(x, mixup_lambda):\n \"\"\"Mixup x of even indexes (0, 2, 4, ...) with x of odd indexes \n (1, 3, 5, ...).\n\n Args:\n x: (batch_size * 2, ...)\n mixup_lambda: (batch_size * 2,)\n\n Returns:\n out: (batch_size, ...)\n \"\"\"\n out = (x[0 :: 2].transpose(0, -1) * mixup_lambda[0 :: 2] + \\\n x[1 :: 2].transpose(0, -1) * mixup_lambda[1 :: 2]).transpose(0, -1)\n return out\n \n\ndef append_to_dict(dict, key, value):\n if key in dict.keys():\n dict[key].append(value)\n else:\n dict[key] = [value]\n\n\ndef forward(model, generator, return_input=False, \n return_target=False):\n \"\"\"Forward data to a model.\n \n Args: \n model: object\n generator: object\n return_input: bool\n return_target: bool\n\n Returns:\n audio_name: (audios_num,)\n clipwise_output: (audios_num, classes_num)\n (ifexist) segmentwise_output: (audios_num, segments_num, classes_num)\n (ifexist) framewise_output: (audios_num, frames_num, classes_num)\n (optional) return_input: (audios_num, segment_samples)\n (optional) return_target: (audios_num, classes_num)\n \"\"\"\n output_dict = {}\n device = next(model.parameters()).device\n time1 = time.time()\n\n # Forward data to a model in mini-batches\n for n, batch_data_dict in enumerate(generator):\n print(n)\n batch_waveform = move_data_to_device(batch_data_dict['waveform'], device)\n \n with torch.no_grad():\n model.eval()\n batch_output = model(batch_waveform)\n\n append_to_dict(output_dict, 'audio_name', batch_data_dict['audio_name'])\n\n append_to_dict(output_dict, 'clipwise_output', \n batch_output['clipwise_output'].data.cpu().numpy())\n\n if 'segmentwise_output' in batch_output.keys():\n append_to_dict(output_dict, 'segmentwise_output', \n batch_output['segmentwise_output'].data.cpu().numpy())\n\n if 'framewise_output' in batch_output.keys():\n append_to_dict(output_dict, 'framewise_output', \n batch_output['framewise_output'].data.cpu().numpy())\n \n if return_input:\n append_to_dict(output_dict, 'waveform', batch_data_dict['waveform'])\n \n if return_target:\n if 'target' in batch_data_dict.keys():\n append_to_dict(output_dict, 'target', batch_data_dict['target'])\n\n if n % 10 == 0:\n print(' --- Inference time: {:.3f} s / 10 iterations ---'.format(\n time.time() - time1))\n time1 = time.time()\n\n for key in output_dict.keys():\n output_dict[key] = np.concatenate(output_dict[key], axis=0)\n\n return output_dict\n\n\ndef interpolate(x, ratio):\n \"\"\"Interpolate data in time domain. This is used to compensate the \n resolution reduction in downsampling of a CNN.\n \n Args:\n x: (batch_size, time_steps, classes_num)\n ratio: int, ratio to interpolate\n\n Returns:\n upsampled: (batch_size, time_steps * ratio, classes_num)\n \"\"\"\n (batch_size, time_steps, classes_num) = x.shape\n upsampled = x[:, :, None, :].repeat(1, 1, ratio, 1)\n upsampled = upsampled.reshape(batch_size, time_steps * ratio, classes_num)\n return upsampled\n\n\ndef pad_framewise_output(framewise_output, frames_num):\n \"\"\"Pad framewise_output to the same length as input frames. The pad value \n is the same as the value of the last frame.\n\n Args:\n framewise_output: (batch_size, frames_num, classes_num)\n frames_num: int, number of frames to pad\n\n Outputs:\n output: (batch_size, frames_num, classes_num)\n \"\"\"\n if frames_num == framewise_output.shape[1]:\n return framewise_output \n pad = framewise_output[:, -1 :, :].repeat(1, frames_num - framewise_output.shape[1], 1)\n \"\"\"tensor for padding\"\"\"\n\n output = torch.cat((framewise_output, pad), dim=1)\n \"\"\"(batch_size, frames_num, classes_num)\"\"\"\n\n return output\n\n\ndef count_parameters(model):\n return sum(p.numel() for p in model.parameters() if p.requires_grad)\n\n\ndef count_flops(model, audio_length):\n \"\"\"Count flops. Code modified from others' implementation.\n \"\"\"\n multiply_adds = True\n list_conv2d=[]\n def conv2d_hook(self, input, output):\n batch_size, input_channels, input_height, input_width = input[0].size()\n output_channels, output_height, output_width = output[0].size()\n \n kernel_ops = self.kernel_size[0] * self.kernel_size[1] * (self.in_channels / self.groups) * (2 if multiply_adds else 1)\n bias_ops = 1 if self.bias is not None else 0\n \n params = output_channels * (kernel_ops + bias_ops)\n flops = batch_size * params * output_height * output_width\n \n list_conv2d.append(flops)\n\n list_conv1d=[]\n def conv1d_hook(self, input, output):\n batch_size, input_channels, input_length = input[0].size()\n output_channels, output_length = output[0].size()\n \n kernel_ops = self.kernel_size[0] * (self.in_channels / self.groups) * (2 if multiply_adds else 1)\n bias_ops = 1 if self.bias is not None else 0\n \n params = output_channels * (kernel_ops + bias_ops)\n flops = batch_size * params * output_length\n \n list_conv1d.append(flops)\n \n list_linear=[] \n def linear_hook(self, input, output):\n batch_size = input[0].size(0) if input[0].dim() == 2 else 1\n \n weight_ops = self.weight.nelement() * (2 if multiply_adds else 1)\n bias_ops = self.bias.nelement()\n \n flops = batch_size * (weight_ops + bias_ops)\n list_linear.append(flops)\n \n list_bn=[] \n def bn_hook(self, input, output):\n list_bn.append(input[0].nelement() * 2)\n \n list_relu=[] \n def relu_hook(self, input, output):\n list_relu.append(input[0].nelement() * 2)\n \n list_pooling2d=[]\n def pooling2d_hook(self, input, output):\n batch_size, input_channels, input_height, input_width = input[0].size()\n output_channels, output_height, output_width = output[0].size()\n \n kernel_ops = self.kernel_size * self.kernel_size\n bias_ops = 0\n params = output_channels * (kernel_ops + bias_ops)\n flops = batch_size * params * output_height * output_width\n \n list_pooling2d.append(flops)\n\n list_pooling1d=[]\n def pooling1d_hook(self, input, output):\n batch_size, input_channels, input_length = input[0].size()\n output_channels, output_length = output[0].size()\n \n kernel_ops = self.kernel_size[0]\n bias_ops = 0\n \n params = output_channels * (kernel_ops + bias_ops)\n flops = batch_size * params * output_length\n \n list_pooling2d.append(flops)\n \n def foo(net):\n childrens = list(net.children())\n if not childrens:\n if isinstance(net, nn.Conv2d):\n net.register_forward_hook(conv2d_hook)\n elif isinstance(net, nn.Conv1d):\n net.register_forward_hook(conv1d_hook)\n elif isinstance(net, nn.Linear):\n net.register_forward_hook(linear_hook)\n elif isinstance(net, nn.BatchNorm2d) or isinstance(net, nn.BatchNorm1d):\n net.register_forward_hook(bn_hook)\n elif isinstance(net, nn.ReLU):\n net.register_forward_hook(relu_hook)\n elif isinstance(net, nn.AvgPool2d) or isinstance(net, nn.MaxPool2d):\n net.register_forward_hook(pooling2d_hook)\n elif isinstance(net, nn.AvgPool1d) or isinstance(net, nn.MaxPool1d):\n net.register_forward_hook(pooling1d_hook)\n else:\n print('Warning: flop of module {} is not counted!'.format(net))\n return\n for c in childrens:\n foo(c)\n\n # Register hook\n foo(model)\n \n device = device = next(model.parameters()).device\n input = torch.rand(1, audio_length).to(device)\n\n out = model(input)\n \n total_flops = sum(list_conv2d) + sum(list_conv1d) + sum(list_linear) + \\\n sum(list_bn) + sum(list_relu) + sum(list_pooling2d) + sum(list_pooling1d)\n \n return total_flops\n"
] | [
[
"torch.rand",
"torch.no_grad",
"numpy.concatenate",
"torch.LongTensor",
"torch.cat",
"torch.Tensor"
]
] |
DTRademaker/pdb2sql | [
"e4ddb4bd554b5623ca7101ebc4f4cd9acc0a422a"
] | [
"pdb2sql/align.py"
] | [
"import numpy as np\nfrom .pdb2sqlcore import pdb2sql\nfrom .interface import interface\nfrom .transform import rot_xyz_around_axis\n\n\ndef align(pdb, axis='x', export=True, **kwargs):\n \"\"\"Align the max principal component of a structure along one of the cartesian axis\n\n Arguments:\n pdb {str, pdb2sql} -- the pdbfile or the sql database of the complex\n\n Keyword Arguments:\n axis {str} -- cartesian axis for alignement (default: {'x'})\n export {bool} -- export the aligned structure to file\n **kwargs {dict} -- option to select subpart of the structure for alignement\n\n Returns:\n pd2sql -- sql databse of the aligned structure\n\n Example:\n >>> pdb = '1AK4'\n >>> sql = align(pdb,chainID='A')\n \"\"\"\n\n if not isinstance(pdb, pdb2sql):\n sql = pdb2sql(pdb)\n else:\n sql = pdb\n\n # extract coordinate\n xyz = np.array(sql.get('x,y,z', **kwargs))\n\n # get the pca eigenvect we want to align\n vect = get_max_pca_vect(xyz)\n\n # align the sql\n sql = align_pca_vect(sql, vect, axis)\n\n # export the pdbfile\n if export:\n export_aligned(sql)\n\n return sql\n\n\ndef align_interface(ppi, plane='xy', export=True, **kwargs):\n \"\"\"align the interface of a complex in a given plane\n\n Arguments:\n ppi {interface} -- sql interface or pdb file\n plane {str} -- plane for alignement\n\n Keyword Arguments:\n export {bool} -- write a pdb file (default: {True})\n kwargs {dict} -- keyword argument from interface.get_contact_atoms method\n \"\"\"\n\n if not isinstance(ppi, interface):\n sql = interface(ppi)\n else:\n sql = ppi\n\n index_contact = sql.get_contact_atoms(**kwargs)\n row_id = []\n for _, v in index_contact.items():\n row_id += v\n xyz = np.array(sql.get('x,y,z', rowID=row_id))\n\n # get the pca eigenvect we want to align\n vect = get_min_pca_vect(xyz)\n\n # align the sql database\n dict_plane = {'xy': 'z', 'xz': 'y', 'yz': 'x'}\n sql = align_pca_vect(sql, vect, dict_plane[plane])\n\n # export the pdbfile\n if export:\n export_aligned(sql)\n\n return sql\n\n\ndef align_pca_vect(sql, vect, axis):\n \"\"\"Align the pca vect of the sql along th axis\n\n Arguments:\n sql {pdb2sql} -- sqldb of the complex\n vect {np.ndarray} -- pca eigenvect\n axis {str} -- axis along which to align vect\n\n Returns:\n pdb2sql -- aligned sqldb\n \"\"\"\n\n # rotation angles\n phi, theta = get_rotation_angle(vect)\n\n # complete coordinate\n xyz = np.array(sql.get('x,y,z'))\n\n # align them\n xyz = _align_along_axis(xyz, axis, phi, theta)\n\n # update the sql\n sql.update('x,y,z', xyz)\n\n return sql\n\n\ndef export_aligned(sql):\n \"\"\"export a pdb file of the aligned pdb\n\n Arguments:\n sql {pdb2sql} -- aligned sqldb\n \"\"\"\n if isinstance(sql.pdbfile, str):\n fname = sql.pdbfile.rstrip('.pdb') + '_aligned.pdb'\n else:\n fname = 'aligned_structure.pdb'\n sql.exportpdb(fname)\n\n\ndef get_rotation_angle(vmax):\n \"\"\"Extracts the rotation angles from the PCA\n\n Arguments:\n u {np.array} -- eigenvalues of the PCA\n V {np.array} -- eigenvectors of the PCA\n \"\"\"\n\n # extract max eigenvector\n\n x, y, z = vmax\n r = np.linalg.norm(vmax)\n\n # rotation angle\n phi = np.arctan2(y, x)\n theta = np.arccos(z/r)\n\n return phi, theta\n\n\ndef get_max_pca_vect(xyz):\n \"\"\"Get the max eigenvector of th pca\n\n Arguments:\n xyz {numpy.ndarray} -- matrix of the atoms coordinates\n \"\"\"\n u, v = pca(xyz)\n return v[:, np.argmax(u)]\n\n\ndef get_min_pca_vect(xyz):\n \"\"\"Get the min eigenvector of th pca\n\n Arguments:\n xyz {numpy.ndarray} -- matrix of the atoms coordinates\n \"\"\"\n u, v = pca(xyz)\n return v[:, np.argmin(u)]\n\n\ndef pca(mat):\n \"\"\"computes the principal component analysis of the points A\n\n Arguments:\n A {numpy.ndarray} -- matrix of points [npoints x ndim]\n\n Returns:\n tuple -- eigenvalues, eigenvectors, score\n \"\"\"\n scat = (mat-np.mean(mat.T, axis=1)).T\n u, v = np.linalg.eig(np.cov(scat))\n return u, v\n\n\ndef _align_along_axis(xyz, axis, phi, theta):\n \"\"\"align the xyz coordinates along the given axi\n\n Arguments:\n xyz {numpy.ndarray} -- coordinates of the atoms\n axis {str} -- axis to align\n phi {float} -- azimuthal angle\n theta {float} -- the other angles\n\n Raises:\n ValueError: axis should be x y or z\n\n Returns:\n nd.array -- rotated coordinates\n \"\"\"\n\n # align along preferred axis\n if axis == 'x':\n xyz = rot_xyz_around_axis(xyz, np.array([0, 0, 1]), -phi)\n xyz = rot_xyz_around_axis(\n xyz, np.array([0, 1, 0]), np.pi/2 - theta)\n\n elif axis == 'y':\n xyz = rot_xyz_around_axis(\n xyz, np.array([0, 0, 1]), np.pi/2 - phi)\n xyz = rot_xyz_around_axis(\n xyz, np.array([0, 1, 0]), np.pi/2 - theta)\n\n elif axis == 'z':\n xyz = rot_xyz_around_axis(xyz, np.array([0, 0, 1]), -phi)\n xyz = rot_xyz_around_axis(xyz, np.array([0, 1, 0]), -theta)\n else:\n raise ValueError('axis should be x, y ,or z')\n\n return xyz\n"
] | [
[
"numpy.arctan2",
"numpy.argmin",
"numpy.cov",
"numpy.arccos",
"numpy.argmax",
"numpy.array",
"numpy.linalg.norm",
"numpy.mean"
]
] |
JudyJin/torchTS | [
"2856e1bae8be3b9fdc23dcc2e8339674f1558ba5"
] | [
"tests/nn/test_loss.py"
] | [
"import pytest\nimport torch\n\nfrom torchts.nn.loss import masked_mae_loss, mis_loss, quantile_loss\n\n\[email protected]\ndef y_true():\n data = [1, 2, 3]\n return torch.tensor(data)\n\n\[email protected]\ndef y_pred():\n data = [1.1, 1.9, 3.1]\n return torch.tensor(data)\n\n\ndef test_masked_mae_loss(y_true, y_pred):\n \"\"\"Test masked_mae_loss()\"\"\"\n loss = masked_mae_loss(y_pred, y_true)\n assert loss == pytest.approx(0.1)\n\n\[email protected](\n \"lower, upper, interval, expected_loss\",\n [\n ([1, 2, 3], [1.1, 2.1, 3.1], 0.8, 0.1),\n ([0.9, 1.9, 2.9], [1.1, 2.1, 3.1], 0.8, 0.2),\n ([0.9, 1.9, 2.9], [1.1, 2.1, 3.1], 0.95, 0.2),\n ([0.7, 1.9, 2.9], [0.9, 2.1, 3.1], 0.8, 1.6 / 3),\n ([0.7, 1.9, 2.9], [0.9, 2.1, 3.1], 0.95, 4.6 / 3),\n ([0.9, 1.9, 3.1], [1.1, 2.1, 3.3], 0.8, 1.6 / 3),\n ([0.9, 1.9, 3.1], [1.1, 2.1, 3.3], 0.95, 4.6 / 3),\n ],\n)\ndef test_mis_loss(y_true, lower, upper, interval, expected_loss):\n \"\"\"Test quantile_loss()\"\"\"\n y_true = y_true.reshape(-1, 1)\n y_pred = torch.transpose(torch.tensor([lower, upper]), 0, 1)\n loss = mis_loss(y_pred, y_true, interval)\n assert loss == pytest.approx(expected_loss)\n\n\[email protected](\n \"quantile, expected_loss\", [(0.05, 0.065), (0.5, 0.05), (0.95, 0.035)]\n)\ndef test_quantile_loss(y_true, y_pred, quantile, expected_loss):\n \"\"\"Test quantile_loss()\"\"\"\n loss = quantile_loss(y_pred, y_true, quantile)\n assert loss == pytest.approx(expected_loss)\n"
] | [
[
"torch.tensor"
]
] |
gabrieloexle/mercury-ml | [
"cc663f84a26ee66ae105bbfc0cd1cbd5629031cd"
] | [
"mercury_ml/common/providers/data_wrappers/pandas.py"
] | [
"class PandasDataWrapper():\n \"\"\"\n A DataWrapper with a Pandas DataFrame as its underlying data\n \"\"\"\n\n def __init__(self, underlying, field_names):\n self.underlying = underlying\n self.field_names = field_names\n\n def slice_on_column_names(self, column_names):\n \"\"\"\n Returns a Pandas DataFrame consisting of the columns that are present in the column_names list\n\n :param list list column_names: the names of the columns to return\n :return: Pandas DataFrame consisting of the selected columns\n \"\"\"\n\n return self.underlying[column_names]\n\n def to_h2o(self, factor_columns_list=None):\n \"\"\"\n Creates a new H2ODataWrapper based on this PandasDataWrapper and returns it as a new object\n\n :params list factor_columns_list: The names of the columns that should be treated as factors\n :return: a new H2ODataWrapper\n \"\"\"\n\n from mercury_ml.common.providers.data_wrappers.h2o import H2ODataWrapper\n import h2o\n df_h2o = h2o.H2OFrame(self.underlying)\n\n # convert columns\n if not factor_columns_list:\n factor_columns_list = []\n\n for factor_column_name in factor_columns_list:\n df_h2o[factor_column_name] = df_h2o[factor_column_name].asfactor()\n\n return H2ODataWrapper(df_h2o, self.field_names)\n\n def to_numpy(self):\n \"\"\"\n Creates a new NumpyDataWrapper based on this PandasDataWrapper and returns it as a new object\n\n :return: a new NumpyDataWrapper\n \"\"\"\n\n from mercury_ml.common.providers.data_wrappers.numpy import NumpyDataWrapper\n return NumpyDataWrapper(self.underlying.values, self.field_names)\n\n def to_spark(self, spark_session_params=None):\n \"\"\"\n Creates a new SparkDataWrapper based on this PandasDataWrapper and returns it as a new object\n\n :return: a new SparkDataWrapper\n :param: dict spark_session_params: A dictionary of parameters according to which to get or initialize a Spark session\n \"\"\"\n\n from mercury_ml.common.providers.data_wrappers.spark import SparkDataWrapper\n from mercury_ml.spark.providers.session import get_or_create_spark_session\n self.underlying.columns = self.underlying.columns.astype(str)\n\n if not spark_session_params:\n spark_session_params = {}\n spark = get_or_create_spark_session(**spark_session_params)\n\n return SparkDataWrapper(\n underlying=spark.createDataFrame(self.underlying),\n field_names=self.field_names\n )\n\n def to_h2o_sparkling(self, spark_session_params=None, factor_columns_list=None, h2o_sparkling_params=None):\n \"\"\"\n Creates a new H2ODataWrapper based on this PandasDataWrapper and returns it as a new object\n\n :param list factor_columns_list: The names of the columns that should be treated as factors\n :param list spark_session_params: A dictionary of parameters according to which to get or initialize a Spark session\n :param list h2o_sparkling_params: A dictionary of parameters according to which to get or initialize an H2OSparkling session\n\n :return: a new H2ODataWrapper\n \"\"\"\n\n if spark_session_params is None:\n spark_session_params = {}\n\n if h2o_sparkling_params is None:\n h2o_sparkling_params = {}\n\n return self.to_spark(spark_session_params).to_h2o_sparkling(factor_columns_list=factor_columns_list,\n h2o_sparkling_params=h2o_sparkling_params)\n\n def to_pandas(self):\n return self\n\n def concatenate(self, right_data_wrapper):\n \"\"\"\n Concatenates this PandasDataWrapper with the one given in right_data_wrapper and returns a new PandasDataWrapper\n\n :param PandasDataWrapper right_data_wrapper: to be concatenated to the right of \"self\"\n :return: a new PandasDataWrapper\n \"\"\"\n\n import pandas as pd\n new_underlying = pd.concat([self.underlying, right_data_wrapper.underlying], axis=1)\n new_field_names = self.field_names + right_data_wrapper.field_names\n return PandasDataWrapper(\n underlying=new_underlying,\n field_names=new_field_names\n )\n\n"
] | [
[
"pandas.concat"
]
] |
furgerf/advent-of-code-2019 | [
"f2c6ad9d401c91a7b04bb699d233a7d6ec9da2ac"
] | [
"day_13/day_13.py"
] | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom enum import Enum, unique\n\nimport numpy as np\n\nfrom day import Day\nfrom intcode import Intcode\n\n\nclass Day13(Day):\n\n @unique\n class TileType(Enum):\n NOTHING = 0\n WALL = 1\n BLOCK = 2\n PADDLE = 3\n BALL = 4\n\n class GameMap:\n\n def __init__(self):\n self._game_map = None\n self._paddle_x = None\n self._ball_x = None\n self._current_score = None\n\n @property\n def paddle_x(self):\n return self._paddle_x\n\n @property\n def ball_x(self):\n return self._ball_x\n\n @property\n def current_score(self):\n return self._current_score\n\n @property\n def number_of_blocks(self):\n return len(np.where(self._game_map == Day13.TileType.BLOCK.value)[0])\n\n def _initialize_map(self, updates):\n max_x = max(u[0] for u in updates)\n max_y = max(u[1] for u in updates)\n self._game_map = np.zeros(shape=(max_x+1, max_y+1))\n\n def update_map(self, update_list):\n updates = list(zip(*[update_list[i::3] for i in range(3)]))\n if self._game_map is None:\n self._initialize_map(updates)\n\n for update in updates:\n if update[0] == -1 and update[1] == 0:\n self._current_score = update[2]\n continue\n\n self._game_map[update[0], update[1]] = Day13.TileType(update[2]).value\n if update[2] == Day13.TileType.BALL.value:\n self._ball_x = update[0]\n if update[2] == Day13.TileType.PADDLE.value:\n self._paddle_x = update[0]\n\n def __init__(self):\n super(Day13, self).__init__(13)\n\n def parse_data(self):\n return self.parse_intcode_data()\n\n def part_1(self):\n intcode = Intcode(self.data[:])\n intcode.compute()\n game_map = Day13.GameMap()\n game_map.update_map(intcode.outputs)\n return game_map.number_of_blocks\n\n @property\n def part_1_solution(self):\n return 258\n\n def part_2(self):\n own_data = self.data[:]\n own_data[0] = 2\n intcode = Intcode(own_data)\n game_map = Day13.GameMap()\n while not intcode.partial_compute():\n game_map.update_map(intcode.outputs)\n intcode.clear_output()\n intcode.add_input(np.sign(game_map.ball_x - game_map.paddle_x))\n game_map.update_map(intcode.outputs)\n return game_map.current_score\n\n @property\n def part_2_solution(self):\n return 12765\n"
] | [
[
"numpy.where",
"numpy.sign",
"numpy.zeros"
]
] |
KaidongLi/pytorch-LatticePointClassifier | [
"5c00bb0f808a928ea57acb8a79364d62eb955cee"
] | [
"data_analysis/conv_att2npz.py"
] | [
"import os\n\nimport pdb\n\nimport argparse\nimport numpy as np\n\nPEND_ORIG = 'orig'\n# PEND_NEW = 'splat'\nPEND_ATT = 'adv'\nPEND_ATT_FAIL = 'adv_f'\nPEND_ATT2D = '2dimg'\nPEND_PRED = 'pred'\n\nparser = argparse.ArgumentParser(\n description='test shape net show image')\nparser.add_argument('--img_dir', default='../log', type=str)\n# parser.add_argument('--check_success', action='store_true', default=False, help='Whether to check success attack [default: False]')\n# parser.add_argument('--plot', action='store_true', default=False, help='Whether to show image [default: False]')\n\nargs = parser.parse_args()\n\ndef conv_att2npz():\n\n # pend_attack = PEND_ATT if args.check_success else PEND_ATT_FAIL\n # norm_succ = []\n # norm_fail = []\n\n # ct_sample = {}\n # ct_succ = {}\n # l_cls = []\n\n all_ori_pc = []\n all_adv_pc = []\n all_real_lbl = []\n all_target_lbl = []\n all_succ = []\n\n for file in os.listdir(args.img_dir):\n if file.endswith(PEND_ORIG + '.npy'):\n pt_cld_ori = np.load( os.path.join(args.img_dir, file) )\n pt_cld_atts= np.load( os.path.join(args.img_dir, file.split(PEND_ORIG)[0]+PEND_ATT+'.npy') )\n pt_cld_attf= np.load( os.path.join(args.img_dir, file.split(PEND_ORIG)[0]+PEND_ATT_FAIL+'.npy') )\n # pt_cld_a2d = np.load( os.path.join(args.img_dir, file.split(PEND_ORIG)[0]+PEND_ATT2D+'.npy') )\n pt_cld_prd = np.load( os.path.join(args.img_dir, file.split(PEND_ORIG)[0]+PEND_PRED+'.npy') )\n\n print(file)\n\n tgt = file.split('_')\n vic = int(tgt[0])\n tgt = int(tgt[1])\n\n\n for i in range(pt_cld_ori.shape[0]):\n\n if tgt == pt_cld_prd[i] \\\n and (pt_cld_atts[i].max() - pt_cld_atts[i].min() > 0) :\n flg = True\n all_adv_pc.append(pt_cld_atts[None, i])\n elif (not tgt == pt_cld_prd[i]) \\\n and (pt_cld_attf[i].max() - pt_cld_attf[i].min() > 0) \\\n and (pt_cld_atts[i].max()==1 and pt_cld_atts[i].min()==1) :\n flg = False\n all_adv_pc.append(pt_cld_attf[None, i])\n else:\n print('conflict!!!')\n pdb.set_trace()\n\n all_ori_pc.append(pt_cld_ori[None, i])\n all_real_lbl.append(vic)\n all_target_lbl.append(tgt)\n all_succ.append(flg)\n\n\n # pdb.set_trace()\n all_ori_pc = np.concatenate(all_ori_pc, axis=0) # [num_data, K, 3]\n all_adv_pc = np.concatenate(all_adv_pc, axis=0) # [num_data, K, 3]\n all_real_lbl = np.array(all_real_lbl) # [num_data]\n all_target_lbl = np.array(all_target_lbl) # [num_data]\n all_succ = np.array(all_succ) # [num_data]\n pdb.set_trace()\n\n\n np.savez(os.path.join(args.img_dir, 'pntnet_pert_6.npz'),\n test_pc=all_adv_pc.astype(np.float32),\n test_ori_pc=all_ori_pc.astype(np.float32),\n test_label=all_real_lbl.astype(np.uint8),\n target_label=all_target_lbl.astype(np.uint8),\n is_succ=all_succ.astype(np.bool))\n\n\ndef add_blank(str_mod, length=2):\n for i in range(2 - len(str_mod)):\n str_mod = ' '+str_mod\n return str_mod\n\nif __name__=='__main__':\n conv_att2npz()\n"
] | [
[
"numpy.array",
"numpy.concatenate"
]
] |
Noba1anc3/recommenders | [
"fb886881137ca3add05bb0d478a4751207ca5559"
] | [
"tensorflow_recommenders/layers/loss.py"
] | [
"# Copyright 2022 The TensorFlow Recommenders Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Lint-as: python3\n\"\"\"Layers related to loss computation.\"\"\"\nfrom typing import Tuple\n\nimport numpy as np\nimport tensorflow as tf\n\nMAX_FLOAT = np.finfo(np.float32).max / 100.0\nMIN_FLOAT = np.finfo(np.float32).min / 100.0\n\n\ndef _gather_elements_along_row(data: tf.Tensor,\n column_indices: tf.Tensor) -> tf.Tensor:\n \"\"\"Gathers elements from a 2D tensor given the column indices of each row.\n\n A more efficient way of gathering elements from 2D tensor than tf.gather_nd().\n First, gets the flat 1D indices to gather from. Then flattens the data to 1D\n and uses tf.gather() to generate 1D output and finnally reshapes the\n output back to 2D.\n\n Args:\n data: A [N, M] 2D `Tensor`.\n column_indices: A [N, K] 2D `Tensor` denoting for each row, the K column\n indices to gather elements from the data `Tensor`.\n\n Returns:\n A [N, K] `Tensor` including output elements gathered from data `Tensor`.\n\n Raises:\n ValueError: if the first dimensions of data and column_indices don't match.\n \"\"\"\n with tf.control_dependencies(\n [tf.assert_equal(tf.shape(data)[0], tf.shape(column_indices)[0])]):\n num_row = tf.shape(data)[0]\n num_column = tf.shape(data)[1]\n num_gathered = tf.shape(column_indices)[1]\n row_indices = tf.tile(\n tf.expand_dims(tf.range(num_row), -1),\n [1, num_gathered])\n flat_data = tf.reshape(data, [-1])\n flat_indices = tf.reshape(\n row_indices * num_column + column_indices, [-1])\n return tf.reshape(\n tf.gather(flat_data, flat_indices), [num_row, num_gathered])\n\n\nclass HardNegativeMining(tf.keras.layers.Layer):\n \"\"\"Transforms logits and labels to return hard negatives.\"\"\"\n\n def __init__(self, num_hard_negatives: int) -> None:\n \"\"\"Initializes the layer.\n\n Args:\n num_hard_negatives: How many hard negatives to return.\n \"\"\"\n\n super(HardNegativeMining, self).__init__()\n self._num_hard_negatives = num_hard_negatives\n\n def call(self, logits: tf.Tensor,\n labels: tf.Tensor) -> Tuple[tf.Tensor, tf.Tensor]:\n \"\"\"Filters logits and labels with per-query hard negative mining.\n\n The result will include logits and labels for num_hard_negatives\n negatives as well as the positive candidate.\n\n Args:\n logits: [batch_size, number_of_candidates] tensor of logits.\n labels: [batch_size, number_of_candidates] one-hot tensor of labels.\n\n Returns:\n logits: [batch_size, num_hard_negatives + 1] tensor of logits.\n labels: [batch_size, num_hard_negatives + 1] one-hot tensor of labels.\n \"\"\"\n\n # Number of sampled logits, i.e, the number of hard negatives to be\n # sampled (k) + number of true logit (1) per query, capped by batch size.\n num_sampled = tf.minimum(self._num_hard_negatives + 1, tf.shape(logits)[1])\n # To gather indices of top k negative logits per row (query) in\n # logits, true logits need to be excluded. First replace the true\n # logits (corresponding to positive labels) with a large score value\n # and then select the top k + 1 logits from each\n # row so that selected indices include the indices of true logit + top k\n # negative logits. This approach is to avoid using inefficient\n # tf.boolean_mask() when excluding true logits.\n\n # For each query, get the indices of the logits which have the highest\n # k + 1 logit values, including the highest k negative logits and one true\n # logit.\n _, col_indices = tf.nn.top_k(\n logits + labels * MAX_FLOAT, k=num_sampled, sorted=False)\n\n # Gather sampled logits and corresponding labels.\n logits = _gather_elements_along_row(logits, col_indices)\n labels = _gather_elements_along_row(labels, col_indices)\n\n return logits, labels\n\n\nclass RemoveAccidentalHits(tf.keras.layers.Layer):\n \"\"\"Zeroes the logits of accidental negatives.\"\"\"\n\n def call(self, labels: tf.Tensor, logits: tf.Tensor,\n candidate_ids: tf.Tensor) -> tf.Tensor:\n \"\"\"Zeros selected logits.\n\n For each row in the batch, zeros the logits of negative candidates that have\n the same id as the positive candidate in that row.\n\n Args:\n labels: [batch_size, num_candidates] one-hot labels tensor.\n logits: [batch_size, num_candidates] logits tensor.\n candidate_ids: [num_candidates] candidate identifiers tensor\n\n Returns:\n logits: Modified logits.\n \"\"\"\n # A more principled way is to implement softmax_cross_entropy_with_logits\n # with a input mask. Here we approximate so by letting accidental hits\n # have extremely small logits (MIN_FLOAT) for ease-of-implementation.\n\n candidate_ids = tf.expand_dims(candidate_ids, 1)\n\n positive_indices = tf.math.argmax(labels, axis=1)\n positive_candidate_ids = tf.gather(candidate_ids, positive_indices)\n\n duplicate = tf.cast(\n tf.equal(positive_candidate_ids, tf.transpose(candidate_ids)),\n labels.dtype\n )\n duplicate = duplicate - labels\n\n return logits + duplicate * MIN_FLOAT\n\n\nclass SamplingProbablityCorrection(tf.keras.layers.Layer):\n \"\"\"Sampling probability correction.\"\"\"\n\n def __call__(self, logits: tf.Tensor,\n candidate_sampling_probability: tf.Tensor) -> tf.Tensor:\n \"\"\"Corrects the input logits to account for candidate sampling probability.\"\"\"\n\n return logits - tf.math.log(\n tf.clip_by_value(candidate_sampling_probability, 1e-6, 1.))\n"
] | [
[
"tensorflow.gather",
"tensorflow.shape",
"tensorflow.reshape",
"tensorflow.range",
"tensorflow.nn.top_k",
"tensorflow.expand_dims",
"tensorflow.math.argmax",
"tensorflow.clip_by_value",
"numpy.finfo",
"tensorflow.transpose"
]
] |
MikePham05/segmentation_models.pytorch | [
"f61acfedf5e5b122430abb71181126bf1a288a94"
] | [
"segmentation_models_pytorch/losses/lovasz.py"
] | [
"\"\"\"\nLovasz-Softmax and Jaccard hinge loss in PyTorch\nMaxim Berman 2018 ESAT-PSI KU Leuven (MIT License)\n\"\"\"\n\nfrom __future__ import print_function, division\nfrom typing import Optional\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch.nn.modules.loss import _Loss\nfrom .constants import BINARY_MODE, MULTICLASS_MODE, MULTILABEL_MODE\n\ntry:\n from itertools import ifilterfalse\nexcept ImportError: # py3k\n from itertools import filterfalse as ifilterfalse\n\n__all__ = [\"LovaszLoss\"]\n\n\ndef _lovasz_grad(gt_sorted):\n \"\"\"Compute gradient of the Lovasz extension w.r.t sorted errors\n See Alg. 1 in paper\n \"\"\"\n p = len(gt_sorted)\n gts = gt_sorted.sum()\n intersection = gts - gt_sorted.float().cumsum(0)\n union = gts + (1 - gt_sorted).float().cumsum(0)\n jaccard = 1.0 - intersection / union\n if p > 1: # cover 1-pixel case\n jaccard[1:p] = jaccard[1:p] - jaccard[0:-1]\n return jaccard\n\n\ndef _lovasz_hinge(logits, labels, per_image=True, ignore=None):\n \"\"\"\n Binary Lovasz hinge loss\n logits: [B, H, W] Variable, logits at each pixel (between -infinity and +infinity)\n labels: [B, H, W] Tensor, binary ground truth masks (0 or 1)\n per_image: compute the loss per image instead of per batch\n ignore: void class id\n \"\"\"\n if per_image:\n loss = mean(\n _lovasz_hinge_flat(*_flatten_binary_scores(log.unsqueeze(0), lab.unsqueeze(0), ignore))\n for log, lab in zip(logits, labels)\n )\n else:\n loss = _lovasz_hinge_flat(*_flatten_binary_scores(logits, labels, ignore))\n return loss\n\n\ndef _lovasz_hinge_flat(logits, labels):\n \"\"\"Binary Lovasz hinge loss\n Args:\n logits: [P] Variable, logits at each prediction (between -infinity and +infinity)\n labels: [P] Tensor, binary ground truth labels (0 or 1)\n ignore: label to ignore\n \"\"\"\n if len(labels) == 0:\n # only void pixels, the gradients should be 0\n return logits.sum() * 0.0\n signs = 2.0 * labels.float() - 1.0\n errors = 1.0 - logits * Variable(signs)\n errors_sorted, perm = torch.sort(errors, dim=0, descending=True)\n perm = perm.data\n gt_sorted = labels[perm]\n grad = _lovasz_grad(gt_sorted)\n loss = torch.dot(F.relu(errors_sorted), Variable(grad))\n return loss\n\n\ndef _flatten_binary_scores(scores, labels, ignore=None):\n \"\"\"Flattens predictions in the batch (binary case)\n Remove labels equal to 'ignore'\n \"\"\"\n scores = scores.view(-1)\n labels = labels.view(-1)\n if ignore is None:\n return scores, labels\n valid = labels != ignore\n vscores = scores[valid]\n vlabels = labels[valid]\n return vscores, vlabels\n\n\n# --------------------------- MULTICLASS LOSSES ---------------------------\n\n\ndef _lovasz_softmax(probas, labels, classes=\"present\", per_image=False, ignore=None):\n \"\"\"Multi-class Lovasz-Softmax loss\n Args:\n @param probas: [B, C, H, W] Variable, class probabilities at each prediction (between 0 and 1).\n Interpreted as binary (sigmoid) output with outputs of size [B, H, W].\n @param labels: [B, H, W] Tensor, ground truth labels (between 0 and C - 1)\n @param classes: 'all' for all, 'present' for classes present in labels, or a list of classes to average.\n @param per_image: compute the loss per image instead of per batch\n @param ignore: void class labels\n \"\"\"\n if per_image:\n loss = mean(\n _lovasz_softmax_flat(*_flatten_probas(prob.unsqueeze(0), lab.unsqueeze(0), ignore), classes=classes)\n for prob, lab in zip(probas, labels)\n )\n else:\n loss = _lovasz_softmax_flat(*_flatten_probas(probas, labels, ignore), classes=classes)\n return loss\n\n\ndef _lovasz_softmax_flat(probas, labels, classes=\"present\"):\n \"\"\"Multi-class Lovasz-Softmax loss\n Args:\n @param probas: [P, C] Variable, class probabilities at each prediction (between 0 and 1)\n @param labels: [P] Tensor, ground truth labels (between 0 and C - 1)\n @param classes: 'all' for all, 'present' for classes present in labels, or a list of classes to average.\n \"\"\"\n if probas.numel() == 0:\n # only void pixels, the gradients should be 0\n return probas * 0.0\n C = probas.size(1)\n losses = []\n class_to_sum = list(range(C)) if classes in [\"all\", \"present\"] else classes\n for c in class_to_sum:\n fg = (labels == c).type_as(probas) # foreground for class c\n if classes == \"present\" and fg.sum() == 0:\n continue\n if C == 1:\n if len(classes) > 1:\n raise ValueError(\"Sigmoid output possible only with 1 class\")\n class_pred = probas[:, 0]\n else:\n class_pred = probas[:, c]\n errors = (fg - class_pred).abs()\n errors_sorted, perm = torch.sort(errors, 0, descending=True)\n perm = perm.data\n fg_sorted = fg[perm]\n losses.append(torch.dot(errors_sorted, _lovasz_grad(fg_sorted)))\n return mean(losses)\n\n\ndef _flatten_probas(probas, labels, ignore=None):\n \"\"\"Flattens predictions in the batch\n \"\"\"\n if probas.dim() == 3:\n # assumes output of a sigmoid layer\n B, H, W = probas.size()\n probas = probas.view(B, 1, H, W)\n\n C = probas.size(1)\n probas = torch.movedim(probas, 0, -1) # [B, C, Di, Dj, Dk...] -> [B, C, Di...Dk, C]\n probas = probas.contiguous().view(-1, C) # [P, C]\n\n labels = labels.view(-1)\n if ignore is None:\n return probas, labels\n valid = labels != ignore\n vprobas = probas[valid]\n vlabels = labels[valid]\n return vprobas, vlabels\n\n\n# --------------------------- HELPER FUNCTIONS ---------------------------\ndef isnan(x):\n return x != x\n\n\ndef mean(values, ignore_nan=False, empty=0):\n \"\"\"Nanmean compatible with generators.\n \"\"\"\n values = iter(values)\n if ignore_nan:\n values = ifilterfalse(isnan, values)\n try:\n n = 1\n acc = next(values)\n except StopIteration:\n if empty == \"raise\":\n raise ValueError(\"Empty mean\")\n return empty\n for n, v in enumerate(values, 2):\n acc += v\n if n == 1:\n return acc\n return acc / n\n\n\nclass LovaszLoss(_Loss):\n def __init__(\n self,\n mode: str,\n per_image: bool = False,\n ignore_index: Optional[int] = None,\n from_logits: bool = True,\n ):\n \"\"\"Implementation of Lovasz loss for image segmentation task.\n It supports binary, multiclass and multilabel cases\n\n Args:\n mode: Loss mode 'binary', 'multiclass' or 'multilabel'\n ignore_index: Label that indicates ignored pixels (does not contribute to loss)\n per_image: If True loss computed per each image and then averaged, else computed per whole batch\n \n Shape\n - **y_pred** - torch.Tensor of shape (N, C, H, W)\n - **y_true** - torch.Tensor of shape (N, H, W) or (N, C, H, W)\n\n Reference\n https://github.com/BloodAxe/pytorch-toolbelt\n \"\"\"\n assert mode in {BINARY_MODE, MULTILABEL_MODE, MULTICLASS_MODE}\n super().__init__()\n\n self.mode = mode\n self.ignore_index = ignore_index\n self.per_image = per_image\n\n def forward(self, y_pred, y_true):\n\n if self.mode in {BINARY_MODE, MULTILABEL_MODE}:\n loss = _lovasz_hinge(y_pred, y_true, per_image=self.per_image, ignore=self.ignore_index)\n elif self.mode == MULTICLASS_MODE:\n y_pred = y_pred.softmax(dim=1)\n loss = _lovasz_softmax(y_pred, y_true, per_image=self.per_image, ignore=self.ignore_index) \n else:\n raise ValueError(\"Wrong mode {}.\".format(self.mode))\n return loss"
] | [
[
"torch.autograd.Variable",
"torch.movedim",
"torch.sort",
"torch.nn.functional.relu"
]
] |
miwojc/scikit-learn-mooc | [
"9eb67c53173218b5cd3061712c827c6a663e425a"
] | [
"python_scripts/trees_ex_02.py"
] | [
"# %% [markdown]\n# # ๐ Exercise M5.02\n#\n# The aim of this exercise is to find out whether a decision tree\n# model is able to extrapolate.\n#\n# By extrapolation, we refer to values predicted by a model outside of the\n# range of feature values seen during the training.\n#\n# We will first load the regression data.\n\n# %%\nimport pandas as pd\n\npenguins = pd.read_csv(\"../datasets/penguins_regression.csv\")\n\ndata_columns = [\"Flipper Length (mm)\"]\ntarget_column = \"Body Mass (g)\"\n\ndata_train, target_train = penguins[data_columns], penguins[target_column]\n\n# %% [markdown]\n# ```{note}\n# If you want a deeper overview regarding this dataset, you can refer to the\n# Appendix - Datasets description section at the end of this MOOC.\n# ```\n\n# %% [markdown]\n# First, create two models, a linear regression model and a decision tree\n# regression model, and fit them on the training data. Limit the depth at\n# 3 levels for the decision tree.\n\n# %%\n# Write your code here.\n\n# %% [markdown]\n# Create a testing dataset, ranging from the minimum to the maximum of the\n# flipper length of the training dataset. Get the predictions of each model\n# using this test dataset.\n\n# %%\n# Write your code here.\n\n# %% [markdown]\n# Create a scatter plot containing the training samples and superimpose the\n# predictions of both model on the top.\n\n# %%\n# Write your code here.\n\n# %% [markdown]\n# Now, we will check the extrapolation capabilities of each model. Create a\n# dataset containing the value of your previous dataset. Besides, add values\n# below and above the minimum and the maximum of the flipper length seen\n# during training.\n\n# %%\n# Write your code here.\n\n# %% [markdown]\n# Finally, make predictions with both model on this new testing set. Repeat\n# the plotting of the previous exercise.\n\n# %%\n# Write your code here.\n"
] | [
[
"pandas.read_csv"
]
] |
bsmithyman/zephyr | [
"ef74caadd74cc357b503560c3800e26c49587e61"
] | [
"zephyr/Dispatcher.py"
] | [
"import numpy as np\nfrom IPython.parallel import Reference, interactive\nfrom SimPEG import Survey, Problem, Mesh, Solver as SimpegSolver\nfrom SimPEG.Parallel import RemoteInterface, SystemSolver\nfrom SimPEG.Utils import CommonReducer\nfrom zephyr.Survey import SurveyHelm\nfrom zephyr.Problem import ProblemHelm\nimport networkx\n\nDEFAULT_DTYPE = 'double'\nDEFAULT_MPI = True\nMPI_BELLWETHERS = ['PMI_SIZE', 'OMPI_UNIVERSE_SIZE']\n\n\n@interactive\ndef setupSystem(scu):\n\n import os\n import zephyr.Kernel as Kernel\n from IPython.parallel.error import UnmetDependency\n\n global localSystem\n\n tag = (scu['ifreq'], scu['iky'])\n\n # If there is already a system to do this job on this machine, push the duplicate to another\n if tag in localSystem:\n raise UnmetDependency\n\n subSystemConfig = baseSystemConfig.copy()\n subSystemConfig.update(scu)\n\n # Set up method output caching\n if 'cacheDir' in baseSystemConfig:\n subSystemConfig['cacheDir'] = os.path.join(baseSystemConfig['cacheDir'], 'cache', '%d-%d'%tag)\n\n localSystem[tag] = Kernel.SeisFDFDKernel(subSystemConfig)\n\n return tag\n\n# def blockOnTag(fn):\n# def checkForSystem(*args, **kwargs):\n# from IPython.parallel.error import UnmetDependency\n# if not args[0] in localSystem:\n# raise UnmetDependency\n\n# return fn(*args, **kwargs)\n\n# return checkForSystem\n\n\n@interactive\ndef clearFromTag(tag):\n return localSystem[tag].clear()\n\n@interactive\n# @blockOnTag\ndef forwardFromTagAccumulate(tag, isrc, **kwargs):\n\n from IPython.parallel.error import UnmetDependency\n if not tag in localSystem:\n raise UnmetDependency\n\n key = tag[0]\n\n if not key in dPred:\n dims = (len(srcs), reduce(max, (src.nD for src in srcs)))\n dPred[key] = np.zeros(dims, dtype=localSystem[tag].dtypeComplex)\n\n if not key in fWave:\n dims = (len(srcs), localSystem[tag].mesh.nN)\n fWave[key] = np.zeros(dims, dtype=localSystem[tag].dtypeComplex)\n\n u, d = localSystem[tag].forward(srcs[isrc], dOnly=False, **kwargs)\n fWave[key][isrc,:] += u\n dPred[key][isrc,:] += d\n\n@interactive\n# @blockOnTag\ndef forwardFromTagAccumulateAll(tag, isrcs, **kwargs):\n\n for isrc in isrcs:\n forwardFromTagAccumulate(tag, isrc, **kwargs)\n\n@interactive\n# @blockOnTag\ndef backpropFromTagAccumulate(tag, isrc, **kwargs):\n\n from IPython.parallel.error import UnmetDependency\n if not tag in localSystem:\n raise UnmetDependency\n\n key = tag[0]\n\n if not key in bWave:\n dims = (len(srcs), localSystem[tag].mesh.nN)\n bWave[key] = np.zeros(dims, dtype=localSystem[tag].dtypeComplex)\n\n dResid = globals().get('dResid', None)\n if dResid is not None and key in dResid:\n resid = dResid[key][isrc,:]\n u = localSystem[tag].backprop(srcs[isrc], np.conj(resid))\n bWave[key][isrc,:] += u\n\n@interactive\n# @blockOnTag\ndef backpropFromTagAccumulateAll(tag, isrcs, **kwargs):\n\n for isrc in isrcs:\n backpropFromTagAccumulate(tag, isrc, **kwargs) \n\n\nclass SeisFDFDDispatcher(object):\n \"\"\"\n Base problem class for FDFD (Frequency Domain Finite Difference)\n modelling of systems for seismic imaging.\n \"\"\"\n\n #surveyPair = Survey.BaseSurvey\n #dataPair = Survey.Data\n systemConfig = {}\n\n Solver = SimpegSolver\n solverOpts = {}\n\n def __init__(self, systemConfig, **kwargs):\n\n self.systemConfig = systemConfig.copy()\n\n hx = [(self.systemConfig['dx'], self.systemConfig['nx']-1)]\n hz = [(self.systemConfig['dz'], self.systemConfig['nz']-1)]\n self.mesh = Mesh.TensorMesh([hx, hz], '00')\n\n # NB: Remember to set up something to do geometry conversion\n # from origin geometry to local geometry. Functions that\n # wrap the geometry vectors are probably easiest.\n\n splitkeys = ['freqs', 'nky']\n\n subConfigSettings = {}\n for key in splitkeys:\n value = self.systemConfig.pop(key, None)\n if value is not None:\n subConfigSettings[key] = value\n\n self._subConfigSettings = subConfigSettings\n\n self.remote = RemoteInterface(systemConfig.get('profile', None), systemConfig.get('MPI', None))\n dview = self.remote.dview\n\n code = '''\n import numpy as np\n import scipy as scipy\n import scipy.sparse\n import SimPEG\n import zephyr.Kernel as Kernel\n '''\n\n for command in code.strip().split('\\n'):\n dview.execute(command.strip())\n\n localcache = ['chunksPerWorker', 'ensembleClear']\n for key in localcache:\n if key in self.systemConfig:\n setattr(self, '_%s'%(key,), systemConfig[key])\n\n self.rebuildSystem()\n\n\n def _getHandles(self, systemConfig, subConfigSettings):\n\n pclient = self.remote.pclient\n dview = self.remote.dview\n lview = self.remote.lview\n\n subConfigs = self._gen25DSubConfigs(**subConfigSettings)\n nsp = len(subConfigs)\n\n # Set up dictionary for subproblem objects and push base configuration for the system\n dview['localSystem'] = {}\n self.remote['baseSystemConfig'] = systemConfig # Faster if MPI is available\n dview['dPred'] = CommonReducer()\n dview['fWave'] = CommonReducer()\n dview['bWave'] = CommonReducer()\n\n dview['forwardFromTagAccumulate'] = forwardFromTagAccumulate\n dview['forwardFromTagAccumulateAll'] = forwardFromTagAccumulateAll\n dview['backpropFromTagAccumulate'] = backpropFromTagAccumulate\n dview['backpropFromTagAccumulateAll'] = backpropFromTagAccumulateAll\n dview['clearFromTag'] = clearFromTag\n\n dview.wait()\n\n schedule = {\n 'forward': {'solve': Reference('forwardFromTagAccumulateAll'), 'clear': Reference('clearFromTag'), 'reduce': ['dPred', 'fWave']},\n 'backprop': {'solve': Reference('backpropFromTagAccumulateAll'), 'clear': Reference('clearFromTag'), 'reduce': ['bWave']},\n }\n\n self.systemsolver = SystemSolver(self, schedule)\n\n if 'parFac' in systemConfig:\n parFac = systemConfig['parFac']\n else:\n parFac = 1\n\n while parFac > 0:\n tags = lview.map_sync(setupSystem, subConfigs)\n parFac -= 1\n\n\n def _gen25DSubConfigs(self, freqs, nky, cmin):\n result = []\n weightfac = 1./(2*nky - 1) if nky > 1 else 1.# alternatively, 1/dky\n for ifreq, freq in enumerate(freqs):\n k_c = freq / cmin\n dky = k_c / (nky - 1) if nky > 1 else 0.\n for iky, ky in enumerate(np.linspace(0, k_c, nky)):\n result.append({\n 'freq': freq,\n 'ky': ky,\n 'kyweight': 2*weightfac if ky != 0 else weightfac,\n 'ifreq': ifreq,\n 'iky': iky,\n })\n return result\n\n # Fields\n def forward(self):\n\n if self.srcs is None:\n raise Exception('Transmitters not defined!')\n\n if not self.solvedF:\n dview = self.remote.dview\n dview['dPred'] = CommonReducer()\n dview['fWave'] = CommonReducer()\n self.forwardGraph = self.systemsolver('forward', slice(len(self.srcs)))\n\n def backprop(self, dresid=None):\n\n if self.srcs is None:\n raise Exception('Transmitters not defined!')\n\n # if not self.dresid:\n # raise Exception('Data residuals not defined!')\n\n if not self.solvedB:\n dview = self.remote.dview\n dview['bWave'] = CommonReducer()\n self.backpropGraph = self.systemsolver('backprop', slice(len(self.srcs)))\n\n def rebuildSystem(self, c = None):\n if c is not None:\n self.systemConfig['c'] = c\n self.rebuildSystem()\n return\n\n if hasattr(self, 'forwardGraph'):\n del self.forwardGraph\n\n if hasattr(self, 'backpropGraph'):\n del self.backpropGraph\n\n self._solvedF = False\n self._solvedB = False\n self._residualPrecomputed = False\n self._misfit = None\n\n self._subConfigSettings['cmin'] = self.systemConfig['c'].min()\n subConfigs = self._gen25DSubConfigs(**self._subConfigSettings)\n nsp = len(subConfigs)\n\n #self.curModel = self.systemConfig['c'].ravel()\n self._handles = self._getHandles(self.systemConfig, self._subConfigSettings)\n\n @property\n def srcs(self):\n if getattr(self, '_srcs', None) is None:\n self._srcs = None\n return self._srcs\n @srcs.setter\n def srcs(self, value):\n self._srcs = value\n self.rebuildSystem()\n self.remote['srcs'] = self._srcs\n\n @property\n def solvedF(self):\n if getattr(self, '_solvedF', None) is None:\n self._solvedF = False\n\n if hasattr(self, 'forwardGraph'):\n self.systemsolver.wait(self.forwardGraph)\n self._solvedF = True\n\n return self._solvedF\n\n @property\n def solvedB(self):\n if getattr(self, '_solvedB', None) is None:\n self._solvedB = False\n\n if hasattr(self, 'backpropGraph'):\n self.systemsolver.wait(self.backpropGraph)\n self._solvedB = True\n\n return self._solvedB\n\n @property\n def uF(self):\n if self.solvedF:\n return self.remote.reduce('fWave').reshape(self.fieldDims)\n else:\n return None\n\n @property\n def uB(self):\n if self.solvedB:\n return self.remote.reduce('bWave').reshape(self.fieldDims)\n else:\n return None\n\n @property\n def dPred(self):\n if self.solvedF:\n return self.remote.reduce('dPred')\n else:\n return None\n\n @property\n def g(self):\n if self.solvedF and self.solvedB:\n return self.remote.reduceMul('fWave', 'bWave', axis=0).reshape(self.modelDims)\n else:\n return None\n\n @property\n def dObs(self):\n return getattr(self, '_dobs', None)\n @dObs.setter\n def dObs(self, value):\n self._dobs = CommonReducer(value)\n self.remote['dObs'] = self._dobs\n\n def _computeResidual(self):\n if not self.solvedF:\n raise Exception('Forward problem has not been solved yet!')\n\n if self.dObs is None:\n raise Exception('No observed data has been defined!')\n\n if getattr(self, '_residualPrecomputed', None) is None:\n self._residualPrecomputed = False\n\n if not self._residualPrecomputed:\n self.remote.remoteDifferenceGatherFirst('dPred', 'dObs', 'dResid')\n #self.remote.dview.execute('dResid = CommonReducer({key: np.log(dResid[key]).real for key in dResid.keys()}')\n self._residualPrecomputed = True\n\n @property\n def residual(self):\n if self.solvedF:\n self._computeResidual()\n return self.remote.e0['dResid']\n else:\n return None\n # A day may come when it may be useful to set this, or to set dPred; but it is not this day!\n # @residual.setter\n # def residual(self, value):\n # self.remote['dResid'] = CommonReducer(value)\n\n @property\n def misfit(self):\n if self.solvedF:\n if getattr(self, '_misfit', None) is None:\n self._computeResidual()\n self._misfit = self.remote.normFromDifference('dResid')\n return self._misfit\n else:\n return None\n\n @property\n def nx(self):\n return self.systemConfig['nx']\n\n @property\n def nz(self):\n return self.systemConfig['nz']\n\n @property\n def nsrc(self):\n return len(self.systemConfig['geom']['src'])\n \n @property\n def modelDims(self):\n return (self.nz, self.nx)\n\n @property\n def fieldDims(self):\n return (self.nsrc, self.nz, self.nx)\n\n @property\n def remoteFieldDims(self):\n return (self.nsrc, self.nz*self.nx)\n\n def spawnInterfaces(self):\n\n self.survey = SurveyHelm(self)\n self.problem = ProblemHelm(self)\n\n self.survey.pair(self.problem)\n\n return self.survey, self.problem\n\n @property\n def chunksPerWorker(self):\n return getattr(self, '_chunksPerWorker', 1)\n\n @property\n def ensembleClear(self):\n return getattr(self, '_ensembleClear', False)\n \n # def fields(self, c):\n\n # self._rebuildSystem(c)\n\n # # F = FieldsSeisFDFD(self.mesh, self.survey)\n\n # # for freq in self.survey.freqs:\n # # A = self._initHelmholtzNinePoint(freq)\n # # q = self.survey.getTransmitters(freq)\n # # Ainv = self.Solver(A, **self.solverOpts)\n # # sol = Ainv * q\n # # F[q, 'u'] = sol\n\n # return F\n\n # def Jvec(self, m, v, u=None):\n # pass\n\n # def Jtvec(self, m, v, u=None):\n # pass\n"
] | [
[
"numpy.conj",
"numpy.linspace",
"numpy.zeros"
]
] |
danielgrijalva/steven-wilson-analysis | [
"6b27f37f66482504f9bdf11f3a13fc4897f122f8"
] | [
"get_lyrics.py"
] | [
"import pandas as pd\nimport lyricwikia \n\nsw = pd.read_csv('Steven Wilson.csv')\npt = pd.read_csv('Porcupine Tree.csv')\n\nsw_songs = sw['name']\npt_songs = pt['name']\n\nsw_lyrics = []\npt_lyrics = []\n\nfor song in sw_songs:\n try:\n lyrics = lyricwikia.get_lyrics('Steven Wilson', song)\n clean = lyrics.replace('\\n', ' ').replace('spoken:', '').strip().lower()\n sw_lyrics.append(clean)\n except:\n sw_lyrics.append('')\n\nfor song in pt_songs:\n try:\n lyrics = lyricwikia.get_lyrics('Porcupine Tree', song)\n clean = lyrics.replace('\\n', ' ').strip().lower()\n pt_lyrics.append(clean)\n print(pt_lyrics)\n except:\n pt_lyrics.append('')\n\nsw['lyrics'] = sw_lyrics\npt['lyrics'] = pt_lyrics\nsw.to_csv('SW Ly.csv', index=False)\npt.to_csv('PT Ly.csv', index=False)"
] | [
[
"pandas.read_csv"
]
] |
hzy5660251/memcnn | [
"1293468e4ee4ed83fcf9da36940065bbe72dd54b"
] | [
"memcnn/models/tests/test_revop.py"
] | [
"import pytest\nimport torch\nimport torch.nn\nimport numpy as np\nimport copy\nfrom memcnn.models.affine import AffineAdapterNaive, AffineAdapterSigmoid\nfrom memcnn import ReversibleBlock\n\n\ndef set_seeds(seed):\n np.random.seed(seed)\n torch.manual_seed(seed)\n\n\[email protected]('coupling', ['additive', 'affine'])\ndef test_reversible_block_additive_notimplemented(coupling):\n fm = torch.nn.Conv2d(10, 10, (3, 3), padding=1)\n X = torch.zeros(1, 20, 10, 10)\n with pytest.raises(NotImplementedError):\n f = ReversibleBlock(fm, coupling=coupling, implementation_bwd=0, implementation_fwd=-2,\n adapter=AffineAdapterNaive)\n f.forward(X)\n with pytest.raises(NotImplementedError):\n f = ReversibleBlock(fm, coupling=coupling, implementation_bwd=-2, implementation_fwd=0,\n adapter=AffineAdapterNaive)\n f.inverse(X)\n with pytest.raises(NotImplementedError):\n ReversibleBlock(fm, coupling='unknown', implementation_bwd=-2, implementation_fwd=0,\n adapter=AffineAdapterNaive)\n\n\[email protected]('coupling,adapter', [('additive', None),\n ('affine', AffineAdapterNaive),\n ('affine', AffineAdapterSigmoid)])\ndef test_reversible_block_fwd_bwd(coupling, adapter):\n \"\"\"ReversibleBlock test of the memory saving forward and backward passes\n\n * test inversion Y = RB(X) and X = RB.inverse(Y)\n * test training the block for a single step and compare weights for implementations: 0, 1\n * test automatic discard of input X and its retrieval after the backward pass\n * test usage of BN to identify non-contiguous memory blocks\n\n \"\"\"\n dims = (2, 10, 8, 8)\n data = np.random.random(dims).astype(np.float32)\n target_data = np.random.random(dims).astype(np.float32)\n\n class SubModule(torch.nn.Module):\n def __init__(self, in_filters, out_filters):\n super(SubModule, self).__init__()\n self.bn = torch.nn.BatchNorm2d(out_filters)\n self.conv = torch.nn.Conv2d(in_filters, out_filters, (3, 3), padding=1)\n\n def forward(self, x):\n return self.bn(self.conv(x))\n\n Gm = SubModule(in_filters=5, out_filters=5 if coupling == 'additive' or adapter is AffineAdapterNaive else 10)\n\n s_grad = [p.data.numpy().copy() for p in Gm.parameters()]\n for seed in range(10):\n set_seeds(seed)\n for bwd in [False, True]:\n impl_out, impl_grad = [], []\n for keep_input_sub in [False, True]:\n for keep_input_inverse_sub in [False, True]:\n for implementation_fwd in [-1, 0, 1]:\n for implementation_bwd in [-1, 0, 1]:\n keep_input = keep_input_sub or implementation_fwd == -1\n keep_input_inverse = keep_input_inverse_sub or implementation_bwd == -1\n # print(bwd, coupling, keep_input, implementation_fwd, implementation_bwd)\n # test with zero padded convolution\n X = torch.from_numpy(data.copy())\n Ytarget = torch.from_numpy(target_data.copy())\n Xshape = X.shape\n Gm2 = copy.deepcopy(Gm)\n rb = ReversibleBlock(Gm2, coupling=coupling, implementation_fwd=implementation_fwd,\n implementation_bwd=implementation_bwd, adapter=adapter,\n keep_input=keep_input, keep_input_inverse=keep_input_inverse)\n rb.train()\n rb.zero_grad()\n\n optim = torch.optim.RMSprop(rb.parameters())\n optim.zero_grad()\n if not bwd:\n Xin = X.clone()\n Y = rb(Xin)\n Yrev = Y.clone()\n Xinv = rb.inverse(Yrev)\n else:\n Xin = X.clone()\n Y = rb.inverse(Xin)\n Yrev = Y.clone()\n Xinv = rb(Yrev)\n loss = torch.nn.MSELoss()(Y, Ytarget)\n\n # has input been retained/discarded after forward (and backward) passes?\n\n def test_memory_cleared(var, isclear, shape):\n if isclear:\n assert var.storage().size() == 0\n else:\n assert var.storage().size() > 0\n assert var.shape == shape\n\n if not bwd:\n test_memory_cleared(Xin, not keep_input, Xshape)\n test_memory_cleared(Yrev, not keep_input_inverse, Xshape)\n else:\n test_memory_cleared(Yrev, not keep_input, Xshape)\n test_memory_cleared(Xin, not keep_input_inverse, Xshape)\n\n optim.zero_grad()\n loss.backward()\n optim.step()\n\n assert Y.shape == Xshape\n assert X.data.numpy().shape == data.shape\n assert np.allclose(X.data.numpy(), data, atol=1e-06)\n assert np.allclose(X.data.numpy(), Xinv.data.numpy(), atol=1e-05)\n impl_out.append(Y.data.numpy().copy())\n impl_grad.append([p.data.numpy().copy() for p in Gm2.parameters()])\n assert not np.allclose(impl_grad[-1][0], s_grad[0])\n\n # output and gradients similar over all implementations?\n for i in range(0, len(impl_grad) - 1, 1):\n assert np.allclose(impl_grad[i][0], impl_grad[i + 1][0])\n assert np.allclose(impl_out[i], impl_out[i + 1])\n\n\[email protected]('coupling,adapter', [('additive', None),\n ('affine', AffineAdapterNaive),\n ('affine', AffineAdapterSigmoid)])\ndef test_revblock_chained(coupling, adapter):\n set_seeds(42)\n dims = (2, 10, 8, 8)\n data = np.random.random(dims).astype(np.float32)\n target_data = np.random.random(dims).astype(np.float32)\n\n X = torch.from_numpy(data.copy())\n Ytarget = torch.from_numpy(target_data.copy())\n\n class SubModule(torch.nn.Module):\n def __init__(self, in_filters, out_filters):\n super(SubModule, self).__init__()\n self.bn = torch.nn.BatchNorm2d(out_filters)\n self.conv = torch.nn.Conv2d(in_filters, out_filters, (3, 3), padding=1)\n\n def forward(self, x):\n return self.bn(self.conv(x))\n\n class SubModuleStack(torch.nn.Module):\n def __init__(self, Gm, coupling='additive', depth=10, implementation_fwd=1, implementation_bwd=1,\n keep_input=False, adapter=None):\n super(SubModuleStack, self).__init__()\n self.stack = torch.nn.Sequential(\n *[ReversibleBlock(Gm, Gm, coupling=coupling, implementation_fwd=implementation_fwd,\n implementation_bwd=implementation_bwd, adapter=adapter,\n keep_input=keep_input) for _ in range(depth)]\n )\n\n def forward(self, x):\n return self.stack(x)\n\n\n Gm = SubModule(in_filters=5, out_filters=5 if coupling == 'additive' or adapter is AffineAdapterNaive else 10)\n rb = SubModuleStack(Gm, coupling=coupling, depth=2, keep_input=False, adapter=adapter)\n rb.train()\n rb.zero_grad()\n\n optim = torch.optim.RMSprop(rb.parameters())\n optim.zero_grad()\n\n Xin = X.clone()\n Y = rb(Xin)\n\n loss = torch.nn.MSELoss()(Y, Ytarget)\n\n optim.zero_grad()\n loss.backward()\n optim.step()\n\n\[email protected]('coupling', ['additive', 'affine'])\ndef test_revblock_simple_inverse(coupling):\n \"\"\"ReversibleBlock inverse test\n\n * test inversion Y = RB(X) and X = RB.inverse(Y)\n\n \"\"\"\n for seed in range(10):\n set_seeds(seed)\n for implementation_fwd in [-1, 0, 1]:\n for implementation_bwd in [-1, 0, 1]:\n # define some data\n X = torch.rand(2, 4, 5, 5)\n\n # define an arbitrary reversible function\n fn = ReversibleBlock(torch.nn.Conv2d(2, 2, 3, padding=1), keep_input=False, coupling=coupling,\n implementation_fwd=implementation_fwd, implementation_bwd=implementation_bwd,\n adapter=AffineAdapterNaive)\n\n # compute output\n Y = fn.forward(X.clone())\n\n # compute input from output\n X2 = fn.inverse(Y)\n\n # check that the inverted output and the original input are approximately similar\n assert np.allclose(X2.data.numpy(), X.data.numpy(), atol=1e-06)\n\n\[email protected]('coupling', ['additive', 'affine'])\[email protected]('implementation_fwd', [-1, 0, 1])\[email protected]('implementation_bwd', [-1, 0, 1])\ndef test_normal_vs_revblock(coupling, implementation_fwd, implementation_bwd):\n \"\"\"ReversibleBlock test if similar gradients and weights results are obtained after similar training\n\n * test training the block for a single step and compare weights and grads for implementations: 0, 1\n * test against normal non Reversible Block function\n * test if recreated input and produced output are contiguous\n\n \"\"\"\n for seed in range(10):\n set_seeds(seed)\n\n X = torch.rand(2, 4, 5, 5)\n\n # define models and their copies\n c1 = torch.nn.Conv2d(2, 2, 3, padding=1)\n c2 = torch.nn.Conv2d(2, 2, 3, padding=1)\n c1_2 = copy.deepcopy(c1)\n c2_2 = copy.deepcopy(c2)\n\n # are weights between models the same, but do they differ between convolutions?\n assert torch.equal(c1.weight, c1_2.weight)\n assert torch.equal(c2.weight, c2_2.weight)\n assert torch.equal(c1.bias, c1_2.bias)\n assert torch.equal(c2.bias, c2_2.bias)\n assert not torch.equal(c1.weight, c2.weight)\n\n # define optimizers\n optim1 = torch.optim.SGD([e for e in c1.parameters()] + [e for e in c2.parameters()], 0.1)\n optim2 = torch.optim.SGD([e for e in c1_2.parameters()] + [e for e in c2_2.parameters()], 0.1)\n for e in [c1, c2, c1_2, c2_2]:\n e.train()\n\n # define an arbitrary reversible function and define graph for model 1\n Xin = X.clone()\n fn = ReversibleBlock(c1_2, c2_2, keep_input=False, coupling=coupling, adapter=AffineAdapterNaive,\n implementation_fwd=implementation_fwd, implementation_bwd=implementation_bwd)\n Y = fn.forward(Xin)\n loss2 = torch.mean(Y)\n\n # define the reversible function without custom backprop and define graph for model 2\n XX = X.clone().data\n XX.requires_grad = True\n x1, x2 = torch.chunk(XX, 2, dim=1)\n if coupling == 'additive':\n y1 = x1 + c1.forward(x2)\n y2 = x2 + c2.forward(y1)\n elif coupling == 'affine':\n fmr2 = c1.forward(x2)\n fmr1 = torch.exp(fmr2)\n y1 = (x1 * fmr1) + fmr2\n gmr2 = c2.forward(y1)\n gmr1 = torch.exp(gmr2)\n y2 = (x2 * gmr1) + gmr2\n else:\n raise NotImplementedError()\n YY = torch.cat([y1, y2], dim=1)\n\n loss = torch.mean(YY)\n\n # compute gradients manually\n grads = torch.autograd.grad(loss, (XX, c1.weight, c2.weight, c1.bias, c2.bias), None, retain_graph=True)\n\n # compute gradients and perform optimization model 2\n loss.backward()\n optim1.step()\n\n # gradients computed manually match those of the .backward() pass\n assert torch.equal(c1.weight.grad, grads[1])\n assert torch.equal(c2.weight.grad, grads[2])\n assert torch.equal(c1.bias.grad, grads[3])\n assert torch.equal(c2.bias.grad, grads[4])\n\n # weights differ after training a single model?\n assert not torch.equal(c1.weight, c1_2.weight)\n assert not torch.equal(c2.weight, c2_2.weight)\n assert not torch.equal(c1.bias, c1_2.bias)\n assert not torch.equal(c2.bias, c2_2.bias)\n\n # compute gradients and perform optimization model 1\n loss2.backward()\n optim2.step()\n\n # input is contiguous tests\n assert Xin.is_contiguous()\n assert Y.is_contiguous()\n\n # weights are approximately the same after training both models?\n assert np.allclose(c1.weight.data.numpy(), c1_2.weight.data.numpy(), atol=1e-06)\n assert np.allclose(c2.weight.data.numpy(), c2_2.weight.data.numpy())\n assert np.allclose(c1.bias.data.numpy(), c1_2.bias.data.numpy())\n assert np.allclose(c2.bias.data.numpy(), c2_2.bias.data.numpy())\n\n # gradients are approximately the same after training both models?\n assert np.allclose(c1.weight.grad.data.numpy(), c1_2.weight.grad.data.numpy(), atol=1e-06)\n assert np.allclose(c2.weight.grad.data.numpy(), c2_2.weight.grad.data.numpy())\n assert np.allclose(c1.bias.grad.data.numpy(), c1_2.bias.grad.data.numpy())\n assert np.allclose(c2.bias.grad.data.numpy(), c2_2.bias.grad.data.numpy())\n"
] | [
[
"torch.nn.BatchNorm2d",
"numpy.allclose",
"torch.autograd.grad",
"torch.nn.MSELoss",
"torch.chunk",
"torch.manual_seed",
"torch.rand",
"numpy.random.seed",
"torch.equal",
"torch.exp",
"numpy.random.random",
"torch.nn.Conv2d",
"torch.zeros",
"torch.cat",
"torch.mean"
]
] |
ncullen93/ANTsPy | [
"a4c990dcd5b7445a45ce7b366ee018c7350e7d9f"
] | [
"ants/core/ants_image.py"
] | [
"\n\n__all__ = ['copy_image_info',\n 'set_origin',\n 'get_origin',\n 'set_direction',\n 'get_direction',\n 'set_spacing',\n 'get_spacing',\n 'image_physical_space_consistency',\n 'image_type_cast']\n\nimport os\nimport numpy as np\nfrom functools import partial, partialmethod\nimport inspect\n\nfrom .. import lib\nfrom .. import utils, registration, segmentation, viz\nfrom . import image_io as io\n\n_npy_type_set = {'uint8', 'uint32', 'float32', 'float64'}\n_itk_type_set = {'unsigned char', 'unsigned int', 'float', 'double'}\n\n_itk_to_npy_map = {\n 'unsigned char': 'uint8',\n 'unsigned int': 'uint32',\n 'float': 'float32',\n 'double': 'float64'}\n\n_npy_to_itk_map = {\n 'uint8': 'unsigned char',\n 'uint32':'unsigned int',\n 'float32': 'float',\n 'float64': 'double'}\n\n\nclass ANTsImage(object):\n\n def __init__(self, img):\n self._img = img\n self.pixeltype = img.pixeltype\n self.dtype = img.dtype\n self.dimension = img.dimension\n self.components = img.components\n self.pointer = img.pointer\n\n @property\n def spacing(self):\n return self._img.get_spacing()\n\n def set_spacing(self, new_spacing):\n self._img.set_spacing(new_spacing)\n\n @property\n def shape(self):\n return self._img.get_shape()\n\n @property\n def physical_shape(self):\n pshape = tuple([round(sh*sp,3) for sh,sp in zip(self.shape, self.spacing)])\n return pshape\n\n @property\n def origin(self):\n return self._img.get_origin()\n\n def set_origin(self, new_origin):\n self._img.set_origin(new_origin)\n\n @property\n def direction(self):\n return self._img.get_direction()\n\n def set_direction(self, new_direction):\n self._img.set_direction(new_direction)\n\n @property\n def has_components(self):\n return self.components > 1\n\n def view(self):\n dtype = self.dtype\n shape = self.shape\n if self.components > 1:\n shape = list(shape) + [self.components]\n memview = self._img.numpy()\n return np.asarray(memview).view(dtype = dtype).reshape(shape).view(np.ndarray)\n\n def numpy(self):\n return np.array(self.view(), copy=True)\n\n def clone(self, dtype=None):\n data = self.numpy()\n if dtype is not None:\n if dtype in _npy_type_set:\n data = data.astype(dtype)\n elif dtype in _itk_type_set:\n dtype = _itk_to_npy_map[dtype]\n data = data.astype(dtype)\n else:\n raise ValueError('dtype arg %s not understood' % str(dtype))\n\n return io.from_numpy(data=data, origin=self.origin, \n spacing=self.spacing, direction=self.direction,\n has_components=self.has_components)\n\n def new_image_like(self, data):\n return io.from_numpy(data, origin=self.origin, \n spacing=self.spacing, direction=self.direction, \n has_components=self.has_components)\n\n def to_file(self, filename):\n return self._img.toFile(filename)\n\n def mean(self, axis=None):\n return self.numpy().mean(axis=axis)\n\n def std(self, axis=None):\n return self.numpy().std(axis=axis)\n\n def sum(self, axis=None, keepdims=False):\n return self.numpy().sum(axis=axis, keepdims=keepdims)\n\n def min(self, axis=None):\n return self.numpy().min(axis=axis)\n\n def max(self, axis=None):\n return self.numpy().max(axis=axis)\n\n def __add__(self, other):\n this_array = self.numpy()\n \n if isinstance(other, ANTsImage):\n if not image_physical_space_consistency(self, other):\n raise ValueError('images do not occupy same physical space')\n other = other.numpy()\n\n new_array = this_array + other\n return self.new_image_like(new_array) \n\n def __sub__(self, other):\n this_array = self.numpy()\n \n if isinstance(other, ANTsImage):\n if not image_physical_space_consistency(self, other):\n raise ValueError('images do not occupy same physical space')\n other = other.numpy()\n\n new_array = this_array - other\n return self.new_image_like(new_array)\n\n def __mul__(self, other):\n this_array = self.numpy()\n \n if isinstance(other, ANTsImage):\n if not image_physical_space_consistency(self, other):\n raise ValueError('images do not occupy same physical space')\n other = other.numpy()\n\n new_array = this_array * other\n return self.new_image_like(new_array) \n\n def __truediv__(self, other):\n this_array = self.numpy()\n \n if isinstance(other, ANTsImage):\n if not image_physical_space_consistency(self, other):\n raise ValueError('images do not occupy same physical space')\n other = other.numpy()\n\n new_array = this_array / other\n return self.new_image_like(new_array)\n\n def __pow__(self, other):\n this_array = self.numpy()\n\n if isinstance(other, ANTsImage):\n if not image_physical_space_consistency(self, other):\n raise ValueError('images do not occupy same physical space')\n other = other.numpy()\n\n new_array = this_array ** other\n return self.new_image_like(new_array)\n\n def __gt__(self, other):\n this_array = self.numpy()\n\n if isinstance(other, ANTsImage):\n if not image_physical_space_consistency(self, other):\n raise ValueError('images do not occupy same physical space')\n other = other.numpy()\n\n new_array = this_array > other\n return self.new_image_like(new_array.astype('uint8'))\n\n def __ge__(self, other):\n this_array = self.numpy()\n\n if isinstance(other, ANTsImage):\n if not image_physical_space_consistency(self, other):\n raise ValueError('images do not occupy same physical space')\n other = other.numpy()\n\n new_array = this_array >= other\n return self.new_image_like(new_array.astype('uint8'))\n\n def __lt__(self, other):\n this_array = self.numpy()\n\n if isinstance(other, ANTsImage):\n if not image_physical_space_consistency(self, other):\n raise ValueError('images do not occupy same physical space')\n other = other.numpy()\n\n new_array = this_array < other\n return self.new_image_like(new_array.astype('uint8'))\n\n def __le__(self, other):\n this_array = self.numpy()\n\n if isinstance(other, ANTsImage):\n if not image_physical_space_consistency(self, other):\n raise ValueError('images do not occupy same physical space')\n other = other.numpy()\n\n new_array = this_array <= other\n return self.new_image_like(new_array.astype('uint8'))\n\n def __eq__(self, other):\n this_array = self.numpy()\n\n if isinstance(other, ANTsImage):\n if not image_physical_space_consistency(self, other):\n raise ValueError('images do not occupy same physical space')\n other = other.numpy()\n\n new_array = this_array == other\n return self.new_image_like(new_array.astype('uint8'))\n\n def __getitem__(self, idx):\n arr = self.numpy()\n if isinstance(idx, ANTsImage):\n if not image_physical_space_consistency(self, idx):\n raise ValueError('images do not occupy same physical space')\n return arr.__getitem__(idx.numpy().astype('bool'))\n else:\n return arr.__getitem__(idx)\n\n\n def __setitem__(self, idx, value):\n arr = self.view()\n if isinstance(idx, ANTsImage):\n if not image_physical_space_consistency(self, idx):\n raise ValueError('images do not occupy same physical space')\n arr.__setitem__(idx.numpy().astype('bool'), value)\n else:\n arr.__setitem__(idx, value)\n\n def __repr__(self):\n s = \"ANTsImage\\n\" +\\\n '\\t {:<10} : {}\\n'.format('Pixel Type', self.pixeltype)+\\\n '\\t {:<10} : {}\\n'.format('Components', self.components)+\\\n '\\t {:<10} : {}\\n'.format('Dimensions', self.shape)+\\\n '\\t {:<10} : {}\\n'.format('Spacing', self.spacing)+\\\n '\\t {:<10} : {}\\n'.format('Origin', self.origin)+\\\n '\\t {:<10} : {}\\n'.format('Direction', self.direction.flatten())\n return s\n\n_utils_partial_dict = {k:v for k,v in utils.__dict__.items() if callable(v) and (inspect.getargspec(getattr(utils,k)).args[0] in {'img','image'})}\n_reg_partial_dict = {k:v for k,v in registration.__dict__.items() if callable(v) and (inspect.getargspec(getattr(registration,k)).args[0] in {'img','image'})}\n_seg_partial_dict = {k:v for k,v in segmentation.__dict__.items() if callable(v) and (inspect.getargspec(getattr(segmentation,k)).args[0] in {'img','image'})}\n_viz_partial_dict = {k:v for k,v in viz.__dict__.items() if callable(v) and (inspect.getargspec(getattr(viz,k)).args[0] in {'img','image'})}\n\nfor k, v in _utils_partial_dict.items():\n setattr(ANTsImage, k, partialmethod(v))\nfor k, v in _reg_partial_dict.items():\n setattr(ANTsImage, k, partialmethod(v))\nfor k, v in _seg_partial_dict.items():\n setattr(ANTsImage, k, partialmethod(v))\nfor k, v in _viz_partial_dict.items():\n setattr(ANTsImage, k, partialmethod(v))\n\n\n\ndef copy_image_info(reference, target):\n \"\"\"\n Copy image information from img1 to img2\n \"\"\"\n target.set_origin(reference.origin)\n target.set_direction(reference.direction)\n target.set_spacing(target.spacing)\n return target\n\ndef set_origin(img, origin):\n img.set_origin(origin)\n\ndef get_origin(img):\n return img.origin\n\ndef set_direction(img, direction):\n img.set_direction(direction)\n\ndef get_direction(img):\n return img.direction\n\ndef set_spacing(img, spacing):\n img.set_spacing(spacing)\n\ndef get_spacing(img):\n return img.spacing\n\n\ndef image_physical_space_consistency(*imgs, tolerance=1e-2, data_type=False):\n if len(imgs) < 2:\n raise ValueError('need at least two images to compare')\n\n img1 = imgs[0]\n for img2 in imgs[1:]:\n if (not isinstance(img1, ANTsImage)) or (not isinstance(img2, ANTsImage)):\n raise ValueError('Both images must be of class `AntsImage`')\n\n # image dimension check\n if img1.dimension != img2.dimension:\n return False\n\n # image spacing check\n space_diffs = sum([abs(s1-s2)>tolerance for s1, s2 in zip(img1.spacing, img2.spacing)])\n if space_diffs > 0:\n return False\n\n # image origin check\n origin_diffs = sum([abs(s1-s2)>tolerance for s1, s2 in zip(img1.origin, img2.origin)])\n if origin_diffs > 0:\n return False\n\n # image direction check\n origin_diff = np.allclose(img1.direction, img2.direction, atol=tolerance)\n if not origin_diff:\n return False\n\n # data type\n if data_type == True:\n if img1.dtype != img2.dtype:\n return False\n\n if img1.n_components != img2.n_components:\n return False\n\n return True\n\n\ndef image_type_cast(image_list, pixeltype=None):\n \"\"\"\n Cast a list of images to the highest pixeltype present in the list\n or all to a specified type\n \"\"\"\n pixtypes = []\n for img in image_list:\n pixtypes.append(img.pixeltype)\n\n if pixeltype is None:\n pixeltype = 'unsigned char'\n for p in pixtypes:\n if p == 'double':\n pixeltype = 'double'\n elif (p=='float') and (pixeltype!='double'):\n pixeltype = 'float'\n elif (p=='unsigned int') and (pixeltype!='float') and (pixeltype!='double'):\n pixeltype = 'unsigned int'\n\n out_images = []\n for img in image_list:\n if img.pixeltype == pixeltype:\n out_images.append(img)\n else:\n out_images.append(img.clone(pixeltype))\n\n return out_images\n\n\n\n\n\n\n"
] | [
[
"numpy.allclose",
"numpy.asarray"
]
] |
tkg-framework/TKG-framework | [
"98586b7199bda0e96d74b2ea02c62226901822cc"
] | [
"tkge/models/loss/MarginRankingLoss.py"
] | [
"from tkge.models.loss import Loss\n\nimport torch\n\n\[email protected](name=\"margin_ranking_loss\")\nclass MarginRankingLoss(Loss):\n def __init__(self, config):\n super().__init__(config)\n\n self.margin = self.config.get(\"train.loss.margin\")\n self.reduction = self.config.get(\"train.loss.reduction\")\n\n self._device = self.config.get(\"task.device\")\n self._train_type = self.config.get(\"train.type\")\n self._loss = torch.nn.MarginRankingLoss(margin=self.margin, reduction=self.reduction)\n\n self.num_samples = self.config.get(\"negative_sampling.num_samples\")\n\n def __call__(self, scores: torch.Tensor, labels: torch.Tensor):\n assert labels.dim() == 2, 'Margin ranking loss only supports matrix-like scores and scores. Set train.negative_sampling.as_matrix to True in configuration file.'\n\n bs = scores.size(0)\n ns = scores.size(1) - 1\n\n # walkaround: assume the 1st column are positive samples and others are negative\n\n positive_scores = scores[:, 0].reshape(-1, 1)\n negative_scores = scores[:, 1:]\n\n positive_scores = positive_scores.repeat((ns, 1)).squeeze()\n negative_scores = negative_scores.reshape(-1)\n y = torch.ones_like(positive_scores)\n\n return self._loss(positive_scores, negative_scores, y)\n\n # def __call__(self, scores, labels, **kwargs):\n # # scores is (batch_size x num_negatives + 1)\n # labels = self._labels_as_matrix(scores, labels)\n #\n # if \"negative_sampling\" in self._train_type:\n # # Pair each 1 with the following zeros until next 1\n # labels = labels.to(self._device).view(-1)\n # pos_positives = labels.nonzero().view(-1)\n # pos_negatives = (labels == 0).nonzero().view(-1)\n #\n # n_over_p = pos_negatives.size(0) // pos_positives.size(0)\n # # repeat each positive score num_negatives times\n # pos_positives = (\n # pos_positives.view(-1, 1).repeat(1, n_over_p).view(-1)\n # )\n # positives = scores.view(-1)[pos_positives].to(self._device).view(-1)\n # negatives = scores.view(-1)[pos_negatives].to(self._device).view(-1)\n # target = torch.ones(positives.size()).to(self._device)\n # return self._loss(positives, negatives, target)\n #\n # elif self._train_type == \"KvsAll\":\n # # TODO determine how to form pairs for margin ranking in KvsAll training\n # # scores and labels are tensors of size (batch_size, num_entities)\n # # Each row has 1s and 0s of a single sp or po tuple from training\n # # How to combine them for pairs?\n # # Each 1 with all 0s? Can memory handle this?\n # raise NotImplementedError(\n # \"Margin ranking with KvsAll training not yet supported.\"\n # )\n # else:\n # raise ValueError(\"train.type for margin ranking.\")\n"
] | [
[
"torch.ones_like",
"torch.nn.MarginRankingLoss"
]
] |
gmabey/numpy | [
"9e9ec3821c1d6a055543e54336ecb2c98ec42c5f"
] | [
"numpy/distutils/fcompiler/intel.py"
] | [
"# http://developer.intel.com/software/products/compilers/flin/\nfrom __future__ import division, absolute_import, print_function\n\nimport sys\n\nfrom numpy.distutils.ccompiler import simple_version_match\nfrom numpy.distutils.fcompiler import FCompiler, dummy_fortran_file\n\ncompilers = ['IntelFCompiler', 'IntelVisualFCompiler',\n 'IntelItaniumFCompiler', 'IntelItaniumVisualFCompiler',\n 'IntelEM64VisualFCompiler', 'IntelEM64TFCompiler']\n\ndef intel_version_match(type):\n # Match against the important stuff in the version string\n return simple_version_match(start=r'Intel.*?Fortran.*?(?:%s).*?Version' % (type,))\n\nclass BaseIntelFCompiler(FCompiler):\n def update_executables(self):\n f = dummy_fortran_file()\n self.executables['version_cmd'] = ['<F77>', '-FI', '-V', '-c',\n f + '.f', '-o', f + '.o']\n\nclass IntelFCompiler(BaseIntelFCompiler):\n\n compiler_type = 'intel'\n compiler_aliases = ('ifort',)\n description = 'Intel Fortran Compiler for 32-bit apps'\n version_match = intel_version_match('32-bit|IA-32')\n\n possible_executables = ['ifort', 'ifc']\n\n executables = {\n 'version_cmd' : None, # set by update_executables\n 'compiler_f77' : [None, \"-72\", \"-w90\", \"-w95\"],\n 'compiler_f90' : [None],\n 'compiler_fix' : [None, \"-FI\"],\n 'linker_so' : [\"<F90>\", \"-shared\"],\n 'archiver' : [\"ar\", \"-cr\"],\n 'ranlib' : [\"ranlib\"]\n }\n\n pic_flags = ['-fPIC']\n module_dir_switch = '-module ' # Don't remove ending space!\n module_include_switch = '-I'\n\n def get_flags_free(self):\n return [\"-FR\"]\n\n def get_flags(self):\n return ['-fPIC']\n\n def get_flags_opt(self):\n #return ['-i8 -xhost -openmp -fp-model strict']\n return ['-xhost -openmp -fp-model strict']\n\n def get_flags_arch(self):\n return []\n\n def get_flags_linker_so(self):\n opt = FCompiler.get_flags_linker_so(self)\n v = self.get_version()\n if v and v >= '8.0':\n opt.append('-nofor_main')\n if sys.platform == 'darwin':\n # Here, it's -dynamiclib\n try:\n idx = opt.index('-shared')\n opt.remove('-shared')\n except ValueError:\n idx = 0\n opt[idx:idx] = ['-dynamiclib', '-Wl,-undefined,dynamic_lookup']\n return opt\n\nclass IntelItaniumFCompiler(IntelFCompiler):\n compiler_type = 'intele'\n compiler_aliases = ()\n description = 'Intel Fortran Compiler for Itanium apps'\n\n version_match = intel_version_match('Itanium|IA-64')\n\n possible_executables = ['ifort', 'efort', 'efc']\n\n executables = {\n 'version_cmd' : None,\n 'compiler_f77' : [None, \"-FI\", \"-w90\", \"-w95\"],\n 'compiler_fix' : [None, \"-FI\"],\n 'compiler_f90' : [None],\n 'linker_so' : ['<F90>', \"-shared\"],\n 'archiver' : [\"ar\", \"-cr\"],\n 'ranlib' : [\"ranlib\"]\n }\n\nclass IntelEM64TFCompiler(IntelFCompiler):\n compiler_type = 'intelem'\n compiler_aliases = ()\n description = 'Intel Fortran Compiler for 64-bit apps'\n\n version_match = intel_version_match('EM64T-based|Intel\\\\(R\\\\) 64|64|IA-64|64-bit')\n\n possible_executables = ['ifort', 'efort', 'efc']\n\n executables = {\n 'version_cmd' : None,\n 'compiler_f77' : [None, \"-FI\"],\n 'compiler_fix' : [None, \"-FI\"],\n 'compiler_f90' : [None],\n 'linker_so' : ['<F90>', \"-shared\"],\n 'archiver' : [\"ar\", \"-cr\"],\n 'ranlib' : [\"ranlib\"]\n }\n\n def get_flags(self):\n return ['-fPIC']\n\n def get_flags_opt(self):\n #return ['-i8 -xhost -openmp -fp-model strict']\n return ['-xhost -openmp -fp-model strict']\n\n def get_flags_arch(self):\n return []\n\n# Is there no difference in the version string between the above compilers\n# and the Visual compilers?\n\nclass IntelVisualFCompiler(BaseIntelFCompiler):\n compiler_type = 'intelv'\n description = 'Intel Visual Fortran Compiler for 32-bit apps'\n version_match = intel_version_match('32-bit|IA-32')\n\n def update_executables(self):\n f = dummy_fortran_file()\n self.executables['version_cmd'] = ['<F77>', '/FI', '/c',\n f + '.f', '/o', f + '.o']\n\n ar_exe = 'lib.exe'\n possible_executables = ['ifort', 'ifl']\n\n executables = {\n 'version_cmd' : None,\n 'compiler_f77' : [None, \"-FI\", \"-w90\", \"-w95\"],\n 'compiler_fix' : [None, \"-FI\", \"-4L72\", \"-w\"],\n 'compiler_f90' : [None],\n 'linker_so' : ['<F90>', \"-shared\"],\n 'archiver' : [ar_exe, \"/verbose\", \"/OUT:\"],\n 'ranlib' : None\n }\n\n compile_switch = '/c '\n object_switch = '/Fo' #No space after /Fo!\n library_switch = '/OUT:' #No space after /OUT:!\n module_dir_switch = '/module:' #No space after /module:\n module_include_switch = '/I'\n\n def get_flags(self):\n opt = ['/nologo', '/MD', '/nbs', '/names:lowercase', '/assume:underscore']\n return opt\n\n def get_flags_free(self):\n return [\"-FR\"]\n\n def get_flags_debug(self):\n return ['/4Yb', '/d2']\n\n def get_flags_opt(self):\n return ['/O1'] # Scipy test failures with /O2\n\n def get_flags_arch(self):\n return [\"/arch:IA-32\", \"/QaxSSE3\"]\n\nclass IntelItaniumVisualFCompiler(IntelVisualFCompiler):\n compiler_type = 'intelev'\n description = 'Intel Visual Fortran Compiler for Itanium apps'\n\n version_match = intel_version_match('Itanium')\n\n possible_executables = ['efl'] # XXX this is a wild guess\n ar_exe = IntelVisualFCompiler.ar_exe\n\n executables = {\n 'version_cmd' : None,\n 'compiler_f77' : [None, \"-FI\", \"-w90\", \"-w95\"],\n 'compiler_fix' : [None, \"-FI\", \"-4L72\", \"-w\"],\n 'compiler_f90' : [None],\n 'linker_so' : ['<F90>', \"-shared\"],\n 'archiver' : [ar_exe, \"/verbose\", \"/OUT:\"],\n 'ranlib' : None\n }\n\nclass IntelEM64VisualFCompiler(IntelVisualFCompiler):\n compiler_type = 'intelvem'\n description = 'Intel Visual Fortran Compiler for 64-bit apps'\n\n version_match = simple_version_match(start='Intel\\(R\\).*?64,')\n\n def get_flags_arch(self):\n return [\"/arch:SSE2\"]\n\n\nif __name__ == '__main__':\n from distutils import log\n log.set_verbosity(2)\n from numpy.distutils.fcompiler import new_fcompiler\n compiler = new_fcompiler(compiler='intel')\n compiler.customize()\n print(compiler.get_version())\n"
] | [
[
"numpy.distutils.ccompiler.simple_version_match",
"numpy.distutils.fcompiler.dummy_fortran_file",
"numpy.distutils.fcompiler.FCompiler.get_flags_linker_so",
"numpy.distutils.fcompiler.new_fcompiler"
]
] |
JonathanRaiman/dali-cython-stub | [
"e258469aeb1d4cb3e4cdf5c07e8948f461a038f1"
] | [
"dali/utils/misc.py"
] | [
"import dill as pickle\nimport inspect\nimport numpy as np\nimport types\n\nfrom os import makedirs, listdir\nfrom os.path import join, exists\n\nimport dali.core as D\n\nclass RunningAverage(object):\n def __init__(self, alpha=0.95):\n self.alpha = alpha\n self.value = None\n\n def update(self, measurement):\n if self.value is None:\n self.value = measurement\n else:\n self.value = (self.alpha * self.value +\n (1.0 - self.alpha) * measurement)\n\n def __float__(self):\n return float(self.value)\n\n\ndef apply_recursively_on_type(x, f, target_type, list_callback=None):\n if type(x) == target_type:\n return f(x)\n elif type(x) == list or isinstance(x, types.GeneratorType):\n ret = [ apply_recursively_on_type(el, f, target_type, list_callback) for el in x]\n if list_callback and all(type(el) == target_type for el in x):\n ret = list_callback(ret)\n return ret\n elif type(x) == dict:\n res = {}\n for k,v in x.items():\n res[k] = apply_recursively_on_type(v, f, target_type, list_callback)\n return res\n else:\n return x\n\ndef integer_ceil(a, b):\n return (a + b - 1) // b\n\ndef subsample(seq, maximum_length):\n if seq == []:\n return seq\n return seq[::integer_ceil(len(seq), maximum_length)]\n\ndef median_smoothing(signal, window=10):\n res = []\n for i in range(window, len(signal)):\n actual_window = signal[i-window:i]\n res.append(np.median(actual_window))\n return res\n\ndef pickle_from_scope(directory, variables, caller_globals=None, caller_locals=None):\n if not exists(directory):\n makedirs(directory)\n\n if caller_globals is None or caller_locals is None:\n stack = inspect.stack()\n if caller_globals is None:\n caller_globals = stack[1][0].f_globals\n if caller_locals is None:\n caller_locals = stack[1][0].f_locals\n del stack\n\n for var in variables:\n with open(join(directory, var + \".pkz\"), \"wb\") as f:\n value = caller_locals.get(var) or caller_globals.get(var)\n assert value is not None\n pickle.dump(value, f)\n\ndef unpickle_as_dict(directory, whitelist=None, extension='.pkz'):\n assert exists(directory)\n\n res = {}\n\n for file_name in listdir(directory):\n if file_name.endswith(extension):\n var_name = file_name[:-len(extension)]\n if whitelist is None or var_name in whitelist:\n with open(join(directory, file_name), \"rb\") as f:\n res[var_name] = pickle.load(f)\n\n return res\n\ndef add_device_args(parser):\n parser.add_argument(\"--device\", type=str, default='gpu', choices=['gpu','cpu'], help=\"Whether model should run on GPU or CPU.\")\n parser.add_argument(\"--gpu_id\", type=int, default=0, help=\"Which GPU to use (zero-indexed just like in CUDA APIs)\")\n\ndef set_device_from_args(args, verbose=False):\n D.config.default_device = args.device\n if args.device == 'gpu':\n D.config.default_gpu = args.gpu_id\n if verbose:\n print(\"Using %s\" % (D.config.gpu_id_to_name(args.gpu_id)))\n\n__all__ = [\n \"apply_recursively_on_type\",\n \"integer_ceil\",\n \"subsample\",\n \"median_smoothing\",\n \"pickle_from_scope\",\n \"unpickle_as_dict\",\n \"RunningAverage\",\n \"add_device_args\",\n \"set_device_from_args\"\n]\n"
] | [
[
"numpy.median"
]
] |
jjmachan/PySyft | [
"41a525443881bfd94ccb488d7a24765c1778ac05"
] | [
"test/torch_test.py"
] | [
"# python -m unittest -v test/torch_test.py\n\n\nimport unittest\nfrom unittest import TestCase\n\nimport random\nimport syft as sy\nimport numpy as np\nfrom syft.core.frameworks.torch import utils as torch_utils\nfrom syft.core.frameworks import encode\nfrom syft.core.frameworks.torch.tensor import _GeneralizedPointerTensor\nimport torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable as Var\nimport msgpack\n\nbob = None\nalice = None\njames = None\nme = None\nhook = None\n\n\ndef setUpModule():\n print(\"setup module\")\n\n global me\n global bob\n global alice\n global james\n global hook\n\n hook = sy.TorchHook(verbose=True)\n\n me = hook.local_worker\n me.is_client_worker = False\n\n bob = sy.VirtualWorker(id=\"bob\", hook=hook, is_client_worker=False)\n alice = sy.VirtualWorker(id=\"alice\", hook=hook, is_client_worker=False)\n james = sy.VirtualWorker(id=\"james\", hook=hook, is_client_worker=False)\n\n bob.add_workers([alice, james])\n alice.add_workers([bob, james])\n james.add_workers([bob, alice])\n\n class Chain:\n def __init__(self, leaf=False):\n if not leaf:\n self.tensor = Chain(True)\n self.var = Chain(True)\n\n global display_chain\n\n display_chain = Chain()\n\n display_chain.tensor.local = \"FloatTensor > _LocalTensor\"\n\n display_chain.tensor.pointer = \"FloatTensor > _PointerTensor\"\n\n display_chain.tensor.fixp_local = (\n \"FloatTensor > _FixedPrecisionTensor > LongTensor > _LocalTensor\"\n )\n\n display_chain.tensor.fixp_mpc_gpt = (\n \"FloatTensor > _FixedPrecisionTensor\"\n \"> LongTensor > _SNNTensor > LongTensor > _GeneralizedPointerTensor\"\n )\n\n display_chain.var.local = (\n \"Variable > _LocalTensor\\n\"\n \" - FloatTensor > _LocalTensor\\n\"\n \" - - Variable > _LocalTensor\\n\"\n \" - FloatTensor > _LocalTensor\"\n )\n\n display_chain.var.pointer = (\n \"Variable > _PointerTensor\\n\"\n \" - FloatTensor > _PointerTensor\\n\"\n \" - - Variable > _PointerTensor\\n\"\n \" - FloatTensor > _PointerTensor\"\n )\n\n display_chain.var.fixp_local = (\n \"Variable > _FixedPrecisionTensor > Variable > _LocalTensor\\n\"\n \" - FloatTensor > _FixedPrecisionTensor > LongTensor > _LocalTensor\\n\"\n \" - - Variable > _FixedPrecisionTensor > Variable > _LocalTensor\\n\"\n \" - FloatTensor > _FixedPrecisionTensor > LongTensor > _LocalTensor\"\n )\n\n display_chain.var.fixp_mpc_gpt = (\n \"Variable > _FixedPrecisionTensor > Variable > _SNNTensor \"\n \"> Variable > _GeneralizedPointerTensor\\n\"\n \" - FloatTensor > _FixedPrecisionTensor > LongTensor\"\n \"> _SNNTensor > LongTensor > _GeneralizedPointerTensor\\n\"\n \" - - Variable > _FixedPrecisionTensor > Variable > _SNNTensor\"\n \"> Variable > _GeneralizedPointerTensor\\n\"\n \" - FloatTensor > _FixedPrecisionTensor > LongTensor\"\n \"> _SNNTensor > LongTensor > _GeneralizedPointerTensor\"\n )\n\n\nclass TestChainTensor(TestCase):\n def test_plus_is_minus_tensor_local(self):\n x = torch.FloatTensor([5, 6])\n y = torch.FloatTensor([3, 4])\n x = sy._PlusIsMinusTensor().on(x)\n y = sy._PlusIsMinusTensor().on(y)\n\n assert (\n torch_utils.chain_print(x, display=False)\n == \"FloatTensor > _PlusIsMinusTensor > _LocalTensor\"\n )\n\n z = x.add(y)\n\n assert (\n torch_utils.chain_print(z, display=False)\n == \"FloatTensor > _PlusIsMinusTensor > _LocalTensor\"\n )\n\n # cut chain for the equality check\n z.child = z.child.child\n assert torch.equal(z, torch.FloatTensor([2, 2]))\n\n z = torch.add(x, y)\n\n # cut chain for the equality check\n z.child = z.child.child\n assert torch.equal(z, torch.FloatTensor([2, 2]))\n\n def test_plus_is_minus_tensor_remote(self):\n x = torch.FloatTensor([5, 6])\n y = torch.FloatTensor([3, 4])\n x = sy._PlusIsMinusTensor().on(x)\n y = sy._PlusIsMinusTensor().on(y)\n\n id1 = random.randint(0, 10e10)\n id2 = random.randint(0, 10e10)\n x.send(bob, ptr_id=id1)\n y.send(bob, ptr_id=id2)\n\n z = x.add(y)\n assert (\n torch_utils.chain_print(z, display=False) == \"FloatTensor > _PointerTensor\"\n )\n\n # Check chain on remote\n ptr_id = z.child.id_at_location\n assert (\n torch_utils.chain_print(bob._objects[ptr_id].parent, display=False)\n == \"FloatTensor > _PlusIsMinusTensor > _LocalTensor\"\n )\n\n z.get()\n assert (\n torch_utils.chain_print(z, display=False)\n == \"FloatTensor > _PlusIsMinusTensor > _LocalTensor\"\n )\n\n # cut chain for the equality check\n z.child = z.child.child\n assert torch.equal(z, torch.FloatTensor([2, 2]))\n\n def test_plus_is_minus_variable_local(self):\n x = sy.Variable(torch.FloatTensor([5, 6]))\n y = sy.Variable(torch.FloatTensor([3, 4]))\n x = sy._PlusIsMinusTensor().on(x)\n y = sy._PlusIsMinusTensor().on(y)\n\n display = (\n \"Variable > _PlusIsMinusTensor > _LocalTensor\\n\"\n \" - FloatTensor > _PlusIsMinusTensor > _LocalTensor\\n\"\n \" - - Variable > _PlusIsMinusTensor > _LocalTensor\\n\"\n \" - FloatTensor > _PlusIsMinusTensor > _LocalTensor\"\n )\n\n assert torch_utils.chain_print(x, display=False) == display\n\n z = x.add(y)\n\n assert (\n torch_utils.chain_print(z, display=False)\n == \"Variable > _PlusIsMinusTensor > \"\n \"_LocalTensor\\n - FloatTensor >\"\n \" _PlusIsMinusTensor > _LocalTensor\"\n )\n\n # cut chain for the equality check\n z.data.child = z.data.child.child\n assert torch.equal(z.data, torch.FloatTensor([2, 2]))\n\n z = torch.add(x, y)\n\n # cut chain for the equality check\n z.data.child = z.data.child.child\n assert torch.equal(z.data, torch.FloatTensor([2, 2]))\n\n def test_plus_is_minus_variable_remote(self):\n x = sy.Variable(torch.FloatTensor([5, 6]))\n y = sy.Variable(torch.FloatTensor([3, 4]))\n x = sy._PlusIsMinusTensor().on(x)\n y = sy._PlusIsMinusTensor().on(y)\n\n id1 = random.randint(0, 10e10)\n id2 = random.randint(0, 10e10)\n id11 = random.randint(0, 10e10)\n id21 = random.randint(0, 10e10)\n x.send(bob, new_id=id1, new_data_id=id11)\n y.send(bob, new_id=id2, new_data_id=id21)\n\n z = x.add(y)\n assert (\n torch_utils.chain_print(z, display=False) == \"Variable > _PointerTensor\\n\"\n \" - FloatTensor > _PointerTensor\\n\"\n \" - - Variable > _PointerTensor\\n\"\n \" - FloatTensor > _PointerTensor\"\n )\n\n assert bob._objects[z.id_at_location].owner.id == \"bob\"\n assert bob._objects[z.data.id_at_location].owner.id == \"bob\"\n\n # Check chain on remote\n ptr_id = x.child.id_at_location\n display = (\n \"Variable > _PlusIsMinusTensor > _LocalTensor\\n\"\n \" - FloatTensor > _PlusIsMinusTensor > _LocalTensor\\n\"\n \" - - Variable > _PlusIsMinusTensor > _LocalTensor\\n\"\n \" - FloatTensor > _PlusIsMinusTensor > _LocalTensor\"\n )\n assert (\n torch_utils.chain_print(bob._objects[ptr_id].parent, display=False)\n == display\n )\n\n # Check chain on remote\n # TODO For now we don't reconstruct the grad chain one non-leaf variable (in our case a leaf\n # variable is a variable that we sent), because we don't care about their gradient.\n # But if we do,then this is a TODO!\n ptr_id = z.child.id_at_location\n display = (\n \"Variable > _PlusIsMinusTensor > _LocalTensor\\n\"\n \" - FloatTensor > _PlusIsMinusTensor > _LocalTensor\\n\"\n \" - - Variable > _LocalTensor\\n\"\n \" - FloatTensor > _LocalTensor\"\n )\n assert (\n torch_utils.chain_print(bob._objects[ptr_id].parent, display=False)\n == display\n )\n\n z.get()\n display = (\n \"Variable > _PlusIsMinusTensor > _LocalTensor\\n\"\n \" - FloatTensor > _PlusIsMinusTensor > _LocalTensor\\n\"\n \" - - Variable > _LocalTensor\\n\"\n \" - FloatTensor > _LocalTensor\"\n )\n assert torch_utils.chain_print(z, display=False) == display\n\n # cut chain for the equality check\n z.data.child = z.data.child.child\n assert torch.equal(z.data, torch.FloatTensor([2, 2]))\n\n def test_plus_is_minus_backward_local(self):\n x = sy.Variable(torch.FloatTensor([5, 6]), requires_grad=True)\n y = sy.Variable(torch.FloatTensor([3, 4]), requires_grad=True)\n x = sy._PlusIsMinusTensor().on(x)\n y = sy._PlusIsMinusTensor().on(y)\n z = x.add(y).sum()\n z.backward()\n\n # cut chain for the equality check\n x.grad.data.child = x.grad.data.child.child\n assert torch.equal(x.grad.data, torch.FloatTensor([1, 1]))\n\n def test_plus_is_minus_backward_remote(self):\n x = sy.Variable(torch.FloatTensor([5, 6]), requires_grad=True)\n y = sy.Variable(torch.FloatTensor([3, 4]), requires_grad=True)\n x = sy._PlusIsMinusTensor().on(x)\n y = sy._PlusIsMinusTensor().on(y)\n x.send(bob)\n y.send(bob)\n\n z = x.add(y).sum()\n z.backward()\n\n # cut chain for the equality check\n x.get()\n x.child = x.child.child\n\n # TODO: figure out why some machines prefer one of these options\n # while others prefer the other\n try:\n target = sy._PlusIsMinusTensor().on(torch.FloatTensor([1, 1]))\n target.child = target.child.child\n assert torch.equal(x.grad.data, target)\n except AttributeError:\n target = sy._PlusIsMinusTensor().on(torch.FloatTensor([1, 1]))\n target.child = target.child\n assert torch.equal(x.grad.data, target)\n\n\nclass TestTorchTensor(TestCase):\n def test_set_id(self):\n\n hook.local_worker.is_client_worker = False\n\n x = torch.FloatTensor([-2, -1, 0, 1, 2, 3]).set_id(\"bobs tensor\")\n assert x.id == \"bobs tensor\"\n assert x.child.id == \"bobs tensor\"\n\n assert x.id in hook.local_worker._objects\n assert list(x.child.old_ids)[0] in hook.local_worker._objects\n assert list(x.child.old_ids)[0] != x.id\n\n x = sy.Var(sy.FloatTensor([-2, -1, 0, 1, 2, 3])).set_id(\"bobs variable\")\n assert x.id == \"bobs variable\"\n assert x.child.id == \"bobs variable\"\n\n assert x.id in hook.local_worker._objects\n assert list(x.child.old_ids)[0] in hook.local_worker._objects\n assert list(x.child.old_ids)[0] != x.id\n\n def test___repr__(self):\n x = torch.FloatTensor([1, 2, 3, 4, 5])\n # assert x.__repr__() == '\\n 1\\n 2\\n 3\\n 4\\n 5\\n[torch.FloatTensor of size 5]\\n'\n assert (\n x.__repr__() == \"\\n 1\\n 2\\n 3\\n 4\\n 5\\n[\"\n \"syft.core.frameworks.torch.tensor.FloatTensor of size 5]\\n\"\n )\n\n def test_send_get_tensor(self):\n\n x = torch.FloatTensor([1, 2, 3, 4, 5])\n x_id = x.id\n ptr_id = random.randint(0, 10e10)\n x.send(bob, ptr_id=ptr_id)\n assert x_id in me._objects\n\n ptr = me._objects[x_id]\n assert x.child == ptr\n assert isinstance(ptr, sy._PointerTensor)\n assert ptr.id_at_location == ptr_id\n assert ptr.location.id == bob.id\n\n assert ptr_id in bob._objects\n remote_x = bob._objects[ptr_id]\n assert isinstance(remote_x, sy._LocalTensor)\n assert torch.equal(remote_x.child, torch.FloatTensor([1, 2, 3, 4, 5]))\n\n x.get()\n # Check that it's still registered\n assert x.id in me._objects\n assert torch.equal(me._objects[x.id].child, x)\n\n assert (x == torch.FloatTensor([1, 2, 3, 4, 5])).all()\n\n # because .get_() was called, x should no longer be in the remote worker's objects dict\n assert ptr_id not in bob._objects\n\n def test_multiple_pointers_to_same_target(self):\n # There are two cases:\n # - You're sending a var on a loc:id you're already pointing at -> should abort\n # - You're pointing at the result of an in-place remote operation like:\n # x = sy.Variable(torch.FloatTensor([1, 2, -3, 4, 5])).send(bob)\n # y = x.abs_() # in-place operation\n # y.get()\n # x.send(bob) # if x.child != y.child, x will send its old pointer\n # to bob->trigger an error\n # You want this to work, but don't want to create a new pointer, just\n # reuse the old one.\n\n # 1.\n ptr_id = random.randint(0, 10e10)\n y = torch.FloatTensor([1, 2])\n y.send(bob, ptr_id=ptr_id)\n x = torch.FloatTensor([1, 2, 3, 4, 5])\n try:\n x.send(bob, ptr_id=ptr_id)\n assert False\n except MemoryError:\n assert True\n\n # 2.\n x = torch.FloatTensor([1, 2, -3, 4, 5]).send(bob)\n x_id = x.id\n y = x.abs_() # in-place operation\n assert y.child == x.child\n assert x.id == x_id\n assert y.id == x.id\n y.get()\n x.send(bob)\n\n def test_chain_send_get_tensor(self):\n\n x = torch.FloatTensor([1, 2, 3, 4, 5])\n id1 = random.randint(0, 10e10)\n id2 = random.randint(0, 10e10)\n id3 = random.randint(0, 10e10)\n x.send(bob, ptr_id=id1)\n assert id1 in bob._objects\n x.send(alice, ptr_id=id2)\n assert id2 in alice._objects\n x.send(james, ptr_id=id3)\n assert id3 in james._objects\n x.get()\n x.get()\n x.get()\n # test the get is ok\n assert torch.equal(x, torch.FloatTensor([1, 2, 3, 4, 5]))\n # Test that the remotes are empty\n assert id1 not in bob._objects\n assert id2 not in alice._objects\n assert id3 not in james._objects\n\n def test_add_remote_tensor(self):\n x = sy.FloatTensor([1, 2, 3, 4])\n x.send(bob, ptr_id=1000)\n x.send(alice, ptr_id=2000)\n y = sy.FloatTensor([2, 3, 4, 5])\n y.send(bob, ptr_id=1001)\n y.send(alice, ptr_id=2001)\n z = torch.add(x, y)\n z.get().get()\n assert torch.equal(z, torch.FloatTensor([3, 5, 7, 9]))\n\n # def test_fixed_prec_ops(self):\n # hook = TorchHook(verbose=False)\n\n # x = torch.FloatTensor([1, 2, 3, 4, 5]).set_precision(7)\n # y = torch.FloatTensor([1, 2, 3, 4, 5]).set_precision(3)\n\n # assert ((x + y).free_precision() == torch.FloatTensor([2, 4, 6, 8, 10])).all()\n # assert ((x / y).free_precision() == torch.FloatTensor([1, 1, 1, 1, 1])).all()\n # assert ((x * y).free_precision() == torch.FloatTensor([1, 4, 9, 16, 25])).all()\n # assert ((x - y).free_precision() == torch.FloatTensor([0, 0, 0, 0, 0])).all()\n\n # x = torch.FloatTensor([1, 2, 3, 4, 5]).set_precision(3)\n # y = torch.FloatTensor([1, 2, 3, 4, 5]).set_precision(7)\n\n # assert ((x + y).free_precision() == torch.FloatTensor([2, 4, 6, 8, 10])).all()\n # assert ((x / y).free_precision() == torch.FloatTensor([1, 1, 1, 1, 1])).all()\n # assert ((x * y).free_precision() == torch.FloatTensor([1, 4, 9, 16, 25])).all()\n # assert ((x - y).free_precision() == torch.FloatTensor([0, 0, 0, 0, 0])).all()\n\n # x = torch.FloatTensor([1, 2, 3, 4, 5]).set_precision(3)\n # y = torch.FloatTensor([1, 2, 3, 4, 5]).set_precision(3)\n\n # assert ((x + y).free_precision() == torch.FloatTensor([2, 4, 6, 8, 10])).all()\n # assert ((x / y).free_precision() == torch.FloatTensor([1, 1, 1, 1, 1])).all()\n # assert ((x * y).free_precision() == torch.FloatTensor([1, 4, 9, 16, 25])).all()\n # assert ((x - y).free_precision() == torch.FloatTensor([0, 0, 0, 0, 0])).all()\n\n def test_local_tensor_unary_methods(self):\n \"\"\"Unit tests for methods mentioned on issue 1385\n https://github.com/OpenMined/PySyft/issues/1385.\"\"\"\n\n x = torch.FloatTensor([1, 2, -3, 4, 5])\n assert (x.abs() == torch.FloatTensor([1, 2, 3, 4, 5])).all()\n assert (x.abs_() == torch.FloatTensor([1, 2, 3, 4, 5])).all()\n x = x.cos()\n assert (x.int() == torch.IntTensor([0, 0, 0, 0, 0])).all()\n\n x = x.cos_()\n assert (x.int() == torch.IntTensor([0, 0, 0, 0, 0])).all()\n\n x = torch.FloatTensor([1, 2, -3, 4, 5])\n\n assert (x.ceil() == x).all()\n assert (x.ceil_() == x).all()\n assert (x.cpu() == x).all()\n\n def test_local_tensor_binary_methods(self):\n \"\"\"Unit tests for methods mentioned on issue 1385\n https://github.com/OpenMined/PySyft/issues/1385.\"\"\"\n\n x = torch.FloatTensor([1, 2, 3, 4])\n y = torch.FloatTensor([[1, 2, 3, 4]])\n z = torch.matmul(x, y.t())\n assert torch.equal(z, torch.FloatTensor([30]))\n\n z = torch.add(x, y)\n assert torch.equal(z, torch.FloatTensor([[2, 4, 6, 8]]))\n\n x = torch.FloatTensor([[1, 2, 3], [3, 4, 5], [5, 6, 7]])\n y = torch.FloatTensor([[1, 2, 3], [3, 4, 5], [5, 6, 7]])\n z = torch.cross(x, y, dim=1)\n assert torch.equal(z, torch.FloatTensor([[0, 0, 0], [0, 0, 0], [0, 0, 0]]))\n\n x = torch.FloatTensor([[1, 2, 3], [3, 4, 5], [5, 6, 7]])\n y = torch.FloatTensor([[1, 2, 3], [3, 4, 5], [5, 6, 7]])\n z = torch.dist(x, y)\n assert torch.equal(torch.FloatTensor([z]), torch.FloatTensor([0]))\n\n x = torch.FloatTensor([1, 2, 3])\n y = torch.FloatTensor([1, 2, 3])\n z = torch.dot(x, y)\n # There is an issue with some Macs getting 0.0 instead\n # Solved here: https://github.com/pytorch/pytorch/issues/5609\n assert torch.equal(torch.FloatTensor([z]), torch.FloatTensor([14])), (\n \"There is an issue with some Macs getting 0.0 instead, \"\n \"see https://github.com/pytorch/pytorch/issues/5609\"\n )\n\n z = torch.eq(x, y)\n assert torch.equal(z, torch.ByteTensor([1, 1, 1]))\n\n z = torch.ge(x, y)\n assert torch.equal(z, torch.ByteTensor([1, 1, 1]))\n\n x = torch.FloatTensor([1, 2, 3, 4, 5])\n y = torch.FloatTensor([1, 2, 3, 4, 5])\n assert (x.add_(y) == torch.FloatTensor([2, 4, 6, 8, 10])).all()\n\n def test_remote_tensor_unary_methods(self):\n \"\"\"Unit tests for methods mentioned on issue 1385\n https://github.com/OpenMined/PySyft/issues/1385.\"\"\"\n\n x = torch.FloatTensor([1, 2, -3, 4, 5]).send(bob)\n assert (x.abs().get() == torch.FloatTensor([1, 2, 3, 4, 5])).all()\n\n x = torch.FloatTensor([1, 2, -3, 4, 5]).send(bob)\n assert (x.cos().int().get() == torch.IntTensor([0, 0, 0, 0, 0])).all()\n y = x.cos_()\n assert (y.cos_().int().get() == torch.IntTensor([0, 0, 0, 0, 0])).all()\n x = torch.FloatTensor([1, 2, -3, 4, 5]).send(bob)\n assert (x.ceil().get() == torch.FloatTensor([1, 2, -3, 4, 5])).all()\n\n assert (x.cpu().get() == torch.FloatTensor([1, 2, -3, 4, 5])).all()\n\n def test_remote_tensor_binary_methods(self):\n\n x = torch.FloatTensor([1, 2, 3, 4, 5]).send(bob)\n y = torch.FloatTensor([1, 2, 3, 4, 5]).send(bob)\n assert (torch.add(x, y).get() == torch.FloatTensor([2, 4, 6, 8, 10])).all()\n\n x = torch.FloatTensor([1, 2, 3, 4]).send(bob)\n y = torch.FloatTensor([[1], [2], [3], [4]]).send(bob)\n z = torch.matmul(x, y)\n assert torch.equal(z.get(), torch.FloatTensor([30]))\n\n x = torch.FloatTensor([[1, 2, 3], [3, 4, 5], [5, 6, 7]]).send(bob)\n y = torch.FloatTensor([[1, 2, 3], [3, 4, 5], [5, 6, 7]]).send(bob)\n z = torch.cross(x, y, dim=1)\n assert torch.equal(\n z.get(), torch.FloatTensor([[0, 0, 0], [0, 0, 0], [0, 0, 0]])\n )\n\n x = torch.FloatTensor([[1, 2, 3], [3, 4, 5], [5, 6, 7]]).send(bob)\n y = torch.FloatTensor([[1, 2, 3], [3, 4, 5], [5, 6, 7]]).send(bob)\n z = torch.dist(x, y)\n z.get()\n assert torch.equal(z, torch.FloatTensor([0.0]))\n\n x = torch.FloatTensor([1, 2, 3]).send(bob).send(alice)\n y = torch.FloatTensor([1, 2, 3]).send(bob).send(alice)\n z = torch.dot(x, y)\n z.get().get()\n assert torch.equal(z, torch.FloatTensor([14]))\n\n z = torch.eq(x, y)\n assert torch.equal(z.get().get(), torch.ByteTensor([1, 1, 1]))\n\n z = torch.ge(x, y)\n assert torch.equal(z.get().get(), torch.ByteTensor([1, 1, 1]))\n\n def test_local_tensor_tertiary_methods(self):\n\n x = torch.FloatTensor([1, 2, 3])\n y = torch.FloatTensor([1, 2, 3])\n z = torch.FloatTensor([1, 2, 3])\n assert torch.equal(\n torch.addcmul(z, 2, x, y), torch.FloatTensor([3.0, 10.0, 21.0])\n )\n\n x = torch.FloatTensor([1, 2, 3])\n y = torch.FloatTensor([1, 2, 3])\n z = torch.FloatTensor([1, 2, 3])\n z.addcmul_(2, x, y)\n assert torch.equal(z, torch.FloatTensor([3.0, 10.0, 21.0]))\n\n x = torch.FloatTensor([[1, 2]])\n y = torch.FloatTensor([[1, 2, 3], [4, 5, 6]])\n z = torch.FloatTensor([1, 2, 3])\n assert torch.equal(\n torch.addmm(z, x, y), torch.FloatTensor([[10.0, 14.0, 18.0]])\n )\n\n def test_remote_tensor_tertiary_methods(self):\n\n x = torch.FloatTensor([1, 2, 3]).send(bob)\n y = torch.FloatTensor([1, 2, 3]).send(bob)\n z = torch.FloatTensor([1, 2, 3]).send(bob)\n assert torch.equal(\n torch.addcmul(z, 2, x, y).get(), torch.FloatTensor([3.0, 10.0, 21.0])\n )\n\n # Uses a method\n x = torch.FloatTensor([1, 2, 3]).send(bob)\n y = torch.FloatTensor([1, 2, 3]).send(bob)\n z = torch.FloatTensor([1, 2, 3]).send(bob)\n z.addcmul_(2, x, y)\n assert torch.equal(z.get(), torch.FloatTensor([3.0, 10.0, 21.0]))\n\n x = torch.FloatTensor([[1, 2]]).send(bob)\n y = torch.FloatTensor([[1, 2, 3], [4, 5, 6]]).send(bob)\n z = torch.FloatTensor([1, 2, 3]).send(bob)\n assert torch.equal(\n torch.addmm(z, x, y).get(), torch.FloatTensor([[10.0, 14.0, 18.0]])\n )\n\n def test_local_tensor_iterable_methods(self):\n\n x = torch.FloatTensor([1, 2, 3])\n y = torch.FloatTensor([2, 3, 4])\n z = torch.FloatTensor([5, 6, 7])\n assert torch.equal(\n torch.stack([x, y, z]), torch.FloatTensor([[1, 2, 3], [2, 3, 4], [5, 6, 7]])\n )\n\n x = torch.FloatTensor([1, 2, 3])\n y = torch.FloatTensor([2, 3, 4])\n z = torch.FloatTensor([5, 6, 7])\n assert torch.equal(\n torch.cat([x, y, z]), torch.FloatTensor([1, 2, 3, 2, 3, 4, 5, 6, 7])\n )\n\n def test_remote_tensor_iterable_methods(self):\n\n x = torch.FloatTensor([1, 2, 3]).send(bob)\n y = torch.FloatTensor([2, 3, 4]).send(bob)\n z = torch.FloatTensor([5, 6, 7]).send(bob)\n x.get()\n y.get()\n z.get()\n assert torch.equal(\n torch.stack([x, y, z]), torch.FloatTensor([[1, 2, 3], [2, 3, 4], [5, 6, 7]])\n )\n\n x = torch.FloatTensor([1, 2, 3]).send(bob)\n y = torch.FloatTensor([2, 3, 4]).send(bob)\n z = torch.FloatTensor([5, 6, 7]).send(bob)\n x.get()\n y.get()\n z.get()\n assert torch.equal(\n torch.cat([x, y, z]), torch.FloatTensor([1, 2, 3, 2, 3, 4, 5, 6, 7])\n )\n\n def test_remote_tensor_unwrapped_addition(self):\n\n x = torch.LongTensor([1, 2, 3, 4, 5]).send(bob)\n y = x.child + x.child\n assert (y.get() == x.get() * 2).all()\n\n def test_end_get_tensor(self):\n\n bob_id = random.randint(0, 10e10)\n alice_id = random.randint(0, 10e10)\n x = (\n sy.FloatTensor([1, 2, 3, 4, 5])\n .send(bob, ptr_id=bob_id)\n .send(alice, ptr_id=alice_id)\n )\n\n x2 = x.end_get()\n # Now alice will own the tensor that was in bob and bob won't have it anymore\n assert bob_id not in bob._objects\n assert alice_id in alice._objects\n assert isinstance(alice._objects[alice_id], sy._LocalTensor)\n\n assert torch.equal(x2.get(), torch.FloatTensor([1, 2, 3, 4, 5]))\n\n\nclass TestTorchVariable(TestCase):\n def test_remote_backprop(self):\n\n x = sy.Variable(torch.ones(2, 2), requires_grad=True).send(bob)\n x2 = sy.Variable(torch.ones(2, 2) * 2, requires_grad=True).send(bob)\n\n y = x * x2\n\n y.sum().backward()\n\n # remote grads should be correct\n assert (\n bob._objects[x2.child.id_at_location].child.grad.data == torch.ones(2, 2)\n ).all()\n # You can call .grad on a syft tensor, which make .child and .grad commutative\n assert (\n bob._objects[x2.child.id_at_location].grad.child.data == torch.ones(2, 2)\n ).all()\n assert (\n bob._objects[x.child.id_at_location].child.grad.data == torch.ones(2, 2) * 2\n ).all()\n\n assert (y.get().data == torch.ones(2, 2) * 2).all()\n\n assert (x.get().data == torch.ones(2, 2)).all()\n assert (x2.get().data == torch.ones(2, 2) * 2).all()\n\n assert (x.grad.data == torch.ones(2, 2) * 2).all()\n assert (x2.grad.data == torch.ones(2, 2)).all()\n\n def test_variable_data_attribute_bug(self):\n\n # previously, newly created Variable objects would lose their OpenMined given\n # attributes on the .data python objects they contain whenever the Variable\n # object is returned from a function. This bug was fixed by storing a bbackup\n # pointer to the .data object (.data_backup) so that the python object doesn't\n # get garbage collected. This test used to error out at the last line (as\n # indcated below)\n\n def relu(x):\n \"\"\"Rectified linear activation.\"\"\"\n return torch.clamp(x, min=0.0)\n\n def linear(x, w):\n \"\"\"Linear transformation of x by w.\"\"\"\n return x.mm(w)\n\n x = Var(torch.FloatTensor([[1, 1], [2, 2]]), requires_grad=True)\n y = Var(torch.FloatTensor([[1, 1], [2, 2]]), requires_grad=True)\n\n z = linear(x, y)\n\n # previously we had to do the following to prevent this bug\n # leaving it here for reference in case the bug returns later.\n # print(z.data.is_pointer)\n\n # before the bugfix, the following line would error out.\n z = relu(z)\n\n assert True\n\n def test_encode_decode_json_python(self):\n \"\"\"Test that the python objects are correctly encoded and decoded in\n json with our encoder/JSONDecoder.\n\n The main focus is on non-serializable objects, such as torch\n Variable or tuple, or even slice().\n \"\"\"\n\n x = Var(torch.FloatTensor([[1, -1], [0, 1]]))\n x.send(bob)\n obj = [None, ({\"marcel\": (1, [1.3], x), \"proust\": slice(0, 2, None)}, 3)]\n enc, t = encode.encode(obj)\n enc = msgpack.packb(enc, use_bin_type=True)\n dec1 = encode.decode(enc, me)\n enc, t = encode.encode(dec1)\n enc = msgpack.packb(enc, use_bin_type=True)\n dec2 = encode.decode(enc, me)\n assert dec1 == dec2\n\n def test_var_gradient_keeps_id_during_send_(self):\n # PyTorch has a tendency to delete var.grad python objects\n # and re-initialize them (resulting in new/random ids)\n # we have fixed this bug and recorded how it was fixed\n # as well as the creation of this unit test in the following\n # video (1:50:00 - 2:00:00) ish\n # https://www.twitch.tv/videos/275838386\n\n data = Var(torch.FloatTensor([[0, 0], [0, 1], [1, 0], [1, 1]]))\n target = Var(torch.FloatTensor([[0], [0], [1], [1]]))\n\n model = Var(torch.zeros(2, 1), requires_grad=True)\n\n # generates grad objects on model\n pred = data.mm(model)\n loss = ((pred - target) ** 2).sum()\n loss.backward()\n\n # the grad's true id\n original_data_id = model.data.id + 0\n original_grad_id = model.grad.data.id + 0\n\n model.send(bob)\n\n assert model.data.id == original_data_id\n assert model.grad.data.id == original_grad_id\n\n def test_operation_with_variable_and_parameter(self):\n x = sy.Parameter(sy.FloatTensor([1]))\n y = sy.Variable(sy.FloatTensor([1]))\n z = x * y\n assert torch.equal(z, sy.Variable(sy.FloatTensor([1])))\n\n def test_send_var_with_gradient(self):\n\n # For now, we assume that var.grad.data does not get allocated\n # a pointer because it would not get used.\n\n data = Var(torch.FloatTensor([[0, 0], [0, 1], [1, 0], [1, 1]]))\n target = Var(torch.FloatTensor([[0], [0], [1], [1]]))\n\n model = Var(torch.zeros(2, 1), requires_grad=True)\n\n # generates grad objects on model\n pred = data.mm(model)\n loss = ((pred - target) ** 2).sum()\n loss.backward()\n\n # ensure that model and all (grand)children are owned by the local worker\n assert model.owner.id == me.id\n assert model.data.owner.id == me.id\n\n # if you get a failure here saying that model.grad.owners does not exist\n # check in hooks.py - _hook_new_grad(). self.grad_backup has probably either\n # been deleted or is being run at the wrong time (see comments there)\n assert model.grad.owner.id == me.id\n assert model.grad.data.owner.id == me.id\n\n # ensure that objects are not yet pointers (haven't sent it yet)\n assert not isinstance(model.child, sy._PointerTensor)\n assert not isinstance(model.data.child, sy._PointerTensor)\n assert not isinstance(model.grad.child, sy._PointerTensor)\n assert not isinstance(model.grad.data.child, sy._PointerTensor)\n\n model.send(bob)\n\n assert model.location.id == bob.id\n assert model.data.location.id == bob.id\n assert model.grad.location.id == bob.id\n assert model.grad.data.location.id == bob.id\n\n # ensure that objects are not yet pointers (haven't sent it yet)\n assert isinstance(model.child, sy._PointerTensor)\n assert isinstance(model.data.child, sy._PointerTensor)\n assert isinstance(model.grad.child, sy._PointerTensor)\n assert isinstance(model.grad.data.child, sy._PointerTensor)\n\n assert model.id_at_location in bob._objects\n assert model.data.id_at_location in bob._objects\n assert model.grad.id_at_location in bob._objects\n assert model.grad.data.id_at_location in bob._objects\n\n def test_remote_optim_step(self):\n\n torch.manual_seed(42)\n\n param = []\n\n data = Var(torch.FloatTensor([[0, 0], [0, 1], [1, 0], [1, 1]])).send(bob)\n target = Var(torch.FloatTensor([[0], [0], [1], [1]])).send(bob)\n\n model = torch.nn.Linear(2, 1)\n opt = torch.optim.SGD(params=model.parameters(), lr=0.1)\n\n for i in model.parameters():\n param.append(i[:])\n\n model.send(bob)\n model.zero_grad()\n pred = model(data)\n loss = ((pred - target) ** 2).sum()\n loss.backward()\n opt.step()\n\n model.get()\n for i in model.parameters():\n param.append(i[:])\n\n x = []\n for i in param:\n if type(i.data[0]) != float:\n x.append(i.data[0][0])\n x.append(i.data[0][1])\n else:\n x.append(i.data[0])\n\n y = [\n 0.5406,\n 0.5869,\n -0.165_655_672_550_201_42,\n 0.6732,\n 0.5103,\n -0.084_136_970_341_205_6,\n ]\n\n assert (self.assertAlmostEqual(X, Y) for X, Y in zip(x, y))\n\n def test_federated_learning(self):\n\n torch.manual_seed(42)\n # hook = TorchHook(verbose=False)\n # me = hook.local_worker\n # me.verbose = False\n #\n # bob = VirtualWorker(id=1, hook=hook, verbose=False)\n # alice = VirtualWorker(id=2, hook=hook, verbose=False)\n\n # me.add_worker(bob)\n # me.add_worker(alice)\n\n # create our dataset\n data = Var(torch.FloatTensor([[0, 0], [0, 1], [1, 0], [1, 1]]))\n target = Var(torch.FloatTensor([[0], [0], [1], [1]]))\n\n data_bob = (data[0:2] + 0).send(bob)\n target_bob = (target[0:2] + 0).send(bob)\n\n data_alice = data[2:].send(alice)\n target_alice = target[2:].send(alice)\n\n # create our model\n model = torch.nn.Linear(2, 1)\n\n opt = torch.optim.SGD(params=model.parameters(), lr=0.1)\n\n datasets = [(data_bob, target_bob), (data_alice, target_alice)]\n\n for iter in range(2):\n\n for data, target in datasets:\n model.send(data.location)\n\n # update the model\n model.zero_grad()\n pred = model(data)\n loss = ((pred - target) ** 2).sum()\n loss.backward()\n opt.step()\n\n model.get()\n if iter == 1:\n final_loss = loss.get().data[0]\n\n assert (final_loss - 0.180_852_845_311_164_86) < 0.001\n\n def test_torch_function_on_remote_var(self):\n x = sy.Variable(torch.FloatTensor([[1, 2], [3, 4]]))\n y = sy.Variable(torch.FloatTensor([[1, 2], [1, 2]]))\n x.send(bob)\n y.send(bob)\n z = torch.matmul(x, y)\n z.get()\n assert torch.equal(z, sy.Variable(torch.FloatTensor([[3, 6], [7, 14]])))\n\n def test_torch_function_with_multiple_input_on_remote_var(self):\n x = sy.Variable(torch.FloatTensor([1, 2]))\n y = sy.Variable(torch.FloatTensor([3, 4]))\n x.send(bob)\n y.send(bob)\n z = torch.stack([x, y])\n z.get()\n assert torch.equal(z, sy.Variable(torch.FloatTensor([[1, 2], [3, 4]])))\n\n def test_torch_function_with_multiple_output_on_remote_var(self):\n x = sy.Variable(torch.FloatTensor([[1, 2], [4, 3], [5, 6]]))\n x.send(bob)\n y, z = torch.max(x, 1)\n y.get()\n assert torch.equal(y, sy.Variable(torch.FloatTensor([2, 4, 6])))\n\n def test_torch_F_relu_on_remote_var(self):\n x = sy.Variable(torch.FloatTensor([[1, -1], [-1, 1]]))\n x.send(bob)\n x = F.relu(x)\n x.get()\n assert torch.equal(x, sy.Variable(torch.FloatTensor([[1, 0], [0, 1]])))\n\n def test_torch_F_conv2d_on_remote_var(self):\n x = sy.Variable(torch.FloatTensor([[[[1, -1, 2], [-1, 0, 1], [1, 0, -2]]]]))\n x.send(bob)\n weight = torch.nn.Parameter(torch.FloatTensor([[[[1, -1], [-1, 1]]]]))\n bias = torch.nn.Parameter(torch.FloatTensor([0]))\n weight.send(bob)\n bias.send(bob)\n conv = F.conv2d(x, weight, bias, stride=(1, 1))\n conv.get()\n expected_conv = sy.Variable(torch.FloatTensor([[[[3, -2], [-2, -3]]]]))\n assert torch.equal(conv, expected_conv)\n\n def test_torch_nn_conv2d_on_remote_var(self):\n\n x = sy.Variable(torch.FloatTensor([[[[1, -1, 2], [-1, 0, 1], [1, 0, -2]]]]))\n x.send(bob)\n convolute = torch.nn.Conv2d(1, 1, 2, stride=1, padding=0)\n convolute.weight = torch.nn.Parameter(torch.FloatTensor([[[[1, -1], [-1, 1]]]]))\n convolute.bias = torch.nn.Parameter(torch.FloatTensor([0]))\n convolute.send(bob)\n conv = convolute(x)\n conv.get()\n expected_conv = sy.Variable(torch.FloatTensor([[[[3, -2], [-2, -3]]]]))\n assert torch.equal(conv, expected_conv)\n\n def test_local_var_unary_methods(self):\n \"\"\"Unit tests for methods mentioned on issue 1385\n https://github.com/OpenMined/PySyft/issues/1385.\"\"\"\n\n x = sy.Variable(torch.FloatTensor([1, 2, -3, 4, 5]))\n assert torch.equal(x.abs(), sy.Variable(torch.FloatTensor([1, 2, 3, 4, 5])))\n assert torch.equal(x.abs_(), sy.Variable(torch.FloatTensor([1, 2, 3, 4, 5])))\n x = sy.Variable(torch.FloatTensor([1, 2, -3, 4, 5]))\n assert torch.equal(x.cos().int(), sy.Variable(torch.IntTensor([0, 0, 0, 0, 0])))\n x = sy.Variable(torch.FloatTensor([1, 2, -3, 4, 5]))\n assert torch.equal(\n x.cos_().int(), sy.Variable(torch.IntTensor([0, 0, 0, 0, 0]))\n )\n x = sy.Variable(torch.FloatTensor([1, 2, -3, 4, 5]))\n assert torch.equal(x.ceil(), x)\n assert torch.equal(x.ceil_(), x)\n assert torch.equal(x.cpu(), x)\n\n def test_local_var_binary_methods(self):\n \"\"\"Unit tests for methods mentioned on issue 1385\n https://github.com/OpenMined/PySyft/issues/1385.\"\"\"\n x = torch.FloatTensor([1, 2, 3, 4])\n y = torch.FloatTensor([[1, 2, 3, 4]])\n z = torch.matmul(x, y.t())\n assert torch.equal(z, torch.FloatTensor([30]))\n z = torch.add(x, y)\n assert torch.equal(z, torch.FloatTensor([[2, 4, 6, 8]]))\n x = sy.Variable(torch.FloatTensor([1, 2, 3, 4, 5]))\n y = sy.Variable(torch.FloatTensor([1, 2, 3, 4, 5]))\n assert torch.equal(x.add_(y), sy.Variable(torch.FloatTensor([2, 4, 6, 8, 10])))\n x = torch.FloatTensor([[1, 2, 3], [3, 4, 5], [5, 6, 7]])\n y = torch.FloatTensor([[1, 2, 3], [3, 4, 5], [5, 6, 7]])\n z = torch.cross(x, y, dim=1)\n assert torch.equal(z, torch.FloatTensor([[0, 0, 0], [0, 0, 0], [0, 0, 0]]))\n x = torch.FloatTensor([[1, 2, 3], [3, 4, 5], [5, 6, 7]])\n y = torch.FloatTensor([[1, 2, 3], [3, 4, 5], [5, 6, 7]])\n z = torch.dist(x, y)\n t = torch.FloatTensor([z])\n assert torch.equal(t, torch.FloatTensor([0.0]))\n x = torch.FloatTensor([1, 2, 3])\n y = torch.FloatTensor([1, 2, 3])\n z = torch.dot(x, y)\n t = torch.FloatTensor([z])\n assert torch.equal(t, torch.FloatTensor([14]))\n z = torch.eq(x, y)\n assert torch.equal(z, torch.ByteTensor([1, 1, 1]))\n z = torch.ge(x, y)\n assert torch.equal(z, torch.ByteTensor([1, 1, 1]))\n\n def test_remote_var_unary_methods(self):\n \"\"\"Unit tests for methods mentioned on issue 1385\n https://github.com/OpenMined/PySyft/issues/1385.\"\"\"\n\n x = sy.Variable(torch.FloatTensor([1, 2, -3, 4, 5])).send(bob)\n assert torch.equal(\n x.abs().get(), sy.Variable(torch.FloatTensor([1, 2, 3, 4, 5]))\n )\n assert torch.equal(\n x.abs_().get(), sy.Variable(torch.FloatTensor([1, 2, 3, 4, 5]))\n )\n x = sy.Variable(torch.FloatTensor([1, 2, -3, 4, 5])).send(bob)\n assert torch.equal(\n x.cos().int().get(), sy.Variable(torch.IntTensor([0, 0, 0, 0, 0]))\n )\n assert torch.equal(\n x.cos_().int().get(), sy.Variable(torch.IntTensor([0, 0, 0, 0, 0]))\n )\n x = sy.Variable(torch.FloatTensor([1, 2, -3, 4, 5])).send(bob)\n assert torch.equal(\n x.ceil().get(), sy.Variable(torch.FloatTensor([1, 2, -3, 4, 5]))\n )\n assert torch.equal(\n x.ceil_().get(), sy.Variable(torch.FloatTensor([1, 2, -3, 4, 5]))\n )\n x = sy.Variable(torch.FloatTensor([1, 2, -3, 4, 5])).send(bob)\n assert torch.equal(\n x.cpu().get(), sy.Variable(torch.FloatTensor([1, 2, -3, 4, 5]))\n )\n\n def test_remote_var_binary_methods(self):\n \"\"\"Unit tests for methods mentioned on issue 1385\n https://github.com/OpenMined/PySyft/issues/1385.\"\"\"\n\n x = sy.Variable(torch.FloatTensor([1, 2, 3, 4])).send(bob)\n y = sy.Variable(torch.FloatTensor([[1, 2, 3, 4]])).send(bob)\n z = torch.matmul(x, y.t())\n assert torch.equal(z.get(), sy.Variable(torch.FloatTensor([30])))\n z = torch.add(x, y)\n assert torch.equal(z.get(), sy.Variable(torch.FloatTensor([[2, 4, 6, 8]])))\n x = sy.Variable(torch.FloatTensor([1, 2, 3, 4, 5])).send(bob)\n y = sy.Variable(torch.FloatTensor([1, 2, 3, 4, 5])).send(bob)\n assert torch.equal(\n x.add_(y).get(), sy.Variable(torch.FloatTensor([2, 4, 6, 8, 10]))\n )\n x = sy.Variable(torch.FloatTensor([[1, 2, 3], [3, 4, 5], [5, 6, 7]])).send(bob)\n y = sy.Variable(torch.FloatTensor([[1, 2, 3], [3, 4, 5], [5, 6, 7]])).send(bob)\n z = torch.cross(x, y, dim=1)\n assert torch.equal(\n z.get(), sy.Variable(torch.FloatTensor([[0, 0, 0], [0, 0, 0], [0, 0, 0]]))\n )\n x = sy.Variable(torch.FloatTensor([[1, 2, 3], [3, 4, 5], [5, 6, 7]])).send(bob)\n y = sy.Variable(torch.FloatTensor([[1, 2, 3], [3, 4, 5], [5, 6, 7]])).send(bob)\n z = torch.dist(x, y)\n assert torch.equal(z.get(), sy.Variable(torch.FloatTensor([0.0])))\n x = sy.Variable(torch.FloatTensor([1, 2, 3])).send(bob)\n y = sy.Variable(torch.FloatTensor([1, 2, 3])).send(bob)\n z = torch.dot(x, y)\n assert torch.equal(z.get(), sy.Variable(torch.FloatTensor([14])))\n z = torch.eq(x, y)\n assert torch.equal(z.get(), sy.Variable(torch.ByteTensor([1, 1, 1])))\n z = torch.ge(x, y)\n assert torch.equal(z.get(), sy.Variable(torch.ByteTensor([1, 1, 1])))\n\n\nclass TestSNNTensor(TestCase):\n def test_mpc_relu(self):\n a = (torch.LongTensor([-1, 3, -5, 7])).share(alice, bob)\n b = a.relu()\n assert (b.get() == torch.LongTensor([0, 3, 0, 7])).all()\n\n def test_mpc_argmax(self):\n x = (\n (torch.FloatTensor([[0.1, 0.2, 0.4, 0.3], [0.9, 0, 0, 0.1]]))\n .fix_precision()\n .share(alice, bob)\n )\n out = x.argmax()\n assert (\n out.get().decode() == torch.FloatTensor([[0, 0, 1, 0], [1, 0, 0, 0]])\n ).all()\n\n def test_mpc_train(self):\n # create our dataset\n data = sy.FloatTensor([[0, 0], [0, 1], [1, 0], [1, 1]])\n target = sy.FloatTensor([[0], [0], [1], [1]])\n\n model = sy.zeros(2, 1)\n\n data = data.fix_precision().share(alice, bob)\n target = target.fix_precision().share(alice, bob)\n model = model.fix_precision().share(alice, bob)\n\n for i in range(10):\n pred = data.mm(model)\n grad = pred - target\n update = data.transpose(0, 1).mm(grad)\n\n model = model - update * 0.1\n loss = grad.get().decode().abs().sum()\n\n assert loss < 0.8\n\n def test_mpc_scalar_mult(self):\n\n data = torch.FloatTensor([1, 2, 3]).fix_precision().share(alice, bob)\n assert ((data * 0.1).get().decode() == torch.FloatTensor([0.1, 0.2, 0.3])).all()\n assert (\n (data * -0.1).get().decode() == torch.FloatTensor([-0.1, -0.2, -0.3])\n ).all()\n assert ((data * 1.1).get().decode() == torch.FloatTensor([1.1, 2.2, 3.3])).all()\n\n\nclass TestSPDZTensor(TestCase):\n def mpc_sum(self, n1, n2):\n x = torch.LongTensor([n1])\n y = torch.LongTensor([n2])\n x = x.share(alice, bob)\n y = y.share(alice, bob)\n z = x + y\n z = z.get()\n assert torch.eq(z, torch.LongTensor([n1 + n2])).all()\n\n def mpc_var_sum(self, n1, n2):\n x = sy.Variable(torch.LongTensor([n1]))\n y = sy.Variable(torch.LongTensor([n2]))\n x = x.share(alice, bob)\n y = y.share(alice, bob)\n z = x + y\n z = z.get()\n z_ = sy.Variable(torch.LongTensor([n1 + n2]))\n assert torch.native_eq(z, z_).all()\n\n def test_mpc_sum(self):\n self.mpc_sum(3, 5)\n self.mpc_sum(4, 0)\n self.mpc_sum(5, -5)\n self.mpc_sum(3, -5)\n self.mpc_sum(2 ** 24, 2 ** 12)\n\n def test_mpc_var_sum(self):\n self.mpc_var_sum(3, 5)\n self.mpc_var_sum(4, 0)\n self.mpc_var_sum(5, -5)\n self.mpc_var_sum(3, -5)\n self.mpc_var_sum(2 ** 24, 2 ** 12)\n\n def mpc_mul(self, n1, n2):\n x = torch.LongTensor([n1])\n y = torch.LongTensor([n2])\n x = x.share(alice, bob)\n y = y.share(alice, bob)\n z = x * y\n z = z.get()\n assert torch.eq(z, torch.LongTensor([n1 * n2])).all(), (\n z,\n \"should be\",\n torch.LongTensor([n1 * n2]),\n )\n\n def mpc_var_mul(self, n1, n2):\n x = sy.Variable(torch.LongTensor([n1]))\n y = sy.Variable(torch.LongTensor([n2]))\n x = x.share(alice, bob)\n y = y.share(alice, bob)\n z = x * y\n z = z.get()\n z_ = sy.Variable(torch.LongTensor([n1 * n2]))\n assert torch.native_eq(z, z_).all()\n\n def test_mpc_mul(self):\n self.mpc_mul(3, 5)\n self.mpc_mul(4, 0)\n self.mpc_mul(5, -5)\n self.mpc_mul(3, 5)\n self.mpc_mul(2 ** 12, 2 ** 12)\n\n def test_mpc_var_mul(self):\n self.mpc_var_mul(3, 5)\n self.mpc_var_mul(4, 0)\n self.mpc_var_mul(5, -5)\n self.mpc_var_mul(3, 5)\n self.mpc_var_mul(2 ** 12, 2 ** 12)\n\n def test_mpc_scalar_mult(self):\n x = torch.LongTensor([[-1, 2], [3, 4]])\n x = x.share(bob, alice)\n\n y = torch.LongTensor([[2, 2], [2, 2]]).send(bob, alice)\n\n z = x * y\n assert (z.get() == torch.LongTensor([[-2, 4], [6, 8]])).all()\n\n x = torch.LongTensor([[-1, 2], [3, 4]])\n x = x.share(bob, alice)\n\n z = x * 2\n assert (z.get() == torch.LongTensor([[-2, 4], [6, 8]])).all()\n\n def test_spdz_matmul(self):\n x = torch.LongTensor([[1, 2], [3, 4]])\n y = torch.LongTensor([[5, 6], [7, 8]])\n\n x = x.share(bob, alice)\n y = y.share(bob, alice)\n\n assert (x.mm(y).get() - torch.LongTensor([[18, 22], [43, 49]])).abs().sum() < 5\n\n x = torch.LongTensor([[1, -2], [3, -4]])\n y = torch.LongTensor([[5, 6], [7, 8]])\n\n target = x.mm(y)\n\n x = x.share(bob, alice)\n y = y.share(bob, alice)\n\n result = x.mm(y)\n assert (result.get() - target).abs().sum() < 5\n\n def test_spdz_negation_and_subtraction(self):\n\n x = torch.LongTensor([[1, 2], [-3, -4]])\n\n x = x.share(bob, alice)\n\n z = -x\n\n assert (z.get() == torch.LongTensor([[-1, -2], [3, 4]])).all()\n\n x = torch.LongTensor([[1, -2], [-3, -4]])\n y = torch.LongTensor([[5, 6], [7, 8]])\n\n x = x.share(bob, alice)\n y = y.share(bob, alice)\n\n z = x - y\n assert (z.get() == torch.LongTensor([[-4, -8], [-10, -12]])).all()\n\n def test_spdz_mul_3_workers(self):\n n1, n2 = (3, -5)\n x = torch.LongTensor([n1])\n y = torch.LongTensor([n2])\n x = x.share(alice, bob, james)\n y = y.share(alice, bob, james)\n z = x * y\n z = z.get()\n assert (z == torch.LongTensor([n1 * n2])).all(), (\n z,\n \"should be\",\n torch.LongTensor([n1 * n2]),\n )\n\n def test_share(self):\n x = torch.LongTensor([-3])\n\n spdz_x = x.share(alice, bob, james)\n assert len(spdz_x.child.shares.child.pointer_tensor_dict.keys()) == 3\n\n spdz_x.get()\n\n assert sy.eq(spdz_x, sy.LongTensor([-3])).all()\n\n def test_fix_precision_decode(self):\n x = torch.FloatTensor([0.1, 0.2, 0.1, 0.2])\n x = x.fix_precision()\n\n assert (\n torch_utils.chain_print(x, display=False) == display_chain.tensor.fixp_local\n )\n\n x = x.decode()\n\n assert torch_utils.chain_print(x, display=False) == display_chain.tensor.local\n\n x = x.fix_precision()\n z = x + x\n z = z.decode()\n assert torch.eq(z, torch.FloatTensor([0.2, 0.4, 0.2, 0.4])).all()\n z = x + x\n z.decode_()\n assert torch.eq(z, torch.FloatTensor([0.2, 0.4, 0.2, 0.4])).all()\n x = x.decode()\n\n x = x.fix_precision()\n\n assert (\n torch_utils.chain_print(x, display=False) == display_chain.tensor.fixp_local\n )\n\n x.decode_()\n\n assert torch_utils.chain_print(x, display=False) == display_chain.tensor.local\n\n def test_fix_precision_mul(self):\n x = torch.FloatTensor([1, 2, 0.4])\n y = torch.FloatTensor([1, 1, 2])\n x = x.fix_precision(precision_fractional=3)\n y = y.fix_precision(precision_fractional=3)\n z = x * y\n z = z.decode()\n assert torch.eq(z, torch.FloatTensor([1, 2, 0.8])).all()\n\n # with different precision fractions x's > y's\n x = torch.FloatTensor([1, 2, 0.4])\n y = torch.FloatTensor([1, 1, 2])\n x = x.fix_precision(precision_fractional=3)\n y = y.fix_precision(precision_fractional=4)\n z = x * y\n z = z.decode()\n assert torch.eq(z, torch.FloatTensor([1, 2, 0.8])).all()\n\n # with different precision fractions x's < y's\n x = torch.FloatTensor([1, 2, 0.4])\n y = torch.FloatTensor([1, 1, 2])\n x = x.fix_precision(precision_fractional=3)\n y = y.fix_precision(precision_fractional=2)\n z = x * y\n z = z.decode()\n assert torch.eq(z, torch.FloatTensor([1, 2, 0.8])).all()\n\n def test_fix_precision_add(self):\n x = torch.FloatTensor([[1, 0.2], [0.9, 11]])\n y = torch.FloatTensor([[0.8, 1], [1, 3]])\n x = x.fix_precision()\n y = y.fix_precision()\n z = x + y\n z = z.decode()\n assert torch.eq(z, torch.FloatTensor([[1.8, 1.2], [1.9, 14]])).all()\n\n # with different precision fractions x's > y's\n x = torch.FloatTensor([[1, 0.2], [0.9, 11]])\n y = torch.FloatTensor([[0.8, 1], [1, 3]])\n x = x.fix_precision(precision_fractional=4)\n y = y.fix_precision(precision_fractional=3)\n z = x + y\n z = z.decode()\n assert torch.eq(z, torch.FloatTensor([[1.8, 1.2], [1.9, 14]])).all()\n\n # with different precision fractions x's < y's\n x = torch.FloatTensor([[1, 0.2], [0.9, 11]])\n y = torch.FloatTensor([[0.8, 1], [1, 3]])\n x = x.fix_precision(precision_fractional=3)\n y = y.fix_precision(precision_fractional=4)\n z = x + y\n z = z.decode()\n assert torch.eq(z, torch.FloatTensor([[1.8, 1.2], [1.9, 14]])).all()\n\n def test_fix_precision_sub(self):\n x = torch.FloatTensor([[1, 1.2], [1.9, 11]])\n y = torch.FloatTensor([[0.8, 1], [1, 3]])\n x = x.fix_precision()\n y = y.fix_precision()\n z = x - y\n z = z.decode()\n assert torch.eq(z, torch.FloatTensor([[0.2, 0.2], [0.9, 8]])).all()\n\n # with different precision fractions x's > y's\n x = torch.FloatTensor([[1, 1.2], [1.9, 11]])\n y = torch.FloatTensor([[0.8, 1], [1, 3]])\n x = x.fix_precision(precision_fractional=4)\n y = y.fix_precision(precision_fractional=3)\n z = x - y\n z = z.decode()\n assert torch.eq(z, torch.FloatTensor([[0.2, 0.2], [0.9, 8]])).all()\n\n # with different precision fractions x's < y's\n x = torch.FloatTensor([[1, 1.2], [1.9, 11]])\n y = torch.FloatTensor([[0.8, 1], [1, 3]])\n x = x.fix_precision(precision_fractional=3)\n y = y.fix_precision(precision_fractional=4)\n z = x - y\n z = z.decode()\n assert torch.eq(z, torch.FloatTensor([[0.2, 0.2], [0.9, 8]])).all()\n\n def test_fix_precision_div(self):\n x = torch.FloatTensor([[1, 1.2], [1.9, 12]])\n y = torch.FloatTensor([[0.8, 0.4], [1, 3]])\n x = x.fix_precision()\n y = y.fix_precision()\n z = x / y\n z = z.decode()\n assert torch.eq(z, torch.FloatTensor([[1.2500, 3], [1.9, 4]])).all()\n\n # with different precision fractions x's > y's\n x = torch.FloatTensor([[1, 1.2], [1.9, 12]])\n y = torch.FloatTensor([[0.8, 0.4], [1, 3]])\n x = x.fix_precision(precision_fractional=4)\n y = y.fix_precision(precision_fractional=3)\n z = x / y\n z = z.decode()\n assert torch.eq(z, torch.FloatTensor([[1.2000, 3], [1.9, 4]])).all()\n\n # with different precision fractions x's < y's\n x = torch.FloatTensor([[1, 1.2], [1.9, 12]])\n y = torch.FloatTensor([[0.8, 0.4], [1, 3]])\n x = x.fix_precision(precision_fractional=3)\n y = y.fix_precision(precision_fractional=4)\n z = x / y\n z = z.decode()\n assert torch.eq(z, torch.FloatTensor([[1.2500, 3], [1.9, 4]])).all()\n\n def test_fix_precision_sum(self):\n x = torch.FloatTensor([[1, 1.2], [1.9, 12]])\n x = x.fix_precision(precision_fractional=4)\n z = x.sum(0)\n z = z.decode()\n assert torch.eq(z, torch.FloatTensor([2, 13])).all()\n\n def test_fix_precision_cumsum(self):\n x = torch.FloatTensor([[1, 1.2], [1.9, 12]])\n x = x.fix_precision(precision_fractional=4)\n z = x.cumsum(0)\n z = z.decode()\n assert torch.eq(z, torch.FloatTensor([[1, 1], [2, 13]])).all()\n\n def test_fix_precision_prod(self):\n x = torch.FloatTensor([[1, 1.2], [1.9, 12]])\n x = x.fix_precision(precision_fractional=4)\n z = x.prod(0)\n z = z.decode()\n assert torch.eq(z, torch.FloatTensor([1, 14])).all()\n\n def test_var_fix_precision_decode(self):\n x = sy.Variable(torch.FloatTensor([0.1, 0.2, 0.1, 0.2]))\n x = x.fix_precision()\n\n assert torch_utils.chain_print(x, display=False) == display_chain.var.fixp_local\n\n x = x.decode()\n\n assert torch_utils.chain_print(x, display=False) == display_chain.var.local\n\n x = x.fix_precision()\n z = x + x\n z = z.decode()\n assert torch.eq(z, sy.Variable(torch.FloatTensor([0.2, 0.4, 0.2, 0.4]))).all()\n z = x + x\n z.decode_()\n assert torch.eq(z, sy.Variable(torch.FloatTensor([0.2, 0.4, 0.2, 0.4]))).all()\n x = x.decode()\n\n x = x.fix_precision()\n\n assert torch_utils.chain_print(x, display=False) == display_chain.var.fixp_local\n\n x.decode_()\n\n assert torch_utils.chain_print(x, display=False) == display_chain.var.local\n\n def test_remote_fix_precision(self):\n x = torch.FloatTensor([0.1, 0.2, 0.1, 0.2])\n x = x.send(bob).fix_precision()\n\n assert torch_utils.chain_print(x, display=False) == display_chain.tensor.pointer\n x_ = bob.get_obj(x.id_at_location).parent\n assert (\n torch_utils.chain_print(x_, display=False)\n == display_chain.tensor.fixp_local\n )\n\n z = x + x\n z.get().decode_()\n torch.eq(z, torch.FloatTensor([0.2, 0.4, 0.2, 0.4])).all()\n\n x = x.get()\n\n assert (\n torch_utils.chain_print(x, display=False) == display_chain.tensor.fixp_local\n )\n\n x = x.decode()\n\n assert torch_utils.chain_print(x, display=False) == display_chain.tensor.local\n\n def test_var_remote_fix_precision(self):\n x = sy.Variable(torch.FloatTensor([0.1, 0.2, 0.1, 0.2]))\n x = x.send(bob).fix_precision()\n\n assert torch_utils.chain_print(x, display=False) == display_chain.var.pointer\n x_ = bob.get_obj(x.id_at_location).parent\n assert (\n torch_utils.chain_print(x_, display=False) == display_chain.var.fixp_local\n )\n\n z = x + x\n z.get().decode_()\n torch.eq(z, sy.Variable(torch.FloatTensor([0.2, 0.4, 0.2, 0.4]))).all()\n\n x = x.get()\n\n assert torch_utils.chain_print(x, display=False) == display_chain.var.fixp_local\n\n x = x.decode()\n\n assert torch_utils.chain_print(x, display=False) == display_chain.var.local\n\n def test_fix_precision_share(self):\n x = torch.FloatTensor([1.1, 2, 3])\n x = x.fix_precision().share(alice, bob)\n\n assert (\n torch_utils.chain_print(x, display=False)\n == display_chain.tensor.fixp_mpc_gpt\n )\n\n z = x + x\n\n x = x.get()\n\n assert (\n torch_utils.chain_print(x, display=False) == display_chain.tensor.fixp_local\n )\n\n z = z.get().decode()\n assert torch.eq(z, torch.FloatTensor([2.2, 4, 6])).all()\n\n def test_var_fix_precision_share(self):\n x = sy.Variable(torch.FloatTensor([1.1, 2, 3]))\n x = x.fix_precision().share(alice, bob)\n\n assert (\n torch_utils.chain_print(x, display=False) == display_chain.var.fixp_mpc_gpt\n )\n\n z = x + x\n\n x = x.get()\n\n assert torch_utils.chain_print(x, display=False) == display_chain.var.fixp_local\n\n z = z.get().decode()\n assert torch.eq(z, sy.Variable(torch.FloatTensor([2.2, 4, 6]))).all()\n\n def test_remote_fix_precision_share(self):\n x = torch.FloatTensor([1.1, 2, 3])\n x = x.send(bob).fix_precision().share(alice, bob)\n\n assert torch_utils.chain_print(x, display=False) == display_chain.tensor.pointer\n x_ = bob.get_obj(x.id_at_location).parent\n assert (\n torch_utils.chain_print(x_, display=False)\n == display_chain.tensor.fixp_mpc_gpt\n )\n\n z = x + x\n\n x = x.get()\n assert (\n torch_utils.chain_print(x, display=False)\n == display_chain.tensor.fixp_mpc_gpt\n )\n\n x = x.get()\n assert (\n torch_utils.chain_print(x, display=False) == display_chain.tensor.fixp_local\n )\n\n x = x.decode()\n assert torch_utils.chain_print(x, display=False) == display_chain.tensor.local\n\n z = z.get().get().decode()\n assert torch.eq(z, torch.FloatTensor([2.2, 4, 6])).all()\n\n def test_var_remote_fix_precision_share(self):\n x = sy.Variable(torch.FloatTensor([1.1, 2, 3]))\n x = x.send(bob).fix_precision().share(alice, bob)\n\n assert torch_utils.chain_print(x, display=False) == display_chain.var.pointer\n x_ = bob.get_obj(x.id_at_location).parent\n assert (\n torch_utils.chain_print(x_, display=False) == display_chain.var.fixp_mpc_gpt\n )\n\n z = x + x\n\n x = x.get()\n assert (\n torch_utils.chain_print(x, display=False) == display_chain.var.fixp_mpc_gpt\n )\n\n x = x.get()\n assert torch_utils.chain_print(x, display=False) == display_chain.var.fixp_local\n\n x = x.decode()\n assert torch_utils.chain_print(x, display=False) == display_chain.var.local\n\n z = z.get().get().decode()\n assert torch.eq(z, sy.Variable(torch.FloatTensor([2.2, 4, 6]))).all()\n\n def fix_precision_operation(self, l1, l2, var=False, op=\"plus\"):\n if var:\n x = sy.Variable(torch.FloatTensor(l1))\n y = sy.Variable(torch.FloatTensor(l2))\n else:\n x = torch.FloatTensor(l1)\n y = torch.FloatTensor(l2)\n x = x.fix_precision()\n y = y.fix_precision()\n if op == \"plus\":\n z = x + y\n l_res = [e1 + e2 for e1, e2 in zip(l1, l2)]\n elif op == \"mul\":\n z = x * y\n l_res = [e1 * e2 for e1, e2 in zip(l1, l2)]\n elif op == \"matmul\":\n z = x.mm(y)\n l_res = np.dot(np.array(l1), np.array(l2)).tolist()\n else:\n raise ArithmeticError(\"Unknown operator\")\n z = z.decode()\n if var:\n assert torch.eq(z, sy.Variable(torch.FloatTensor(l_res))).all()\n else:\n assert torch.eq(z, torch.FloatTensor(l_res)).all()\n\n def test_addition_fix_precision(self):\n self.fix_precision_operation([3.3], [5.1])\n self.fix_precision_operation([2.5, 3.2], [5.4, -1.1])\n self.fix_precision_operation([-2.8, -3.9], [-1, -1])\n self.fix_precision_operation([-2, 3.3], [-1.9, 1])\n self.fix_precision_operation([-19000, 3.3], [-1.9, 17654])\n\n def test_var_addition_fix_precision(self):\n self.fix_precision_operation([3.3], [5.1], var=True)\n self.fix_precision_operation([2.5, 3.2], [5.4, -1.1], var=True)\n self.fix_precision_operation([-2.8, -3.9], [-1, -1], var=True)\n self.fix_precision_operation([-2, 3.3], [-1.9, 1], var=True)\n self.fix_precision_operation([-19000, 3.3], [-1.9, 17654], var=True)\n\n def test_mult_fix_precision(self):\n self.fix_precision_operation([3.3], [5.1], op=\"mul\")\n self.fix_precision_operation([2.5, 3.2], [5.4, -1.1], op=\"mul\")\n self.fix_precision_operation([-2.8, -3.9], [-1, -1], op=\"mul\")\n self.fix_precision_operation([-2, 3.3], [-1.9, 1], op=\"mul\")\n self.fix_precision_operation([-19000, 3.3], [-1.9, 17654], op=\"mul\")\n\n def test_var_mult_fix_precision(self):\n self.fix_precision_operation([3.3], [5.1], var=True, op=\"mul\")\n self.fix_precision_operation([2.5, 3.2], [5.4, -1.1], var=True, op=\"mul\")\n self.fix_precision_operation([-2.8, -3.9], [-1, -1], var=True, op=\"mul\")\n self.fix_precision_operation([-2, 3.3], [-1.9, 1], var=True, op=\"mul\")\n self.fix_precision_operation([-19000, 3.3], [-1.9, 17654], var=True, op=\"mul\")\n\n def test_matmul_fix_precision(self):\n self.fix_precision_operation(\n [[3.3, 2.1], [1.1, 5.2]], [[1, 2], [3, 4]], op=\"matmul\"\n )\n self.fix_precision_operation(\n [[-3.3, -2.1], [1.1, 5.2]], [[1, 2], [3, -4.8]], op=\"matmul\"\n )\n self.fix_precision_operation(\n [[1.1, -2.1], [3.2, 8.1], [3.0, -7]],\n [[-3.3, -2.1], [1.1, 5.2]],\n op=\"matmul\",\n )\n self.fix_precision_operation(\n [[-40.2, -20.1], [100.7, 51.2]], [[14.1, 21], [30, -41.8]], op=\"matmul\"\n )\n\n def test_var_matmul_fix_precision(self):\n self.fix_precision_operation(\n [[3.3, 2.1], [1.1, 5.2]], [[1, 2], [3, 4]], var=True, op=\"matmul\"\n )\n self.fix_precision_operation(\n [[-3.3, -2.1], [1.1, 5.2]], [[1, 2], [3, -4.8]], var=True, op=\"matmul\"\n )\n self.fix_precision_operation(\n [[1.1, -2.1], [3.2, 8.1], [3.0, -7]],\n [[-3.3, -2.1], [1.1, 5.2]],\n var=True,\n op=\"matmul\",\n )\n self.fix_precision_operation(\n [[-40.2, -20.1], [100.7, 51.2]],\n [[14.1, 21], [30, -41.8]],\n var=True,\n op=\"matmul\",\n )\n\n def remote_fix_precision_operation(self, l1, l2, var=False, op=\"plus\"):\n if var:\n x = sy.Variable(torch.FloatTensor(l1))\n y = sy.Variable(torch.FloatTensor(l2))\n else:\n x = torch.FloatTensor(l1)\n y = torch.FloatTensor(l2)\n x = x.send(bob).fix_precision()\n y = y.send(bob).fix_precision()\n if op == \"plus\":\n z = x + y\n l_res = [e1 + e2 for e1, e2 in zip(l1, l2)]\n elif op == \"mul\":\n z = x * y\n l_res = [e1 * e2 for e1, e2 in zip(l1, l2)]\n elif op == \"matmul\":\n z = x.mm(y)\n l_res = np.dot(np.array(l1), np.array(l2)).tolist()\n else:\n raise ArithmeticError(\"Unknown operator\")\n z = z.get().decode()\n if var:\n assert torch.eq(z, sy.Variable(torch.FloatTensor(l_res))).all()\n else:\n assert torch.eq(z, torch.FloatTensor(l_res)).all()\n\n def test_addition_remote_fix_precision(self):\n self.remote_fix_precision_operation([3.3], [5.1])\n self.remote_fix_precision_operation([2.5, 3.2], [5.4, -1.1])\n self.remote_fix_precision_operation([-2.8, -3.9], [-1, -1])\n self.remote_fix_precision_operation([-2, 3.3], [-1.9, 1])\n self.remote_fix_precision_operation([-19000, 3.3], [-1.9, 17654])\n\n def test_var_addition_remote_fix_precision(self):\n self.remote_fix_precision_operation([3.3], [5.1], var=True)\n self.remote_fix_precision_operation([2.5, 3.2], [5.4, -1.1], var=True)\n self.remote_fix_precision_operation([-2.8, -3.9], [-1, -1], var=True)\n self.remote_fix_precision_operation([-2, 3.3], [-1.9, 1], var=True)\n self.remote_fix_precision_operation([-19000, 3.3], [-1.9, 17654], var=True)\n\n def test_mult_remote_fix_precision(self):\n self.remote_fix_precision_operation([3.3], [5.1], op=\"mul\")\n self.remote_fix_precision_operation([2.5, 3.2], [5.4, -1.1], op=\"mul\")\n self.remote_fix_precision_operation([-2.8, -3.9], [-1, -1], op=\"mul\")\n self.remote_fix_precision_operation([-2, 3.3], [-1.9, 1], op=\"mul\")\n self.remote_fix_precision_operation([-19000, 3.3], [-1.9, 17654], op=\"mul\")\n\n def test_var_mult_remote_fix_precision(self):\n self.remote_fix_precision_operation([3.3], [5.1], var=True, op=\"mul\")\n self.remote_fix_precision_operation([2.5, 3.2], [5.4, -1.1], var=True, op=\"mul\")\n self.remote_fix_precision_operation([-2.8, -3.9], [-1, -1], var=True, op=\"mul\")\n self.remote_fix_precision_operation([-2, 3.3], [-1.9, 1], var=True, op=\"mul\")\n self.remote_fix_precision_operation(\n [-19000, 3.3], [-1.9, 17654], var=True, op=\"mul\"\n )\n\n def test_matmul_remote_fix_precision(self):\n self.remote_fix_precision_operation(\n [[3.3, 2.1], [1.1, 5.2]], [[1, 2], [3, 4]], op=\"matmul\"\n )\n self.remote_fix_precision_operation(\n [[-3.3, -2.1], [1.1, 5.2]], [[1, 2], [3, -4.8]], op=\"matmul\"\n )\n self.remote_fix_precision_operation(\n [[1.1, -2.1], [3.2, 8.1], [3.0, -7]],\n [[-3.3, -2.1], [1.1, 5.2]],\n op=\"matmul\",\n )\n self.remote_fix_precision_operation(\n [[-40.2, -20.1], [100.7, 51.2]], [[14.1, 21], [30, -41.8]], op=\"matmul\"\n )\n\n def test_var_matmul_remote_fix_precision(self):\n self.remote_fix_precision_operation(\n [[3.3, 2.1], [1.1, 5.2]], [[1, 2], [3, 4]], var=True, op=\"matmul\"\n )\n self.remote_fix_precision_operation(\n [[-3.3, -2.1], [1.1, 5.2]], [[1, 2], [3, -4.8]], var=True, op=\"matmul\"\n )\n self.remote_fix_precision_operation(\n [[1.1, -2.1], [3.2, 8.1], [3.0, -7]],\n [[-3.3, -2.1], [1.1, 5.2]],\n var=True,\n op=\"matmul\",\n )\n self.remote_fix_precision_operation(\n [[-40.2, -20.1], [100.7, 51.2]],\n [[14.1, 21], [30, -41.8]],\n var=True,\n op=\"matmul\",\n )\n\n def remote_fix_precision_share_operation(self, l1, l2, var=False, op=\"plus\"):\n if var:\n x = sy.Variable(torch.FloatTensor(l1))\n y = sy.Variable(torch.FloatTensor(l2))\n else:\n x = torch.FloatTensor(l1)\n y = torch.FloatTensor(l2)\n x = x.send(bob).fix_precision().share(alice, bob)\n y = y.send(bob).fix_precision().share(alice, bob)\n if op == \"plus\":\n z = x + y\n l_res = [e1 + e2 for e1, e2 in zip(l1, l2)]\n elif op == \"mul\":\n z = x * y\n l_res = [e1 * e2 for e1, e2 in zip(l1, l2)]\n elif op == \"matmul\":\n z = x.mm(y)\n l_res = np.dot(np.array(l1), np.array(l2)).tolist()\n else:\n raise ArithmeticError(\"Unknown operator\")\n z = z.get().get().decode()\n if var:\n assert torch.eq(z, sy.Variable(torch.FloatTensor(l_res))).all()\n else:\n assert torch.eq(z, torch.FloatTensor(l_res)).all()\n\n def test_addition_remote_fix_precision_share(self):\n self.remote_fix_precision_share_operation([3.3], [5.1])\n self.remote_fix_precision_share_operation([2.5, 3.2], [5.4, -1.1])\n self.remote_fix_precision_share_operation([-2.8, -3.9], [-1, -1])\n self.remote_fix_precision_share_operation([-2, 3.3], [-1.9, 1])\n self.remote_fix_precision_share_operation([-190, 3.3], [-1.9, 174])\n\n def test_var_addition_remote_fix_precision_share(self):\n self.remote_fix_precision_share_operation([3.3], [5.1], var=True)\n self.remote_fix_precision_share_operation([2.5, 3.2], [5.4, -1.1], var=True)\n self.remote_fix_precision_share_operation([-2.8, -3.9], [-1, -1], var=True)\n self.remote_fix_precision_share_operation([-2, 3.3], [-1.9, 1], var=True)\n self.remote_fix_precision_share_operation([-190, 3.3], [-1.9, 174], var=True)\n\n def test_mult_remote_fix_precision_share(self):\n self.remote_fix_precision_share_operation([3.3], [5.1], op=\"mul\")\n self.remote_fix_precision_share_operation([2.5, 3.2], [5.4, -1.1], op=\"mul\")\n self.remote_fix_precision_share_operation([-2.8, -3.9], [-1, -1], op=\"mul\")\n self.remote_fix_precision_share_operation([-2, 3.3], [-1.9, 1], op=\"mul\")\n\n # available precision too small for this at the moment\n # self.remote_fix_precision_share_operation([-190, 3.3], [-1.9, 174], op='mul')\n\n def test_var_mult_remote_fix_precision_share(self):\n self.remote_fix_precision_share_operation([3.3], [5.1], var=True, op=\"mul\")\n self.remote_fix_precision_share_operation(\n [2.5, 3.2], [5.4, -1.1], var=True, op=\"mul\"\n )\n self.remote_fix_precision_share_operation(\n [-2.8, -3.9], [-1, -1], var=True, op=\"mul\"\n )\n self.remote_fix_precision_share_operation(\n [-2, 3.3], [-1.9, 1], var=True, op=\"mul\"\n )\n\n # available precision too small for this at the moment\n # self.remote_fix_precision_share_operation([-190, 3.3], [-1.9, 174], var=True, op='mul')\n\n def test_matmul_remote_fix_precision_share(self):\n self.remote_fix_precision_share_operation(\n [[3.3, 2.1], [1.1, 5.2]], [[1, 2], [3, 4]], op=\"matmul\"\n )\n self.remote_fix_precision_share_operation(\n [[-3.3, -2.1], [1.1, 5.2]], [[1, 2], [3, -4.8]], op=\"matmul\"\n )\n self.remote_fix_precision_share_operation(\n [[1.1, -2.1], [3.2, 8.1], [3.0, -7]],\n [[-3.3, -2.1], [1.1, 5.2]],\n op=\"matmul\",\n )\n\n # available precision too small for this at the moment\n\n # self.remote_fix_precision_share_operation([[-40.2, -20.1],\n # [10.7, 21.2]],\n # [[14.1, 21],\n # [10, -11.8]], op='matmul')\n\n def test_var_matmul_remote_fix_precision_share(self):\n self.remote_fix_precision_share_operation(\n [[3.3, 2.1], [1.1, 5.2]], [[1, 2], [3, 4]], var=True, op=\"matmul\"\n )\n # self.remote_fix_precision_share_operation([[-3.3, -2.1],\n # [1.1, 5.2]],\n # [[1, 2],\n # [3, -4.8]], var=True, op='matmul')\n # self.remote_fix_precision_share_operation([[1.1, -2.1],\n # [3.2, 8.1],\n # [3.0, -7]],\n # [[-3.3, -2.1],\n # [1.1, 5.2]], var=True, op='matmul')\n\n # available precision too small for this at the moment\n\n # self.remote_fix_precision_share_operation([[-40.2, -20.1],\n # [10.7, 21.2]],\n # [[14.1, 21],\n # [10, -11.8]], op='matmul')\n\n\nclass TestGPCTensor(TestCase):\n def test_gpc_add(self):\n x = torch.LongTensor([1, 2, 3, 4, 5])\n y = torch.LongTensor([1, 2, 3, 4, 5])\n\n x.send(bob)\n y.send(alice)\n\n x_pointer_tensor_dict = {alice: y.child, bob: x.child}\n x_gp = _GeneralizedPointerTensor(\n x_pointer_tensor_dict, torch_type=\"syft.LongTensor\"\n ).wrap(True)\n\n y = x_gp + x_gp\n\n results = y.get()\n\n assert (results[0] == (x.get() * 2)).all()\n\n def test_gpc_unwrapped_add(self):\n x = torch.LongTensor([1, 2, 3, 4, 5])\n y = torch.LongTensor([1, 2, 3, 4, 5])\n\n x.send(bob)\n y.send(alice)\n\n x_pointer_tensor_dict = {alice: y.child, bob: x.child}\n x_gp = _GeneralizedPointerTensor(\n x_pointer_tensor_dict, torch_type=\"syft.LongTensor\"\n ).wrap(True)\n\n y = x_gp.child + x_gp.child\n\n results = y.get()\n\n assert (results[0] == (x.get() * 2)).all()\n\n def test_gpc_workers(self):\n x = torch.LongTensor([1, 2, 3, 4, 5])\n y = torch.LongTensor([1, 2, 3, 4, 5])\n\n x.send(bob)\n y.send(alice)\n\n x_pointer_tensor_dict = {alice: y.child, bob: x.child}\n x_gp = _GeneralizedPointerTensor(x_pointer_tensor_dict)\n\n results = x_gp.workers()\n\n assert results == [k.id for k in x_pointer_tensor_dict.keys()]\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] | [
[
"torch.stack",
"torch.addcmul",
"torch.eq",
"torch.ByteTensor",
"torch.addmm",
"torch.nn.Conv2d",
"torch.native_eq",
"torch.cross",
"torch.max",
"torch.cat",
"torch.add",
"torch.ones",
"torch.ge",
"torch.manual_seed",
"torch.dist",
"torch.IntTensor",
"numpy.array",
"torch.clamp",
"torch.FloatTensor",
"torch.dot",
"torch.nn.Linear",
"torch.nn.functional.conv2d",
"torch.equal",
"torch.nn.functional.relu",
"torch.zeros",
"torch.LongTensor",
"torch.matmul"
]
] |
ARudiuk/mne-python | [
"63feb683cd1f8ddd598a78d12c8ef522f9ca2d78"
] | [
"mne/label.py"
] | [
"# Authors: Alexandre Gramfort <[email protected]>\n# Martin Luessi <[email protected]>\n# Denis Engemann <[email protected]>\n#\n# License: BSD (3-clause)\n\nfrom collections import defaultdict\nfrom colorsys import hsv_to_rgb, rgb_to_hsv\nfrom os import path as op\nimport os\nimport copy as cp\nimport re\n\nimport numpy as np\nfrom scipy import linalg, sparse\n\nfrom .fixes import digitize, in1d\nfrom .utils import (get_subjects_dir, _check_subject, logger, verbose, warn,\n _check_copy_dep)\nfrom .source_estimate import (morph_data, SourceEstimate,\n spatial_src_connectivity)\nfrom .source_space import add_source_space_distances\nfrom .surface import read_surface, fast_cross_3d, mesh_edges, mesh_dist\nfrom .source_space import SourceSpaces\nfrom .parallel import parallel_func, check_n_jobs\nfrom .stats.cluster_level import _find_clusters, _get_components\nfrom .externals.six import b, string_types\nfrom .externals.six.moves import zip, xrange\n\n\ndef _blend_colors(color_1, color_2):\n \"\"\"Blend two colors in HSV space\n\n Parameters\n ----------\n color_1, color_2 : None | tuple\n RGBA tuples with values between 0 and 1. None if no color is available.\n If both colors are None, the output is None. If only one is None, the\n output is the other color.\n\n Returns\n -------\n color : None | tuple\n RGBA tuple of the combined color. Saturation, value and alpha are\n averaged, whereas the new hue is determined as angle half way between\n the two input colors' hues.\n \"\"\"\n if color_1 is None and color_2 is None:\n return None\n elif color_1 is None:\n return color_2\n elif color_2 is None:\n return color_1\n\n r_1, g_1, b_1, a_1 = color_1\n h_1, s_1, v_1 = rgb_to_hsv(r_1, g_1, b_1)\n r_2, g_2, b_2, a_2 = color_2\n h_2, s_2, v_2 = rgb_to_hsv(r_2, g_2, b_2)\n hue_diff = abs(h_1 - h_2)\n if hue_diff < 0.5:\n h = min(h_1, h_2) + hue_diff / 2.\n else:\n h = max(h_1, h_2) + (1. - hue_diff) / 2.\n h %= 1.\n s = (s_1 + s_2) / 2.\n v = (v_1 + v_2) / 2.\n r, g, b = hsv_to_rgb(h, s, v)\n a = (a_1 + a_2) / 2.\n color = (r, g, b, a)\n return color\n\n\ndef _split_colors(color, n):\n \"\"\"Create n colors in HSV space that occupy a gradient in value\n\n Parameters\n ----------\n color : tuple\n RGBA tuple with values between 0 and 1.\n n : int >= 2\n Number of colors on the gradient.\n\n Returns\n -------\n colors : tuple of tuples, len = n\n N RGBA tuples that occupy a gradient in value (low to high) but share\n saturation and hue with the input color.\n \"\"\"\n r, g, b, a = color\n h, s, v = rgb_to_hsv(r, g, b)\n gradient_range = np.sqrt(n / 10.)\n if v > 0.5:\n v_max = min(0.95, v + gradient_range / 2)\n v_min = max(0.05, v_max - gradient_range)\n else:\n v_min = max(0.05, v - gradient_range / 2)\n v_max = min(0.95, v_min + gradient_range)\n\n hsv_colors = ((h, s, v_) for v_ in np.linspace(v_min, v_max, n))\n rgb_colors = (hsv_to_rgb(h_, s_, v_) for h_, s_, v_ in hsv_colors)\n rgba_colors = ((r_, g_, b_, a,) for r_, g_, b_ in rgb_colors)\n return tuple(rgba_colors)\n\n\ndef _n_colors(n, bytes_=False, cmap='hsv'):\n \"\"\"Produce a list of n unique RGBA color tuples based on a colormap\n\n Parameters\n ----------\n n : int\n Number of colors.\n bytes : bool\n Return colors as integers values between 0 and 255 (instead of floats\n between 0 and 1).\n cmap : str\n Which colormap to use.\n\n Returns\n -------\n colors : array, shape (n, 4)\n RGBA color values.\n \"\"\"\n n_max = 2 ** 10\n if n > n_max:\n raise NotImplementedError(\"Can't produce more than %i unique \"\n \"colors\" % n_max)\n\n from matplotlib.cm import get_cmap\n cm = get_cmap(cmap, n_max)\n pos = np.linspace(0, 1, n, False)\n colors = cm(pos, bytes=bytes_)\n if bytes_:\n # make sure colors are unique\n for ii, c in enumerate(colors):\n if np.any(np.all(colors[:ii] == c, 1)):\n raise RuntimeError('Could not get %d unique colors from %s '\n 'colormap. Try using a different colormap.'\n % (n, cmap))\n return colors\n\n\nclass Label(object):\n \"\"\"A FreeSurfer/MNE label with vertices restricted to one hemisphere\n\n Labels can be combined with the ``+`` operator:\n\n * Duplicate vertices are removed.\n * If duplicate vertices have conflicting position values, an error\n is raised.\n * Values of duplicate vertices are summed.\n\n\n Parameters\n ----------\n vertices : array (length N)\n vertex indices (0 based).\n pos : array (N by 3) | None\n locations in meters. If None, then zeros are used.\n values : array (length N) | None\n values at the vertices. If None, then ones are used.\n hemi : 'lh' | 'rh'\n Hemisphere to which the label applies.\n comment : str\n Kept as information but not used by the object itself.\n name : str\n Kept as information but not used by the object itself.\n filename : str\n Kept as information but not used by the object itself.\n subject : str | None\n Name of the subject the label is from.\n color : None | matplotlib color\n Default label color and alpha (e.g., ``(1., 0., 0., 1.)`` for red).\n verbose : bool, str, int, or None\n If not None, override default verbose level (see mne.verbose).\n\n Attributes\n ----------\n color : None | tuple\n Default label color, represented as RGBA tuple with values between 0\n and 1.\n comment : str\n Comment from the first line of the label file.\n hemi : 'lh' | 'rh'\n Hemisphere.\n name : None | str\n A name for the label. It is OK to change that attribute manually.\n pos : array, shape = (n_pos, 3)\n Locations in meters.\n subject : str | None\n Subject name. It is best practice to set this to the proper\n value on initialization, but it can also be set manually.\n values : array, len = n_pos\n Values at the vertices.\n verbose : bool, str, int, or None\n See above.\n vertices : array, len = n_pos\n Vertex indices (0 based)\n \"\"\"\n @verbose\n def __init__(self, vertices, pos=None, values=None, hemi=None, comment=\"\",\n name=None, filename=None, subject=None, color=None,\n verbose=None):\n # check parameters\n if not isinstance(hemi, string_types):\n raise ValueError('hemi must be a string, not %s' % type(hemi))\n vertices = np.asarray(vertices)\n if np.any(np.diff(vertices.astype(int)) <= 0):\n raise ValueError('Vertices must be ordered in increasing order.')\n\n if color is not None:\n from matplotlib.colors import colorConverter\n color = colorConverter.to_rgba(color)\n\n if values is None:\n values = np.ones(len(vertices))\n else:\n values = np.asarray(values)\n\n if pos is None:\n pos = np.zeros((len(vertices), 3))\n else:\n pos = np.asarray(pos)\n\n if not (len(vertices) == len(values) == len(pos)):\n raise ValueError(\"vertices, values and pos need to have same \"\n \"length (number of vertices)\")\n\n # name\n if name is None and filename is not None:\n name = op.basename(filename[:-6])\n\n self.vertices = vertices\n self.pos = pos\n self.values = values\n self.hemi = hemi\n self.comment = comment\n self.verbose = verbose\n self.subject = _check_subject(None, subject, False)\n self.color = color\n self.name = name\n self.filename = filename\n\n def __setstate__(self, state):\n self.vertices = state['vertices']\n self.pos = state['pos']\n self.values = state['values']\n self.hemi = state['hemi']\n self.comment = state['comment']\n self.verbose = state['verbose']\n self.subject = state.get('subject', None)\n self.color = state.get('color', None)\n self.name = state['name']\n self.filename = state['filename']\n\n def __getstate__(self):\n out = dict(vertices=self.vertices,\n pos=self.pos,\n values=self.values,\n hemi=self.hemi,\n comment=self.comment,\n verbose=self.verbose,\n subject=self.subject,\n color=self.color,\n name=self.name,\n filename=self.filename)\n return out\n\n def __repr__(self):\n name = 'unknown, ' if self.subject is None else self.subject + ', '\n name += repr(self.name) if self.name is not None else \"unnamed\"\n n_vert = len(self)\n return \"<Label | %s, %s : %i vertices>\" % (name, self.hemi, n_vert)\n\n def __len__(self):\n return len(self.vertices)\n\n def __add__(self, other):\n if isinstance(other, BiHemiLabel):\n return other + self\n elif isinstance(other, Label):\n if self.subject != other.subject:\n raise ValueError('Label subject parameters must match, got '\n '\"%s\" and \"%s\". Consider setting the '\n 'subject parameter on initialization, or '\n 'setting label.subject manually before '\n 'combining labels.' % (self.subject,\n other.subject))\n if self.hemi != other.hemi:\n name = '%s + %s' % (self.name, other.name)\n if self.hemi == 'lh':\n lh, rh = self.copy(), other.copy()\n else:\n lh, rh = other.copy(), self.copy()\n color = _blend_colors(self.color, other.color)\n return BiHemiLabel(lh, rh, name, color)\n else:\n raise TypeError(\"Need: Label or BiHemiLabel. Got: %r\" % other)\n\n # check for overlap\n duplicates = np.intersect1d(self.vertices, other.vertices)\n n_dup = len(duplicates)\n if n_dup:\n self_dup = [np.where(self.vertices == d)[0][0]\n for d in duplicates]\n other_dup = [np.where(other.vertices == d)[0][0]\n for d in duplicates]\n if not np.all(self.pos[self_dup] == other.pos[other_dup]):\n err = (\"Labels %r and %r: vertices overlap but differ in \"\n \"position values\" % (self.name, other.name))\n raise ValueError(err)\n\n isnew = np.array([v not in duplicates for v in other.vertices])\n\n vertices = np.hstack((self.vertices, other.vertices[isnew]))\n pos = np.vstack((self.pos, other.pos[isnew]))\n\n # find position of other's vertices in new array\n tgt_idx = [np.where(vertices == v)[0][0] for v in other.vertices]\n n_self = len(self.values)\n n_other = len(other.values)\n new_len = n_self + n_other - n_dup\n values = np.zeros(new_len, dtype=self.values.dtype)\n values[:n_self] += self.values\n values[tgt_idx] += other.values\n else:\n vertices = np.hstack((self.vertices, other.vertices))\n pos = np.vstack((self.pos, other.pos))\n values = np.hstack((self.values, other.values))\n\n indcs = np.argsort(vertices)\n vertices, pos, values = vertices[indcs], pos[indcs, :], values[indcs]\n\n comment = \"%s + %s\" % (self.comment, other.comment)\n\n name0 = self.name if self.name else 'unnamed'\n name1 = other.name if other.name else 'unnamed'\n name = \"%s + %s\" % (name0, name1)\n\n color = _blend_colors(self.color, other.color)\n verbose = self.verbose or other.verbose\n\n label = Label(vertices, pos, values, self.hemi, comment, name, None,\n self.subject, color, verbose)\n return label\n\n def __sub__(self, other):\n if isinstance(other, BiHemiLabel):\n if self.hemi == 'lh':\n return self - other.lh\n else:\n return self - other.rh\n elif isinstance(other, Label):\n if self.subject != other.subject:\n raise ValueError('Label subject parameters must match, got '\n '\"%s\" and \"%s\". Consider setting the '\n 'subject parameter on initialization, or '\n 'setting label.subject manually before '\n 'combining labels.' % (self.subject,\n other.subject))\n else:\n raise TypeError(\"Need: Label or BiHemiLabel. Got: %r\" % other)\n\n if self.hemi == other.hemi:\n keep = in1d(self.vertices, other.vertices, True, invert=True)\n else:\n keep = np.arange(len(self.vertices))\n\n name = \"%s - %s\" % (self.name or 'unnamed', other.name or 'unnamed')\n return Label(self.vertices[keep], self.pos[keep], self.values[keep],\n self.hemi, self.comment, name, None, self.subject,\n self.color, self.verbose)\n\n def save(self, filename):\n \"\"\"Write to disk as FreeSurfer \\*.label file\n\n Parameters\n ----------\n filename : string\n Path to label file to produce.\n\n Notes\n -----\n Note that due to file specification limitations, the Label's subject\n and color attributes are not saved to disk.\n \"\"\"\n write_label(filename, self)\n\n def copy(self):\n \"\"\"Copy the label instance.\n\n Returns\n -------\n label : instance of Label\n The copied label.\n \"\"\"\n return cp.deepcopy(self)\n\n def fill(self, src, name=None):\n \"\"\"Fill the surface between sources for a label defined in source space\n\n Parameters\n ----------\n src : SourceSpaces\n Source space in which the label was defined. If a source space is\n provided, the label is expanded to fill in surface vertices that\n lie between the vertices included in the source space. For the\n added vertices, ``pos`` is filled in with positions from the\n source space, and ``values`` is filled in from the closest source\n space vertex.\n name : None | str\n Name for the new Label (default is self.name).\n\n Returns\n -------\n label : Label\n The label covering the same vertices in source space but also\n including intermediate surface vertices.\n \"\"\"\n # find source space patch info\n if self.hemi == 'lh':\n hemi_src = src[0]\n elif self.hemi == 'rh':\n hemi_src = src[1]\n\n if not np.all(in1d(self.vertices, hemi_src['vertno'])):\n msg = \"Source space does not contain all of the label's vertices\"\n raise ValueError(msg)\n\n nearest = hemi_src['nearest']\n if nearest is None:\n warn(\"Computing patch info for source space, this can take \"\n \"a while. In order to avoid this in the future, run \"\n \"mne.add_source_space_distances() on the source space \"\n \"and save it.\")\n add_source_space_distances(src)\n nearest = hemi_src['nearest']\n\n # find new vertices\n include = in1d(nearest, self.vertices, False)\n vertices = np.nonzero(include)[0]\n\n # values\n nearest_in_label = digitize(nearest[vertices], self.vertices, True)\n values = self.values[nearest_in_label]\n # pos\n pos = hemi_src['rr'][vertices]\n\n if name is None:\n name = self.name\n label = Label(vertices, pos, values, self.hemi, self.comment, name,\n None, self.subject, self.color)\n return label\n\n @verbose\n def smooth(self, subject=None, smooth=2, grade=None,\n subjects_dir=None, n_jobs=1, copy=None, verbose=None):\n \"\"\"Smooth the label\n\n Useful for filling in labels made in a\n decimated source space for display.\n\n Parameters\n ----------\n subject : str | None\n The name of the subject used. If None, the value will be\n taken from self.subject.\n smooth : int\n Number of iterations for the smoothing of the surface data.\n Cannot be None here since not all vertices are used. For a\n grade of 5 (e.g., fsaverage), a smoothing of 2 will fill a\n label.\n grade : int, list (of two arrays), array, or None\n Resolution of the icosahedral mesh (typically 5). If None, all\n vertices will be used (potentially filling the surface). If a list,\n values will be morphed to the set of vertices specified in grade[0]\n and grade[1], assuming that these are vertices for the left and\n right hemispheres. Note that specifying the vertices (e.g.,\n grade=[np.arange(10242), np.arange(10242)] for fsaverage on a\n standard grade 5 source space) can be substantially faster than\n computing vertex locations. If one array is used, it is assumed\n that all vertices belong to the hemisphere of the label. To create\n a label filling the surface, use None.\n subjects_dir : string, or None\n Path to SUBJECTS_DIR if it is not set in the environment.\n n_jobs : int\n Number of jobs to run in parallel\n copy : bool\n This parameter has been deprecated and will be removed in 0.14.\n Use inst.copy() instead.\n Whether to return a new instance or modify in place.\n verbose : bool, str, int, or None\n If not None, override default verbose level (see mne.verbose).\n Defaults to self.verbose.\n\n Returns\n -------\n label : instance of Label\n The smoothed label.\n\n Notes\n -----\n This function will set label.pos to be all zeros. If the positions\n on the new surface are required, consider using mne.read_surface\n with label.vertices.\n \"\"\"\n subject = _check_subject(self.subject, subject)\n return self.morph(subject, subject, smooth, grade, subjects_dir,\n n_jobs, copy=copy)\n\n @verbose\n def morph(self, subject_from=None, subject_to=None, smooth=5, grade=None,\n subjects_dir=None, n_jobs=1, copy=None, verbose=None):\n \"\"\"Morph the label\n\n Useful for transforming a label from one subject to another.\n\n Parameters\n ----------\n subject_from : str | None\n The name of the subject of the current label. If None, the\n initial subject will be taken from self.subject.\n subject_to : str\n The name of the subject to morph the label to. This will\n be put in label.subject of the output label file.\n smooth : int\n Number of iterations for the smoothing of the surface data.\n Cannot be None here since not all vertices are used.\n grade : int, list (of two arrays), array, or None\n Resolution of the icosahedral mesh (typically 5). If None, all\n vertices will be used (potentially filling the surface). If a list,\n values will be morphed to the set of vertices specified in grade[0]\n and grade[1], assuming that these are vertices for the left and\n right hemispheres. Note that specifying the vertices (e.g.,\n ``grade=[np.arange(10242), np.arange(10242)]`` for fsaverage on a\n standard grade 5 source space) can be substantially faster than\n computing vertex locations. If one array is used, it is assumed\n that all vertices belong to the hemisphere of the label. To create\n a label filling the surface, use None.\n subjects_dir : string, or None\n Path to SUBJECTS_DIR if it is not set in the environment.\n n_jobs : int\n Number of jobs to run in parallel.\n copy : bool\n This parameter has been deprecated and will be removed in 0.14.\n Use inst.copy() instead.\n Whether to return a new instance or modify in place.\n verbose : bool, str, int, or None\n If not None, override default verbose level (see mne.verbose).\n\n Returns\n -------\n label : instance of Label\n The morphed label.\n\n Notes\n -----\n This function will set label.pos to be all zeros. If the positions\n on the new surface are required, consider using `mne.read_surface`\n with `label.vertices`.\n \"\"\"\n subject_from = _check_subject(self.subject, subject_from)\n if not isinstance(subject_to, string_types):\n raise TypeError('\"subject_to\" must be entered as a string')\n if not isinstance(smooth, int):\n raise TypeError('smooth must be an integer')\n if np.all(self.values == 0):\n raise ValueError('Morphing label with all zero values will result '\n 'in the label having no vertices. Consider using '\n 'something like label.values.fill(1.0).')\n if(isinstance(grade, np.ndarray)):\n if self.hemi == 'lh':\n grade = [grade, np.array([], int)]\n else:\n grade = [np.array([], int), grade]\n if self.hemi == 'lh':\n vertices = [self.vertices, np.array([], int)]\n else:\n vertices = [np.array([], int), self.vertices]\n data = self.values[:, np.newaxis]\n stc = SourceEstimate(data, vertices, tmin=1, tstep=1,\n subject=subject_from)\n stc = morph_data(subject_from, subject_to, stc, grade=grade,\n smooth=smooth, subjects_dir=subjects_dir,\n warn=False, n_jobs=n_jobs)\n inds = np.nonzero(stc.data)[0]\n label = _check_copy_dep(self, copy)\n label.values = stc.data[inds, :].ravel()\n label.pos = np.zeros((len(inds), 3))\n if label.hemi == 'lh':\n label.vertices = stc.vertices[0][inds]\n else:\n label.vertices = stc.vertices[1][inds]\n label.subject = subject_to\n return label\n\n def split(self, parts=2, subject=None, subjects_dir=None,\n freesurfer=False):\n \"\"\"Split the Label into two or more parts\n\n Parameters\n ----------\n parts : int >= 2 | tuple of str | str\n Number of labels to create (default is 2), or tuple of strings\n specifying label names for new labels (from posterior to anterior),\n or 'contiguous' to split the label into connected components.\n If a number or 'contiguous' is specified, names of the new labels\n will be the input label's name with div1, div2 etc. appended.\n subject : None | str\n Subject which this label belongs to (needed to locate surface file;\n should only be specified if it is not specified in the label).\n subjects_dir : None | str\n Path to SUBJECTS_DIR if it is not set in the environment.\n freesurfer : bool\n By default (``False``) ``split_label`` uses an algorithm that is\n slightly optimized for performance and numerical precision. Set\n ``freesurfer`` to ``True`` in order to replicate label splits from\n FreeSurfer's ``mris_divide_parcellation``.\n\n Returns\n -------\n labels : list of Label (len = n_parts)\n The labels, starting from the lowest to the highest end of the\n projection axis.\n\n Notes\n -----\n If using 'contiguous' split, you must ensure that the label being split\n uses the same triangular resolution as the surface mesh files in\n ``subjects_dir`` Also, some small fringe labels may be returned that\n are close (but not connected) to the large components.\n\n The spatial split finds the label's principal eigen-axis on the\n spherical surface, projects all label vertex coordinates onto this\n axis, and divides them at regular spatial intervals.\n \"\"\"\n if isinstance(parts, string_types) and parts == 'contiguous':\n return _split_label_contig(self, subject, subjects_dir)\n elif isinstance(parts, (tuple, int)):\n return split_label(self, parts, subject, subjects_dir, freesurfer)\n else:\n raise ValueError(\"Need integer, tuple of strings, or string \"\n \"('contiguous'). Got %s)\" % type(parts))\n\n def get_vertices_used(self, vertices=None):\n \"\"\"Get the source space's vertices inside the label\n\n Parameters\n ----------\n vertices : ndarray of int, shape (n_vertices,) | None\n The set of vertices to compare the label to. If None, equals to\n ``np.arange(10242)``. Defaults to None.\n\n Returns\n -------\n label_verts : ndarray of in, shape (n_label_vertices,)\n The vertices of the label corresponding used by the data.\n \"\"\"\n if vertices is None:\n vertices = np.arange(10242)\n\n label_verts = vertices[in1d(vertices, self.vertices)]\n return label_verts\n\n def get_tris(self, tris, vertices=None):\n \"\"\"Get the source space's triangles inside the label\n\n Parameters\n ----------\n tris : ndarray of int, shape (n_tris, 3)\n The set of triangles corresponding to the vertices in a\n source space.\n vertices : ndarray of int, shape (n_vertices,) | None\n The set of vertices to compare the label to. If None, equals to\n ``np.arange(10242)``. Defaults to None.\n\n Returns\n -------\n label_tris : ndarray of int, shape (n_tris, 3)\n The subset of tris used by the label\n \"\"\"\n vertices_ = self.get_vertices_used(vertices)\n selection = np.all(in1d(tris, vertices_).reshape(tris.shape),\n axis=1)\n label_tris = tris[selection]\n if len(np.unique(label_tris)) < len(vertices_):\n logger.info('Surprising label structure. Trying to repair '\n 'triangles.')\n dropped_vertices = np.setdiff1d(vertices_, label_tris)\n n_dropped = len(dropped_vertices)\n assert n_dropped == (len(vertices_) - len(np.unique(label_tris)))\n\n # put missing vertices as extra zero-length triangles\n add_tris = (dropped_vertices +\n np.zeros((len(dropped_vertices), 3), dtype=int).T)\n\n label_tris = np.r_[label_tris, add_tris.T]\n assert len(np.unique(label_tris)) == len(vertices_)\n\n return label_tris\n\n\nclass BiHemiLabel(object):\n \"\"\"A freesurfer/MNE label with vertices in both hemispheres\n\n Parameters\n ----------\n lh : Label\n Label for the left hemisphere.\n rh : Label\n Label for the right hemisphere.\n name : None | str\n name for the label\n color : None | matplotlib color\n Label color and alpha (e.g., ``(1., 0., 0., 1.)`` for red).\n Note that due to file specification limitations, the color isn't saved\n to or loaded from files written to disk.\n\n Attributes\n ----------\n lh : Label\n Label for the left hemisphere.\n rh : Label\n Label for the right hemisphere.\n name : None | str\n A name for the label. It is OK to change that attribute manually.\n subject : str | None\n Subject the label is from.\n\n \"\"\"\n\n def __init__(self, lh, rh, name=None, color=None):\n if lh.subject != rh.subject:\n raise ValueError('lh.subject (%s) and rh.subject (%s) must '\n 'agree' % (lh.subject, rh.subject))\n self.lh = lh\n self.rh = rh\n self.name = name\n self.subject = lh.subject\n self.color = color\n self.hemi = 'both'\n\n def __repr__(self):\n temp = \"<BiHemiLabel | %s, lh : %i vertices, rh : %i vertices>\"\n name = 'unknown, ' if self.subject is None else self.subject + ', '\n name += repr(self.name) if self.name is not None else \"unnamed\"\n return temp % (name, len(self.lh), len(self.rh))\n\n def __len__(self):\n return len(self.lh) + len(self.rh)\n\n def __add__(self, other):\n if isinstance(other, Label):\n if other.hemi == 'lh':\n lh = self.lh + other\n rh = self.rh\n else:\n lh = self.lh\n rh = self.rh + other\n elif isinstance(other, BiHemiLabel):\n lh = self.lh + other.lh\n rh = self.rh + other.rh\n else:\n raise TypeError(\"Need: Label or BiHemiLabel. Got: %r\" % other)\n\n name = '%s + %s' % (self.name, other.name)\n color = _blend_colors(self.color, other.color)\n return BiHemiLabel(lh, rh, name, color)\n\n def __sub__(self, other):\n if isinstance(other, Label):\n if other.hemi == 'lh':\n lh = self.lh - other\n rh = self.rh\n else:\n rh = self.rh - other\n lh = self.lh\n elif isinstance(other, BiHemiLabel):\n lh = self.lh - other.lh\n rh = self.rh - other.rh\n else:\n raise TypeError(\"Need: Label or BiHemiLabel. Got: %r\" % other)\n\n if len(lh.vertices) == 0:\n return rh\n elif len(rh.vertices) == 0:\n return lh\n else:\n name = '%s - %s' % (self.name, other.name)\n return BiHemiLabel(lh, rh, name, self.color)\n\n\ndef read_label(filename, subject=None, color=None):\n \"\"\"Read FreeSurfer Label file\n\n Parameters\n ----------\n filename : string\n Path to label file.\n subject : str | None\n Name of the subject the data are defined for.\n It is good practice to set this attribute to avoid combining\n incompatible labels and SourceEstimates (e.g., ones from other\n subjects). Note that due to file specification limitations, the\n subject name isn't saved to or loaded from files written to disk.\n color : None | matplotlib color\n Default label color and alpha (e.g., ``(1., 0., 0., 1.)`` for red).\n Note that due to file specification limitations, the color isn't saved\n to or loaded from files written to disk.\n\n Returns\n -------\n label : Label\n Instance of Label object with attributes:\n\n - ``comment``: comment from the first line of the label file\n - ``vertices``: vertex indices (0 based, column 1)\n - ``pos``: locations in meters (columns 2 - 4 divided by 1000)\n - ``values``: values at the vertices (column 5)\n\n See Also\n --------\n read_labels_from_annot\n \"\"\"\n if subject is not None and not isinstance(subject, string_types):\n raise TypeError('subject must be a string')\n\n # find hemi\n basename = op.basename(filename)\n if basename.endswith('lh.label') or basename.startswith('lh.'):\n hemi = 'lh'\n elif basename.endswith('rh.label') or basename.startswith('rh.'):\n hemi = 'rh'\n else:\n raise ValueError('Cannot find which hemisphere it is. File should end'\n ' with lh.label or rh.label')\n\n # find name\n if basename.startswith(('lh.', 'rh.')):\n basename_ = basename[3:]\n if basename.endswith('.label'):\n basename_ = basename[:-6]\n else:\n basename_ = basename[:-9]\n name = \"%s-%s\" % (basename_, hemi)\n\n # read the file\n with open(filename, 'r') as fid:\n comment = fid.readline().replace('\\n', '')[1:]\n nv = int(fid.readline())\n data = np.empty((5, nv))\n for i, line in enumerate(fid):\n data[:, i] = line.split()\n\n # let's make sure everything is ordered correctly\n vertices = np.array(data[0], dtype=np.int32)\n pos = 1e-3 * data[1:4].T\n values = data[4]\n order = np.argsort(vertices)\n vertices = vertices[order]\n pos = pos[order]\n values = values[order]\n\n label = Label(vertices, pos, values, hemi, comment, name, filename,\n subject, color)\n\n return label\n\n\n@verbose\ndef write_label(filename, label, verbose=None):\n \"\"\"Write a FreeSurfer label\n\n Parameters\n ----------\n filename : string\n Path to label file to produce.\n label : Label\n The label object to save.\n verbose : bool, str, int, or None\n If not None, override default verbose level (see mne.verbose).\n\n Notes\n -----\n Note that due to file specification limitations, the Label's subject and\n color attributes are not saved to disk.\n\n See Also\n --------\n write_labels_to_annot\n \"\"\"\n hemi = label.hemi\n path_head, name = op.split(filename)\n if name.endswith('.label'):\n name = name[:-6]\n if not (name.startswith(hemi) or name.endswith(hemi)):\n name += '-' + hemi\n filename = op.join(path_head, name) + '.label'\n\n logger.info('Saving label to : %s' % filename)\n\n with open(filename, 'wb') as fid:\n n_vertices = len(label.vertices)\n data = np.zeros((n_vertices, 5), dtype=np.float)\n data[:, 0] = label.vertices\n data[:, 1:4] = 1e3 * label.pos\n data[:, 4] = label.values\n fid.write(b(\"#%s\\n\" % label.comment))\n fid.write(b(\"%d\\n\" % n_vertices))\n for d in data:\n fid.write(b(\"%d %f %f %f %f\\n\" % tuple(d)))\n return label\n\n\ndef _prep_label_split(label, subject=None, subjects_dir=None):\n \"\"\"Helper to get label and subject information prior to label spliting\"\"\"\n\n # If necessary, find the label\n if isinstance(label, BiHemiLabel):\n raise TypeError(\"Can only split labels restricted to one hemisphere.\")\n elif isinstance(label, string_types):\n label = read_label(label)\n\n # Find the subject\n subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)\n if label.subject is None and subject is None:\n raise ValueError(\"The subject needs to be specified.\")\n elif subject is None:\n subject = label.subject\n elif label.subject is None:\n pass\n elif subject != label.subject:\n raise ValueError(\"The label specifies a different subject (%r) from \"\n \"the subject parameter (%r).\"\n % label.subject, subject)\n\n return label, subject, subjects_dir\n\n\ndef _split_label_contig(label_to_split, subject=None, subjects_dir=None):\n \"\"\"Split label into contiguous regions (i.e., connected components)\n\n Parameters\n ----------\n label_to_split : Label | str\n Label which is to be split (Label object or path to a label file).\n subject : None | str\n Subject which this label belongs to (needed to locate surface file;\n should only be specified if it is not specified in the label).\n subjects_dir : None | str\n Path to SUBJECTS_DIR if it is not set in the environment.\n\n Returns\n -------\n labels : list of Label\n The contiguous labels, in order of decending size.\n \"\"\"\n # Convert to correct input if necessary\n label_to_split, subject, subjects_dir = _prep_label_split(label_to_split,\n subject,\n subjects_dir)\n\n # Find the spherical surface to get vertices and tris\n surf_fname = '.'.join((label_to_split.hemi, 'sphere'))\n surf_path = op.join(subjects_dir, subject, 'surf', surf_fname)\n surface_points, surface_tris = read_surface(surf_path)\n\n # Get vertices we want to keep and compute mesh edges\n verts_arr = label_to_split.vertices\n edges_all = mesh_edges(surface_tris)\n\n # Subselect rows and cols of vertices that belong to the label\n select_edges = edges_all[verts_arr][:, verts_arr].tocoo()\n\n # Compute connected components and store as lists of vertex numbers\n comp_labels = _get_components(verts_arr, select_edges)\n\n # Convert to indices in the original surface space\n label_divs = []\n for comp in comp_labels:\n label_divs.append(verts_arr[comp])\n\n # Construct label division names\n n_parts = len(label_divs)\n if label_to_split.name.endswith(('lh', 'rh')):\n basename = label_to_split.name[:-3]\n name_ext = label_to_split.name[-3:]\n else:\n basename = label_to_split.name\n name_ext = ''\n name_pattern = \"%s_div%%i%s\" % (basename, name_ext)\n names = tuple(name_pattern % i for i in range(1, n_parts + 1))\n\n # Colors\n if label_to_split.color is None:\n colors = (None,) * n_parts\n else:\n colors = _split_colors(label_to_split.color, n_parts)\n\n # Sort label divisions by their size (in vertices)\n label_divs.sort(key=lambda x: len(x), reverse=True)\n labels = []\n for div, name, color in zip(label_divs, names, colors):\n # Get indices of dipoles within this division of the label\n verts = np.array(sorted(list(div)))\n vert_indices = in1d(verts_arr, verts, assume_unique=True)\n\n # Set label attributes\n pos = label_to_split.pos[vert_indices]\n values = label_to_split.values[vert_indices]\n hemi = label_to_split.hemi\n comment = label_to_split.comment\n lbl = Label(verts, pos, values, hemi, comment, name, None, subject,\n color)\n labels.append(lbl)\n\n return labels\n\n\ndef split_label(label, parts=2, subject=None, subjects_dir=None,\n freesurfer=False):\n \"\"\"Split a Label into two or more parts\n\n Parameters\n ----------\n label : Label | str\n Label which is to be split (Label object or path to a label file).\n parts : int >= 2 | tuple of str\n A sequence of strings specifying label names for the new labels (from\n posterior to anterior), or the number of new labels to create (default\n is 2). If a number is specified, names of the new labels will be the\n input label's name with div1, div2 etc. appended.\n subject : None | str\n Subject which this label belongs to (needed to locate surface file;\n should only be specified if it is not specified in the label).\n subjects_dir : None | str\n Path to SUBJECTS_DIR if it is not set in the environment.\n freesurfer : bool\n By default (``False``) ``split_label`` uses an algorithm that is\n slightly optimized for performance and numerical precision. Set\n ``freesurfer`` to ``True`` in order to replicate label splits from\n FreeSurfer's ``mris_divide_parcellation``.\n\n Returns\n -------\n labels : list of Label (len = n_parts)\n The labels, starting from the lowest to the highest end of the\n projection axis.\n\n Notes\n -----\n Works by finding the label's principal eigen-axis on the spherical surface,\n projecting all label vertex coordinates onto this axis and dividing them at\n regular spatial intervals.\n \"\"\"\n\n label, subject, subjects_dir = _prep_label_split(label, subject,\n subjects_dir)\n\n # find the parts\n if np.isscalar(parts):\n n_parts = int(parts)\n if label.name.endswith(('lh', 'rh')):\n basename = label.name[:-3]\n name_ext = label.name[-3:]\n else:\n basename = label.name\n name_ext = ''\n name_pattern = \"%s_div%%i%s\" % (basename, name_ext)\n names = tuple(name_pattern % i for i in range(1, n_parts + 1))\n else:\n names = parts\n n_parts = len(names)\n\n if n_parts < 2:\n raise ValueError(\"Can't split label into %i parts\" % n_parts)\n\n # find the spherical surface\n surf_fname = '.'.join((label.hemi, 'sphere'))\n surf_path = op.join(subjects_dir, subject, \"surf\", surf_fname)\n surface_points, surface_tris = read_surface(surf_path)\n # find the label coordinates on the surface\n points = surface_points[label.vertices]\n center = np.mean(points, axis=0)\n centered_points = points - center\n\n # find the label's normal\n if freesurfer:\n # find the Freesurfer vertex closest to the center\n distance = np.sqrt(np.sum(centered_points ** 2, axis=1))\n i_closest = np.argmin(distance)\n closest_vertex = label.vertices[i_closest]\n # find the normal according to freesurfer convention\n idx = np.any(surface_tris == closest_vertex, axis=1)\n tris_for_normal = surface_tris[idx]\n r1 = surface_points[tris_for_normal[:, 0], :]\n r2 = surface_points[tris_for_normal[:, 1], :]\n r3 = surface_points[tris_for_normal[:, 2], :]\n tri_normals = fast_cross_3d((r2 - r1), (r3 - r1))\n normal = np.mean(tri_normals, axis=0)\n normal /= linalg.norm(normal)\n else:\n # Normal of the center\n normal = center / linalg.norm(center)\n\n # project all vertex coordinates on the tangential plane for this point\n q, _ = linalg.qr(normal[:, np.newaxis])\n tangent_u = q[:, 1:]\n m_obs = np.dot(centered_points, tangent_u)\n # find principal eigendirection\n m_cov = np.dot(m_obs.T, m_obs)\n w, vr = linalg.eig(m_cov)\n i = np.argmax(w)\n eigendir = vr[:, i]\n # project back into 3d space\n axis = np.dot(tangent_u, eigendir)\n # orient them from posterior to anterior\n if axis[1] < 0:\n axis *= -1\n\n # project the label on the axis\n proj = np.dot(points, axis)\n\n # assign mark (new label index)\n proj -= proj.min()\n proj /= (proj.max() / n_parts)\n mark = proj // 1\n mark[mark == n_parts] = n_parts - 1\n\n # colors\n if label.color is None:\n colors = (None,) * n_parts\n else:\n colors = _split_colors(label.color, n_parts)\n\n # construct new labels\n labels = []\n for i, name, color in zip(range(n_parts), names, colors):\n idx = (mark == i)\n vert = label.vertices[idx]\n pos = label.pos[idx]\n values = label.values[idx]\n hemi = label.hemi\n comment = label.comment\n lbl = Label(vert, pos, values, hemi, comment, name, None, subject,\n color)\n labels.append(lbl)\n\n return labels\n\n\ndef label_sign_flip(label, src):\n \"\"\"Compute sign for label averaging\n\n Parameters\n ----------\n label : Label\n A label.\n src : list of dict\n The source space over which the label is defined.\n\n Returns\n -------\n flip : array\n Sign flip vector (contains 1 or -1)\n \"\"\"\n if len(src) != 2:\n raise ValueError('Only source spaces with 2 hemisphers are accepted')\n\n lh_vertno = src[0]['vertno']\n rh_vertno = src[1]['vertno']\n\n # get source orientations\n if label.hemi == 'lh':\n vertno_sel = np.intersect1d(lh_vertno, label.vertices)\n if len(vertno_sel) == 0:\n return np.array([], int)\n ori = src[0]['nn'][vertno_sel]\n elif label.hemi == 'rh':\n vertno_sel = np.intersect1d(rh_vertno, label.vertices)\n if len(vertno_sel) == 0:\n return np.array([], int)\n ori = src[1]['nn'][vertno_sel]\n else:\n raise Exception(\"Unknown hemisphere type\")\n\n _, _, Vh = linalg.svd(ori, full_matrices=False)\n\n # Comparing to the direction of the first right singular vector\n flip = np.sign(np.dot(ori, Vh[0]))\n return flip\n\n\ndef stc_to_label(stc, src=None, smooth=True, connected=False,\n subjects_dir=None):\n \"\"\"Compute a label from the non-zero sources in an stc object.\n\n Parameters\n ----------\n stc : SourceEstimate\n The source estimates.\n src : SourceSpaces | str | None\n The source space over which the source estimates are defined.\n If it's a string it should the subject name (e.g. fsaverage).\n Can be None if stc.subject is not None.\n smooth : bool\n Fill in vertices on the cortical surface that are not in the source\n space based on the closest source space vertex (requires\n src to be a SourceSpace).\n connected : bool\n If True a list of connected labels will be returned in each\n hemisphere. The labels are ordered in decreasing order depending\n of the maximum value in the stc.\n subjects_dir : str | None\n Path to SUBJECTS_DIR if it is not set in the environment.\n\n Returns\n -------\n labels : list of Labels | list of list of Labels\n The generated labels. If connected is False, it returns\n a list of Labels (one per hemisphere). If no Label is available\n in a hemisphere, None is returned. If connected is True,\n it returns for each hemisphere a list of connected labels\n ordered in decreasing order depending of the maximum value in the stc.\n If no Label is available in an hemisphere, an empty list is returned.\n \"\"\"\n if not isinstance(smooth, bool):\n raise ValueError('smooth should be True or False. Got %s.' % smooth)\n\n src = stc.subject if src is None else src\n if src is None:\n raise ValueError('src cannot be None if stc.subject is None')\n if isinstance(src, string_types):\n subject = src\n else:\n subject = stc.subject\n\n if not isinstance(stc, SourceEstimate):\n raise ValueError('SourceEstimate should be surface source estimates')\n\n if isinstance(src, string_types):\n if connected:\n raise ValueError('The option to return only connected labels is '\n 'only available if source spaces are provided.')\n if smooth:\n msg = (\"stc_to_label with smooth=True requires src to be an \"\n \"instance of SourceSpace\")\n raise ValueError(msg)\n subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)\n surf_path_from = op.join(subjects_dir, src, 'surf')\n rr_lh, tris_lh = read_surface(op.join(surf_path_from, 'lh.white'))\n rr_rh, tris_rh = read_surface(op.join(surf_path_from, 'rh.white'))\n rr = [rr_lh, rr_rh]\n tris = [tris_lh, tris_rh]\n else:\n if not isinstance(src, SourceSpaces):\n raise TypeError('src must be a string or a set of source spaces')\n if len(src) != 2:\n raise ValueError('source space should contain the 2 hemispheres')\n rr = [1e3 * src[0]['rr'], 1e3 * src[1]['rr']]\n tris = [src[0]['tris'], src[1]['tris']]\n src_conn = spatial_src_connectivity(src).tocsr()\n\n labels = []\n cnt = 0\n cnt_full = 0\n for hemi_idx, (hemi, this_vertno, this_tris, this_rr) in enumerate(\n zip(['lh', 'rh'], stc.vertices, tris, rr)):\n this_data = stc.data[cnt:cnt + len(this_vertno)]\n e = mesh_edges(this_tris)\n e.data[e.data == 2] = 1\n n_vertices = e.shape[0]\n e = e + sparse.eye(n_vertices, n_vertices)\n\n if connected: # we know src *must* be a SourceSpaces now\n vertno = np.where(src[hemi_idx]['inuse'])[0]\n if not len(np.setdiff1d(this_vertno, vertno)) == 0:\n raise RuntimeError('stc contains vertices not present '\n 'in source space, did you morph?')\n tmp = np.zeros((len(vertno), this_data.shape[1]))\n this_vertno_idx = np.searchsorted(vertno, this_vertno)\n tmp[this_vertno_idx] = this_data\n this_data = tmp\n offset = cnt_full + len(this_data)\n this_src_conn = src_conn[cnt_full:offset, cnt_full:offset].tocoo()\n this_data_abs_max = np.abs(this_data).max(axis=1)\n clusters, _ = _find_clusters(this_data_abs_max, 0.,\n connectivity=this_src_conn)\n cnt_full += len(this_data)\n # Then order clusters in descending order based on maximum value\n clusters_max = np.argsort([np.max(this_data_abs_max[c])\n for c in clusters])[::-1]\n clusters = [clusters[k] for k in clusters_max]\n clusters = [vertno[c] for c in clusters]\n else:\n clusters = [this_vertno[np.any(this_data, axis=1)]]\n\n cnt += len(this_vertno)\n\n clusters = [c for c in clusters if len(c) > 0]\n\n if len(clusters) == 0:\n if not connected:\n this_labels = None\n else:\n this_labels = []\n else:\n this_labels = []\n colors = _n_colors(len(clusters))\n for c, color in zip(clusters, colors):\n idx_use = c\n label = Label(idx_use, this_rr[idx_use], None, hemi,\n 'Label from stc', subject=subject,\n color=color)\n if smooth:\n label = label.fill(src)\n\n this_labels.append(label)\n\n if not connected:\n this_labels = this_labels[0]\n\n labels.append(this_labels)\n\n return labels\n\n\ndef _verts_within_dist(graph, sources, max_dist):\n \"\"\"Find all vertices wihin a maximum geodesic distance from source\n\n Parameters\n ----------\n graph : scipy.sparse.csr_matrix\n Sparse matrix with distances between adjacent vertices.\n sources : list of int\n Source vertices.\n max_dist : float\n Maximum geodesic distance.\n\n Returns\n -------\n verts : array\n Vertices within max_dist.\n dist : array\n Distances from source vertex.\n \"\"\"\n dist_map = {}\n verts_added_last = []\n for source in sources:\n dist_map[source] = 0\n verts_added_last.append(source)\n\n # add neighbors until no more neighbors within max_dist can be found\n while len(verts_added_last) > 0:\n verts_added = []\n for i in verts_added_last:\n v_dist = dist_map[i]\n row = graph[i, :]\n neighbor_vert = row.indices\n neighbor_dist = row.data\n for j, d in zip(neighbor_vert, neighbor_dist):\n n_dist = v_dist + d\n if j in dist_map:\n if n_dist < dist_map[j]:\n dist_map[j] = n_dist\n else:\n if n_dist <= max_dist:\n dist_map[j] = n_dist\n # we found a new vertex within max_dist\n verts_added.append(j)\n verts_added_last = verts_added\n\n verts = np.sort(np.array(list(dist_map.keys()), dtype=np.int))\n dist = np.array([dist_map[v] for v in verts])\n\n return verts, dist\n\n\ndef _grow_labels(seeds, extents, hemis, names, dist, vert, subject):\n \"\"\"Helper for parallelization of grow_labels\n \"\"\"\n labels = []\n for seed, extent, hemi, name in zip(seeds, extents, hemis, names):\n label_verts, label_dist = _verts_within_dist(dist[hemi], seed, extent)\n\n # create a label\n if len(seed) == 1:\n seed_repr = str(seed)\n else:\n seed_repr = ','.join(map(str, seed))\n comment = 'Circular label: seed=%s, extent=%0.1fmm' % (seed_repr,\n extent)\n label = Label(vertices=label_verts,\n pos=vert[hemi][label_verts],\n values=label_dist,\n hemi=hemi,\n comment=comment,\n name=str(name),\n subject=subject)\n labels.append(label)\n return labels\n\n\ndef grow_labels(subject, seeds, extents, hemis, subjects_dir=None, n_jobs=1,\n overlap=True, names=None, surface='white'):\n \"\"\"Generate circular labels in source space with region growing\n\n This function generates a number of labels in source space by growing\n regions starting from the vertices defined in \"seeds\". For each seed, a\n label is generated containing all vertices within a maximum geodesic\n distance on the white matter surface from the seed.\n\n Note: \"extents\" and \"hemis\" can either be arrays with the same length as\n seeds, which allows using a different extent and hemisphere for each\n label, or integers, in which case the same extent and hemisphere is\n used for each label.\n\n Parameters\n ----------\n subject : string\n Name of the subject as in SUBJECTS_DIR.\n seeds : int | list\n Seed, or list of seeds. Each seed can be either a vertex number or\n a list of vertex numbers.\n extents : array | float\n Extents (radius in mm) of the labels.\n hemis : array | int\n Hemispheres to use for the labels (0: left, 1: right).\n subjects_dir : string\n Path to SUBJECTS_DIR if not set in the environment.\n n_jobs : int\n Number of jobs to run in parallel. Likely only useful if tens\n or hundreds of labels are being expanded simultaneously. Does not\n apply with ``overlap=False``.\n overlap : bool\n Produce overlapping labels. If True (default), the resulting labels\n can be overlapping. If False, each label will be grown one step at a\n time, and occupied territory will not be invaded.\n names : None | list of str\n Assign names to the new labels (list needs to have the same length as\n seeds).\n surface : string\n The surface used to grow the labels, defaults to the white surface.\n\n Returns\n -------\n labels : list of Label\n The labels' ``comment`` attribute contains information on the seed\n vertex and extent; the ``values`` attribute contains distance from the\n seed in millimeters\n \"\"\"\n subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)\n n_jobs = check_n_jobs(n_jobs)\n\n # make sure the inputs are arrays\n if np.isscalar(seeds):\n seeds = [seeds]\n seeds = np.atleast_1d([np.atleast_1d(seed) for seed in seeds])\n extents = np.atleast_1d(extents)\n hemis = np.atleast_1d(hemis)\n n_seeds = len(seeds)\n\n if len(extents) != 1 and len(extents) != n_seeds:\n raise ValueError('The extents parameter has to be of length 1 or '\n 'len(seeds)')\n\n if len(hemis) != 1 and len(hemis) != n_seeds:\n raise ValueError('The hemis parameter has to be of length 1 or '\n 'len(seeds)')\n\n # make the arrays the same length as seeds\n if len(extents) == 1:\n extents = np.tile(extents, n_seeds)\n\n if len(hemis) == 1:\n hemis = np.tile(hemis, n_seeds)\n\n hemis = np.array(['lh' if h == 0 else 'rh' for h in hemis])\n\n # names\n if names is None:\n names = [\"Label_%i-%s\" % items for items in enumerate(hemis)]\n else:\n if np.isscalar(names):\n names = [names]\n if len(names) != n_seeds:\n raise ValueError('The names parameter has to be None or have '\n 'length len(seeds)')\n for i, hemi in enumerate(hemis):\n if not names[i].endswith(hemi):\n names[i] = '-'.join((names[i], hemi))\n names = np.array(names)\n\n # load the surfaces and create the distance graphs\n tris, vert, dist = {}, {}, {}\n for hemi in set(hemis):\n surf_fname = op.join(subjects_dir, subject, 'surf', hemi + '.' +\n surface)\n vert[hemi], tris[hemi] = read_surface(surf_fname)\n dist[hemi] = mesh_dist(tris[hemi], vert[hemi])\n\n if overlap:\n # create the patches\n parallel, my_grow_labels, _ = parallel_func(_grow_labels, n_jobs)\n seeds = np.array_split(seeds, n_jobs)\n extents = np.array_split(extents, n_jobs)\n hemis = np.array_split(hemis, n_jobs)\n names = np.array_split(names, n_jobs)\n labels = sum(parallel(my_grow_labels(s, e, h, n, dist, vert, subject)\n for s, e, h, n\n in zip(seeds, extents, hemis, names)), [])\n else:\n # special procedure for non-overlapping labels\n labels = _grow_nonoverlapping_labels(subject, seeds, extents, hemis,\n vert, dist, names)\n\n # add a unique color to each label\n colors = _n_colors(len(labels))\n for label, color in zip(labels, colors):\n label.color = color\n\n return labels\n\n\ndef _grow_nonoverlapping_labels(subject, seeds_, extents_, hemis, vertices_,\n graphs, names_):\n \"\"\"Grow labels while ensuring that they don't overlap\n \"\"\"\n labels = []\n for hemi in set(hemis):\n hemi_index = (hemis == hemi)\n seeds = seeds_[hemi_index]\n extents = extents_[hemi_index]\n names = names_[hemi_index]\n graph = graphs[hemi] # distance graph\n n_vertices = len(vertices_[hemi])\n n_labels = len(seeds)\n\n # prepare parcellation\n parc = np.empty(n_vertices, dtype='int32')\n parc[:] = -1\n\n # initialize active sources\n sources = {} # vert -> (label, dist_from_seed)\n edge = [] # queue of vertices to process\n for label, seed in enumerate(seeds):\n if np.any(parc[seed] >= 0):\n raise ValueError(\"Overlapping seeds\")\n parc[seed] = label\n for s in np.atleast_1d(seed):\n sources[s] = (label, 0.)\n edge.append(s)\n\n # grow from sources\n while edge:\n vert_from = edge.pop(0)\n label, old_dist = sources[vert_from]\n\n # add neighbors within allowable distance\n row = graph[vert_from, :]\n for vert_to, dist in zip(row.indices, row.data):\n new_dist = old_dist + dist\n\n # abort if outside of extent\n if new_dist > extents[label]:\n continue\n\n vert_to_label = parc[vert_to]\n if vert_to_label >= 0:\n _, vert_to_dist = sources[vert_to]\n # abort if the vertex is occupied by a closer seed\n if new_dist > vert_to_dist:\n continue\n elif vert_to in edge:\n edge.remove(vert_to)\n\n # assign label value\n parc[vert_to] = label\n sources[vert_to] = (label, new_dist)\n edge.append(vert_to)\n\n # convert parc to labels\n for i in xrange(n_labels):\n vertices = np.nonzero(parc == i)[0]\n name = str(names[i])\n label_ = Label(vertices, hemi=hemi, name=name, subject=subject)\n labels.append(label_)\n\n return labels\n\n\ndef _read_annot(fname):\n \"\"\"Read a Freesurfer annotation from a .annot file.\n\n Note : Copied from PySurfer\n\n Parameters\n ----------\n fname : str\n Path to annotation file\n\n Returns\n -------\n annot : numpy array, shape=(n_verts)\n Annotation id at each vertex\n ctab : numpy array, shape=(n_entries, 5)\n RGBA + label id colortable array\n names : list of str\n List of region names as stored in the annot file\n\n \"\"\"\n if not op.isfile(fname):\n dir_name = op.split(fname)[0]\n if not op.isdir(dir_name):\n raise IOError('Directory for annotation does not exist: %s',\n fname)\n cands = os.listdir(dir_name)\n cands = [c for c in cands if '.annot' in c]\n if len(cands) == 0:\n raise IOError('No such file %s, no candidate parcellations '\n 'found in directory' % fname)\n else:\n raise IOError('No such file %s, candidate parcellations in '\n 'that directory: %s' % (fname, ', '.join(cands)))\n with open(fname, \"rb\") as fid:\n n_verts = np.fromfile(fid, '>i4', 1)[0]\n data = np.fromfile(fid, '>i4', n_verts * 2).reshape(n_verts, 2)\n annot = data[data[:, 0], 1]\n ctab_exists = np.fromfile(fid, '>i4', 1)[0]\n if not ctab_exists:\n raise Exception('Color table not found in annotation file')\n n_entries = np.fromfile(fid, '>i4', 1)[0]\n if n_entries > 0:\n length = np.fromfile(fid, '>i4', 1)[0]\n orig_tab = np.fromfile(fid, '>c', length)\n orig_tab = orig_tab[:-1]\n\n names = list()\n ctab = np.zeros((n_entries, 5), np.int)\n for i in range(n_entries):\n name_length = np.fromfile(fid, '>i4', 1)[0]\n name = np.fromfile(fid, \"|S%d\" % name_length, 1)[0]\n names.append(name)\n ctab[i, :4] = np.fromfile(fid, '>i4', 4)\n ctab[i, 4] = (ctab[i, 0] + ctab[i, 1] * (2 ** 8) +\n ctab[i, 2] * (2 ** 16) +\n ctab[i, 3] * (2 ** 24))\n else:\n ctab_version = -n_entries\n if ctab_version != 2:\n raise Exception('Color table version not supported')\n n_entries = np.fromfile(fid, '>i4', 1)[0]\n ctab = np.zeros((n_entries, 5), np.int)\n length = np.fromfile(fid, '>i4', 1)[0]\n np.fromfile(fid, \"|S%d\" % length, 1) # Orig table path\n entries_to_read = np.fromfile(fid, '>i4', 1)[0]\n names = list()\n for i in range(entries_to_read):\n np.fromfile(fid, '>i4', 1) # Structure\n name_length = np.fromfile(fid, '>i4', 1)[0]\n name = np.fromfile(fid, \"|S%d\" % name_length, 1)[0]\n names.append(name)\n ctab[i, :4] = np.fromfile(fid, '>i4', 4)\n ctab[i, 4] = (ctab[i, 0] + ctab[i, 1] * (2 ** 8) +\n ctab[i, 2] * (2 ** 16))\n\n # convert to more common alpha value\n ctab[:, 3] = 255 - ctab[:, 3]\n\n return annot, ctab, names\n\n\ndef _get_annot_fname(annot_fname, subject, hemi, parc, subjects_dir):\n \"\"\"Helper function to get the .annot filenames and hemispheres\"\"\"\n if annot_fname is not None:\n # we use use the .annot file specified by the user\n hemis = [op.basename(annot_fname)[:2]]\n if hemis[0] not in ['lh', 'rh']:\n raise ValueError('Could not determine hemisphere from filename, '\n 'filename has to start with \"lh\" or \"rh\".')\n annot_fname = [annot_fname]\n else:\n # construct .annot file names for requested subject, parc, hemi\n if hemi not in ['lh', 'rh', 'both']:\n raise ValueError('hemi has to be \"lh\", \"rh\", or \"both\"')\n if hemi == 'both':\n hemis = ['lh', 'rh']\n else:\n hemis = [hemi]\n\n subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)\n dst = op.join(subjects_dir, subject, 'label', '%%s.%s.annot' % parc)\n annot_fname = [dst % hemi_ for hemi_ in hemis]\n\n return annot_fname, hemis\n\n\n@verbose\ndef read_labels_from_annot(subject, parc='aparc', hemi='both',\n surf_name='white', annot_fname=None, regexp=None,\n subjects_dir=None, verbose=None):\n \"\"\"Read labels from a FreeSurfer annotation file\n\n Note: Only cortical labels will be returned.\n\n Parameters\n ----------\n subject : str\n The subject for which to read the parcellation for.\n parc : str\n The parcellation to use, e.g., 'aparc' or 'aparc.a2009s'.\n hemi : str\n The hemisphere to read the parcellation for, can be 'lh', 'rh',\n or 'both'.\n surf_name : str\n Surface used to obtain vertex locations, e.g., 'white', 'pial'\n annot_fname : str or None\n Filename of the .annot file. If not None, only this file is read\n and 'parc' and 'hemi' are ignored.\n regexp : str\n Regular expression or substring to select particular labels from the\n parcellation. E.g. 'superior' will return all labels in which this\n substring is contained.\n subjects_dir : string, or None\n Path to SUBJECTS_DIR if it is not set in the environment.\n verbose : bool, str, int, or None\n If not None, override default verbose level (see mne.verbose).\n\n Returns\n -------\n labels : list of Label\n The labels, sorted by label name (ascending).\n \"\"\"\n logger.info('Reading labels from parcellation..')\n\n subjects_dir = get_subjects_dir(subjects_dir)\n\n # get the .annot filenames and hemispheres\n annot_fname, hemis = _get_annot_fname(annot_fname, subject, hemi, parc,\n subjects_dir)\n\n if regexp is not None:\n # allow for convenient substring match\n r_ = (re.compile('.*%s.*' % regexp if regexp.replace('_', '').isalnum()\n else regexp))\n\n # now we are ready to create the labels\n n_read = 0\n labels = list()\n for fname, hemi in zip(annot_fname, hemis):\n # read annotation\n annot, ctab, label_names = _read_annot(fname)\n label_rgbas = ctab[:, :4]\n label_ids = ctab[:, -1]\n\n # load the vertex positions from surface\n fname_surf = op.join(subjects_dir, subject, 'surf',\n '%s.%s' % (hemi, surf_name))\n vert_pos, _ = read_surface(fname_surf)\n vert_pos /= 1e3 # the positions in labels are in meters\n for label_id, label_name, label_rgba in\\\n zip(label_ids, label_names, label_rgbas):\n vertices = np.where(annot == label_id)[0]\n if len(vertices) == 0:\n # label is not part of cortical surface\n continue\n name = label_name.decode() + '-' + hemi\n if (regexp is not None) and not r_.match(name):\n continue\n pos = vert_pos[vertices, :]\n values = np.zeros(len(vertices))\n label_rgba = tuple(label_rgba / 255.)\n label = Label(vertices, pos, values, hemi, name=name,\n subject=subject, color=label_rgba)\n labels.append(label)\n\n n_read = len(labels) - n_read\n logger.info(' read %d labels from %s' % (n_read, fname))\n\n # sort the labels by label name\n labels = sorted(labels, key=lambda l: l.name)\n\n if len(labels) == 0:\n msg = 'No labels found.'\n if regexp is not None:\n msg += ' Maybe the regular expression %r did not match?' % regexp\n raise RuntimeError(msg)\n\n logger.info('[done]')\n return labels\n\n\ndef _write_annot(fname, annot, ctab, names):\n \"\"\"Write a Freesurfer annotation to a .annot file.\n\n Parameters\n ----------\n fname : str\n Path to annotation file\n annot : numpy array, shape=(n_verts)\n Annotation id at each vertex. Note: IDs must be computed from\n RGBA colors, otherwise the mapping will be invalid.\n ctab : numpy array, shape=(n_entries, 4)\n RGBA colortable array.\n names : list of str\n List of region names to be stored in the annot file\n \"\"\"\n\n with open(fname, 'wb') as fid:\n n_verts = len(annot)\n np.array(n_verts, dtype='>i4').tofile(fid)\n\n data = np.zeros((n_verts, 2), dtype='>i4')\n data[:, 0] = np.arange(n_verts)\n data[:, 1] = annot\n data.ravel().tofile(fid)\n\n # indicate that color table exists\n np.array(1, dtype='>i4').tofile(fid)\n\n # color table version 2\n np.array(-2, dtype='>i4').tofile(fid)\n\n # write color table\n n_entries = len(ctab)\n np.array(n_entries, dtype='>i4').tofile(fid)\n\n # write dummy color table name\n table_name = 'MNE-Python Colortable'\n np.array(len(table_name), dtype='>i4').tofile(fid)\n np.fromstring(table_name, dtype=np.uint8).tofile(fid)\n\n # number of entries to write\n np.array(n_entries, dtype='>i4').tofile(fid)\n\n # write entries\n for ii, (name, color) in enumerate(zip(names, ctab)):\n np.array(ii, dtype='>i4').tofile(fid)\n np.array(len(name), dtype='>i4').tofile(fid)\n np.fromstring(name, dtype=np.uint8).tofile(fid)\n np.array(color[:4], dtype='>i4').tofile(fid)\n\n\n@verbose\ndef write_labels_to_annot(labels, subject=None, parc=None, overwrite=False,\n subjects_dir=None, annot_fname=None,\n colormap='hsv', hemi='both', verbose=None):\n \"\"\"Create a FreeSurfer annotation from a list of labels\n\n Parameters\n ----------\n labels : list with instances of mne.Label\n The labels to create a parcellation from.\n subject : str | None\n The subject for which to write the parcellation for.\n parc : str | None\n The parcellation name to use.\n overwrite : bool\n Overwrite files if they already exist.\n subjects_dir : string, or None\n Path to SUBJECTS_DIR if it is not set in the environment.\n annot_fname : str | None\n Filename of the .annot file. If not None, only this file is written\n and 'parc' and 'subject' are ignored.\n colormap : str\n Colormap to use to generate label colors for labels that do not\n have a color specified.\n hemi : 'both' | 'lh' | 'rh'\n The hemisphere(s) for which to write \\*.annot files (only applies if\n annot_fname is not specified; default is 'both').\n verbose : bool, str, int, or None\n If not None, override default verbose level (see mne.verbose).\n\n Notes\n -----\n Vertices that are not covered by any of the labels are assigned to a label\n named \"unknown\".\n \"\"\"\n logger.info('Writing labels to parcellation..')\n\n subjects_dir = get_subjects_dir(subjects_dir)\n\n # get the .annot filenames and hemispheres\n annot_fname, hemis = _get_annot_fname(annot_fname, subject, hemi, parc,\n subjects_dir)\n\n if not overwrite:\n for fname in annot_fname:\n if op.exists(fname):\n raise ValueError('File %s exists. Use \"overwrite=True\" to '\n 'overwrite it' % fname)\n\n # prepare container for data to save:\n to_save = []\n # keep track of issues found in the labels\n duplicate_colors = []\n invalid_colors = []\n overlap = []\n no_color = (-1, -1, -1, -1)\n no_color_rgb = (-1, -1, -1)\n for hemi, fname in zip(hemis, annot_fname):\n hemi_labels = [label for label in labels if label.hemi == hemi]\n n_hemi_labels = len(hemi_labels)\n\n if n_hemi_labels == 0:\n ctab = np.empty((0, 4), dtype=np.int32)\n ctab_rgb = ctab[:, :3]\n else:\n hemi_labels.sort(key=lambda label: label.name)\n\n # convert colors to 0-255 RGBA tuples\n hemi_colors = [no_color if label.color is None else\n tuple(int(round(255 * i)) for i in label.color)\n for label in hemi_labels]\n ctab = np.array(hemi_colors, dtype=np.int32)\n ctab_rgb = ctab[:, :3]\n\n # make color dict (for annot ID, only R, G and B count)\n labels_by_color = defaultdict(list)\n for label, color in zip(hemi_labels, ctab_rgb):\n labels_by_color[tuple(color)].append(label.name)\n\n # check label colors\n for color, names in labels_by_color.items():\n if color == no_color_rgb:\n continue\n\n if color == (0, 0, 0):\n # we cannot have an all-zero color, otherw. e.g. tksurfer\n # refuses to read the parcellation\n warn('At least one label contains a color with, \"r=0, '\n 'g=0, b=0\" value. Some FreeSurfer tools may fail '\n 'to read the parcellation')\n\n if any(i > 255 for i in color):\n msg = (\"%s: %s (%s)\" % (color, ', '.join(names), hemi))\n invalid_colors.append(msg)\n\n if len(names) > 1:\n msg = \"%s: %s (%s)\" % (color, ', '.join(names), hemi)\n duplicate_colors.append(msg)\n\n # replace None values (labels with unspecified color)\n if labels_by_color[no_color_rgb]:\n default_colors = _n_colors(n_hemi_labels, bytes_=True,\n cmap=colormap)\n # keep track of colors known to be in hemi_colors :\n safe_color_i = 0\n for i in xrange(n_hemi_labels):\n if ctab[i, 0] == -1:\n color = default_colors[i]\n # make sure to add no duplicate color\n while np.any(np.all(color[:3] == ctab_rgb, 1)):\n color = default_colors[safe_color_i]\n safe_color_i += 1\n # assign the color\n ctab[i] = color\n\n # find number of vertices in surface\n if subject is not None and subjects_dir is not None:\n fpath = op.join(subjects_dir, subject, 'surf', '%s.white' % hemi)\n points, _ = read_surface(fpath)\n n_vertices = len(points)\n else:\n if len(hemi_labels) > 0:\n max_vert = max(np.max(label.vertices) for label in hemi_labels)\n n_vertices = max_vert + 1\n else:\n n_vertices = 1\n warn('Number of vertices in the surface could not be '\n 'verified because the surface file could not be found; '\n 'specify subject and subjects_dir parameters.')\n\n # Create annot and color table array to write\n annot = np.empty(n_vertices, dtype=np.int)\n annot[:] = -1\n # create the annotation ids from the colors\n annot_id_coding = np.array((1, 2 ** 8, 2 ** 16))\n annot_ids = list(np.sum(ctab_rgb * annot_id_coding, axis=1))\n for label, annot_id in zip(hemi_labels, annot_ids):\n # make sure the label is not overwriting another label\n if np.any(annot[label.vertices] != -1):\n other_ids = set(annot[label.vertices])\n other_ids.discard(-1)\n other_indices = (annot_ids.index(i) for i in other_ids)\n other_names = (hemi_labels[i].name for i in other_indices)\n other_repr = ', '.join(other_names)\n msg = \"%s: %s overlaps %s\" % (hemi, label.name, other_repr)\n overlap.append(msg)\n\n annot[label.vertices] = annot_id\n\n hemi_names = [label.name for label in hemi_labels]\n\n if None in hemi_names:\n msg = (\"Found %i labels with no name. Writing annotation file\"\n \"requires all labels named\" % (hemi_names.count(None)))\n # raise the error immediately rather than crash with an\n # uninformative error later (e.g. cannot join NoneType)\n raise ValueError(msg)\n\n # Assign unlabeled vertices to an \"unknown\" label\n unlabeled = (annot == -1)\n if np.any(unlabeled):\n msg = (\"Assigning %i unlabeled vertices to \"\n \"'unknown-%s'\" % (unlabeled.sum(), hemi))\n logger.info(msg)\n\n # find an unused color (try shades of gray first)\n for i in range(1, 257):\n if not np.any(np.all((i, i, i) == ctab_rgb, 1)):\n break\n if i < 256:\n color = (i, i, i, 0)\n else:\n err = (\"Need one free shade of gray for 'unknown' label. \"\n \"Please modify your label colors, or assign the \"\n \"unlabeled vertices to another label.\")\n raise ValueError(err)\n\n # find the id\n annot_id = np.sum(annot_id_coding * color[:3])\n\n # update data to write\n annot[unlabeled] = annot_id\n ctab = np.vstack((ctab, color))\n hemi_names.append(\"unknown\")\n\n # convert to FreeSurfer alpha values\n ctab[:, 3] = 255 - ctab[:, 3]\n\n # remove hemi ending in names\n hemi_names = [name[:-3] if name.endswith(hemi) else name\n for name in hemi_names]\n\n to_save.append((fname, annot, ctab, hemi_names))\n\n issues = []\n if duplicate_colors:\n msg = (\"Some labels have the same color values (all labels in one \"\n \"hemisphere must have a unique color):\")\n duplicate_colors.insert(0, msg)\n issues.append(os.linesep.join(duplicate_colors))\n if invalid_colors:\n msg = (\"Some labels have invalid color values (all colors should be \"\n \"RGBA tuples with values between 0 and 1)\")\n invalid_colors.insert(0, msg)\n issues.append(os.linesep.join(invalid_colors))\n if overlap:\n msg = (\"Some labels occupy vertices that are also occupied by one or \"\n \"more other labels. Each vertex can only be occupied by a \"\n \"single label in *.annot files.\")\n overlap.insert(0, msg)\n issues.append(os.linesep.join(overlap))\n\n if issues:\n raise ValueError('\\n\\n'.join(issues))\n\n # write it\n for fname, annot, ctab, hemi_names in to_save:\n logger.info(' writing %d labels to %s' % (len(hemi_names), fname))\n _write_annot(fname, annot, ctab, hemi_names)\n\n logger.info('[done]')\n"
] | [
[
"numpy.sum",
"numpy.intersect1d",
"numpy.any",
"numpy.argsort",
"numpy.asarray",
"matplotlib.cm.get_cmap",
"numpy.isscalar",
"numpy.vstack",
"scipy.linalg.norm",
"numpy.argmin",
"numpy.abs",
"numpy.where",
"numpy.linspace",
"numpy.nonzero",
"numpy.mean",
"numpy.unique",
"numpy.sqrt",
"numpy.tile",
"numpy.fromstring",
"numpy.fromfile",
"numpy.zeros",
"numpy.searchsorted",
"numpy.setdiff1d",
"numpy.argmax",
"numpy.arange",
"scipy.sparse.eye",
"numpy.array_split",
"numpy.all",
"numpy.hstack",
"numpy.max",
"numpy.empty",
"numpy.atleast_1d",
"scipy.linalg.qr",
"matplotlib.colors.colorConverter.to_rgba",
"numpy.array",
"numpy.dot",
"scipy.linalg.eig",
"scipy.linalg.svd"
]
] |
tlsgusdn1107/BRAIN | [
"7664e276d0de16f27b0c40d5a83b5fe751830b15"
] | [
"BRAIN/Scripts/PREPROCESSING (DONE)/PRE_POST_SCALP_SEGMENTATION/4middlereg_v2.py"
] | [
"from __future__ import division\nfrom sympy import *\nimport numpy as np\nimport nibabel as nib\n\ndef middle_reg(a,b):\n \n A = nib.load(str(a))\n AA = np.array(A.dataobj)\n B = []\n for x in range(AA.shape[0]):\n for y in range(AA.shape[1]):\n for z in range(AA.shape[2]):\n if AA[x][y][z] != 0:\n B += [[x,y,z]]\n\n C = nib.load(str(b))\n CC = np.array(C.dataobj)\n D = []\n center = [129.99408517, 155.40402737140525, 120.06418584]\n #make sure the center for the actual code is the variable stored in the full code version.\n for x in range(CC.shape[0]):\n for y in range(CC.shape[1]):\n for z in range(CC.shape[2]):\n if CC[x][y][z] != 0:\n D += [[x,y,z]]\n E = []\n #final collection of MNI-mid registrated points\n for i in range(len(B)):\n F = []\n K = []\n for l in range(150,250):\n #range is manually determined\n Bx = round(center[0] + (B[i][0]-center[0])*(l/200))\n By = round(center[1] + (B[i][1]-center[1])*(l/200))\n Bz = round(center[2] + (B[i][2]-center[2])*(l/200))\n K += [[Bx,By,Bz]]\n for m in range(len(D)):\n if D[m] in K:\n sum_abs = abs(D[m][0]-center[0]) + abs(D[m][1]-center[1]) + abs(D[m][2]-center[2])\n F += [[sum_abs,D[m]]]\n if len(F) != 0:\n F.sort()\n final_point = [round((F[0][1][0]+F[-1][1][0])/2), round((F[0][1][1]+F[-1][1][1])/2), round((F[0][1][2]+F[-1][1][2])/2)]\n E += [final_point]\n G = np.zeros((AA.shape[0],AA.shape[1],AA.shape[2]))\n for h in range(len(E)):\n G[E[h][0]][E[h][1]][E[h][2]] = 1\n J = nib.Nifti1Image(G,affine=np.eye(4))\n nib.save(J,str(a)[:-7]+\"_middle_registered.nii.gz\")\n\n\nif __name__ == \"__main__\":\n middle_reg('13_reflecting.nii.gz','MNI-template_SCALP_normalized_filtered.nii.gz')\n middle_reg('16_reflecting.nii.gz','MNI-template_SCALP_normalized_filtered.nii.gz')\n middle_reg('26_reflecting.nii.gz','MNI-template_SCALP_normalized_filtered.nii.gz')\n\n"
] | [
[
"numpy.array",
"numpy.eye",
"numpy.zeros"
]
] |
segrelab/MiCoNE-synthetic-data | [
"330957b5d1c8ce8f27f915c8c5ceaedbcb1447b5"
] | [
"scripts/data_generation/create_samplesheets.py"
] | [
"#!/usr/bin/env python3\n\nimport pathlib\nfrom typing import List\n\nimport pandas as pd\n\nHEADER = [\"id\", \"otu_table\", \"obs_metadata\", \"sample_metadata\", \"children_map\"]\n\n\ndef main(files: List[pathlib.Path], name: str) -> None:\n \"\"\"Create samplesheet for list of files\"\"\"\n data = []\n for file in files:\n dir = file.parent\n id_ = dir.stem\n otu_table = dir / \"otu_table.tsv\"\n obs_metadata = dir / \"obs_metadata.tsv\"\n sample_metadata = dir / \"sample_metadata.tsv\"\n children_map = dir / \"children_map.json\"\n data.append(\n {\n \"id\": id_,\n \"otu_table\": otu_table,\n \"obs_metadata\": obs_metadata,\n \"sample_metadata\": sample_metadata,\n \"children_map\": children_map,\n }\n )\n df = pd.DataFrame(data, columns=HEADER)\n cwd = pathlib.Path(f\"../../pipeline/{name}\")\n df.to_csv(cwd / \"samplesheet.csv\", index=False, sep=\",\")\n\n\nif __name__ == \"__main__\":\n NORTA_FILES = list(pathlib.Path(\"../../data/norta/\").glob(\"**/otu_table.tsv\"))\n SEQTIME_FILES = list(pathlib.Path(\"../../data/seqtime/\").glob(\"**/otu_table.tsv\"))\n main(NORTA_FILES, \"norta\")\n main(SEQTIME_FILES, \"seqtime\")\n"
] | [
[
"pandas.DataFrame"
]
] |
SvtFilatov/PredictPricesSoccer | [
"ad50823ff49e696332c1a7e1e1b0559d6d5d511e"
] | [
"main.py"
] | [
"import streamlit as st\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom datetime import datetime\nimport warnings\nwarnings.filterwarnings('ignore')\nimport random\n\nst.title('ะัะพะณะฝะพะทะธัะพะฒะฐะฝะธะต ัะตะฝั ัััะฑะพะปะธััะพะฒ')\n\nst.markdown('ะฆะตะปัั ััะพะณะพ ะฟัะพะตัะฐ ะฑัะปะพ ะฟัะตะดัะบะฐะทะฐะฝะธะต ัะตะฝ ะฝะฐ ะผะพะปะพะดัั
ะฐัะฐะบัััะธั
ัััะฑะพะปะธััะพะฒ ะฟะพัะปะต ัะปะตะดัััะตะณะพ ัะตะทะพะฝะฐ. '\n 'ะัะฝะพะฒั ะพะฑััะฐััะตะน ะฒัะฑะพัะบะธ ัะพััะฐะฒะธะปะธ ะพะบะพะปะพ 400 ะธะณัะพะบะพะฒ ะธะท ัะพะฟ-5 ะะฒัะพะฟะตะนัะบะธั
ัััะฑะพะปัะฝัั
ะปะธะณ ะธ '\n 'ะ ะพััะธะนัะบะพะณะพ ัะตะผะฟะธะพะฝะฐัะฐ. ะฆะตะฝั ะฒัะตั
ัััะฑะพะปะธััะพะฒ ะฒะทััั ั ัะฐะนัะฐ [transfermarkt.com ](https://transfermarkt.com ). '\n 'ะะพะปะฝะพะต ะพะฟะธัะฐะฝะธะต ะฒัะตั
ััะฐะฟะพะฒ ะฟะพัััะพะตะฝะธั ะฟัะตะดัะบะฐะทะฐัะตะปัะฝะพะน ะผะพะดะตะปะธ ะพัะพะฒะฐะฝะฝะพะน ะฝะฐ ะผะฐัะธะฝะฝะพะผ ะพะฑััะตะฝะธะธ (ะธัะฟะพะปัะทะพะฒะฐะปัั ะณัะฐะดะธะตะฝัะฝัะน ะฑัััะธะฝะณ) '\n 'ะฒั ะฝะฐะนะดะตัะต ะฒ ัะพะพัะฒะตััะฒััััะตะผ Jupiter Notebook. ะญัะพ ะฒะตะฑ-ะฟัะธะปะพะถะตะฝะธะต ะถะต ะฒะธะทัะฐะปะธะทะธััะตั ะฟะพะปััะตะฝะฝัะต ัะตะทัะปััะฐัั. '\n 'ะัะฑะตัะธัะต ะธะฝัะตัะตััััะตะณะพ ะฒะฐั ะธะณัะพะบะฐ ะธ ัะทะฝะฐะนัะต ะบะฐะบ ะธะทะผะตะฝะธััั ะตะณะพ ัะตะฝะฐ ะฒ ัะตัะตะท ะณะพะด!')\ndata = pd.read_csv('final_predictions.csv')\ndata.price_predicted = data.price_predicted.apply(round)\n\ndef change_name(s):\n res = ''\n for a in s.split():\n res += a[0].capitalize()+a[1:]\n res += ' '\n return res[:-1]\n\ndata.player_name = data.player_name.apply(change_name)\n\nleagues = data.League.unique()\n\nteams_by_league = {}\nfor i in leagues:\n teams_by_league[i] = data[data['League'] == i]['team_title'].unique()\n\nplayer_by_team = {}\nfor j in data.team_title.unique():\n player_by_team[j] = data[data['team_title'] == j]['player_name'].unique()\n\ncol1, col2 = st.beta_columns(2)\n\nleague1 = col1.selectbox('First Player', leagues, index= 1)\nleague2 = col2.selectbox('Second Player', leagues, index = 1)\nteam1 = col1.selectbox('Pick club', teams_by_league[league1], index= 1)\nteam2 = col2.selectbox('Pick club', teams_by_league[league2], index= 2)\nif len(player_by_team[team1]) == 1:\n player1 = player_by_team[team1][0]\n col1.markdown(player1 + ' is the only player under 23')\n col1.markdown('in ' + team1)\nelse:\n player1 = col1.selectbox('Pick player', player_by_team[team1], index= 0)\n\nif len(player_by_team[team2]) == 1:\n player2 = player_by_team[team2][0]\n col2.markdown(player2 + ' is the only player under 23')\n col2.markdown('in ' + team2)\nelse:\n player2 = col2.selectbox('Pick player', player_by_team[team2], index= 1)\n\ndata['goals_90'] = (data['goals_season'] * 90) / data['time']\ndata['assists_90'] = (data['assists_season'] * 90) / data['time']\n\ncategories = ['xGBuildup 90', 'assists', 'xG 90', 'xA 90', 'goals']\nstats1 = list(data[data['player_name'] == player1][['xGBuildup_90','assists_90', 'npxG_season_90', 'xA_season_90', 'goals_90']].values[0])\n\nstats2 = list(data[data['player_name'] == player2][['xGBuildup_90', 'assists_90', 'npxG_season_90',\n 'xA_season_90', 'goals_90']].values[0])\nangles = list(np.linspace(0, 2 * np.pi, len(categories), endpoint=False))\nangles += angles[:1]\nstats1 += stats1[:1]\nstats2 += stats2[:1]\n\nfig = plt.figure()\nax = plt.subplot(111, polar=True)\n\nax.set_theta_offset(np.pi / 2) ###FROM: https://www.python-graph-gallery.com/391-radar-chart-with-several-individuals\nax.set_theta_direction(-1)\n\nplt.xticks(angles[:-1], categories)\n\nax.set_rlabel_position(0)\n\nmax_stat = np.max(stats1 + stats2) ###END FROM\n\nplt.yticks([max_stat * 0.25, max_stat * 0.5,\n max_stat * 0.75], [str(round(max_stat * 0.25, 2)), str(round(max_stat * 0.5, 2)),\n str(round(max_stat * 0.75, 2))], color=\"grey\", size=7)\nplt.ylim(0, max_stat)\n\nax.plot(angles, stats1, linewidth=1, linestyle='solid', label= player1)\nax.fill(angles, stats1, 'b', alpha=0.1)\n\nax.plot(angles, stats2, linewidth=1, linestyle='solid', label= player2)\nax.fill(angles, stats2, 'r', alpha=0.1)\n\nplt.legend(loc='lower left', bbox_to_anchor=(0.9, 0.9))\n\nst.pyplot(fig)\n\nplayer1_price = data[data['player_name'] == player1]['price_after_season']\nplayer2_price = data[data['player_name'] == player2]['price_after_season']\n\nplayer1_price_proj = data[data['player_name'] == player1]['price_predicted']\nplayer2_price_proj = data[data['player_name'] == player2]['price_predicted']\n\ncol11, col22 = st.beta_columns(2)\ncol11.write(player1 + ' ัะตะนัะฐั ััะพะธั ' + str(int(player1_price)) + ' ั. โฌ')\ncol11.write('ะะณะพ ะพะถะธะดะฐะตะผะฐั ัะตะฝะฐ ัะตัะตะท ะณะพะด - ' + str(int(player1_price_proj)) + ' ั. โฌ')\n\ncol22.write(player2 + ' ัะตะนัะฐั ััะพะธั ' + str(int(player2_price)) + ' ั. โฌ')\ncol22.write('ะะณะพ ะพะถะธะดะฐะตะผะฐั ัะตะฝะฐ ัะตัะตะท ะณะพะด - ' + str(int(player2_price_proj)) + ' ั. โฌ')\n\nst.write(\"ะะพะปั ะธ ะฐััะธััั ะฟัะธะฒะตะดะตะฝั ะธะท ัะฐััะตัะฐ ะฝะฐ 90 ะผะธะฝัั. ะก ะฟัะพะดะฒะธะฝััะพะน ััะฐัะธััะธะบะพะน ะผะพะถะฝะพ ะพะทะฝะฐะบะพะผะธัััั\"\n \"ะฝะฐ ัะฐะนัะต [understat.com](https://understat.com)\")\n\nst.write(\"ะะต ะทะฐะฑัะฒะฐะนัะต, ััะพ ััะพ ะผะธะฝะธ-ะฟัะธะปะพะถะตะฝะธะต - ะปะธัั ะธะฝััััะผะตะฝั ะฒะธะทัะฐะปะธะทะฐัะธะธ ัะตะทัะปััะฐัะพะฒ ะฟัะตะดัะบะฐะทะฐัะตะปัะฝะพะน ะผะพะดะตะปะธ. \"\n \"ะัะฝะพะฒะฝะฐั ัะฐััั ัะฐะฑะพัั ะฝะฐั
ะพะดะธััั ะฒ ะฟัะธะปะพะถะตะฝะฝะพะผ Jupiter Notebook\")\n#python -m streamlit run main.py\n\n"
] | [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.xticks",
"pandas.read_csv",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.subplot",
"numpy.max",
"matplotlib.pyplot.ylim"
]
] |
zhanglirong1999/YOLOX | [
"8b96c9c954e773a68cb439506bedd3b80406cc7d"
] | [
"yolox/models/yolo_head.py"
] | [
"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# Copyright (c) Megvii Inc. All rights reserved.\n\nimport math\nfrom loguru import logger\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom yolox.utils import bboxes_iou, meshgrid\n\nfrom .losses import IOUloss\nfrom .network_blocks import BaseConv, DWConv\n\n\nclass YOLOXHead(nn.Module):\n def __init__(\n self,\n num_classes,\n width=1.0,\n strides=[8, 16, 32],\n in_channels=[256, 512, 1024],\n act=\"silu\",\n depthwise=False,\n ):\n \"\"\"\n Args:\n act (str): activation type of conv. Defalut value: \"silu\".\n depthwise (bool): whether apply depthwise conv in conv branch. Defalut value: False.\n \"\"\"\n super().__init__()\n\n self.n_anchors = 1\n self.num_classes = num_classes\n self.decode_in_inference = True # for deploy, set to False\n\n self.cls_convs = nn.ModuleList()\n self.reg_convs = nn.ModuleList()\n self.cls_preds = nn.ModuleList()\n self.reg_preds = nn.ModuleList()\n self.obj_preds = nn.ModuleList()\n self.stems = nn.ModuleList()\n Conv = DWConv if depthwise else BaseConv\n\n for i in range(len(in_channels)):\n self.stems.append(\n BaseConv(\n in_channels=int(in_channels[i] * width),\n out_channels=int(256 * width),\n ksize=1,\n stride=1,\n act=act,\n )\n )\n self.cls_convs.append(\n nn.Sequential(\n *[\n Conv(\n in_channels=int(256 * width),\n out_channels=int(256 * width),\n ksize=3,\n stride=1,\n act=act,\n ),\n Conv(\n in_channels=int(256 * width),\n out_channels=int(256 * width),\n ksize=3,\n stride=1,\n act=act,\n ),\n ]\n )\n )\n self.reg_convs.append(\n nn.Sequential(\n *[\n Conv(\n in_channels=int(256 * width),\n out_channels=int(256 * width),\n ksize=3,\n stride=1,\n act=act,\n ),\n Conv(\n in_channels=int(256 * width),\n out_channels=int(256 * width),\n ksize=3,\n stride=1,\n act=act,\n ),\n ]\n )\n )\n self.cls_preds.append(\n nn.Conv2d(\n in_channels=int(256 * width),\n out_channels=self.n_anchors * self.num_classes,\n kernel_size=1,\n stride=1,\n padding=0,\n )\n )\n self.reg_preds.append(\n nn.Conv2d(\n in_channels=int(256 * width),\n out_channels=4,\n kernel_size=1,\n stride=1,\n padding=0,\n )\n )\n self.obj_preds.append(\n nn.Conv2d(\n in_channels=int(256 * width),\n out_channels=self.n_anchors * 1,\n kernel_size=1,\n stride=1,\n padding=0,\n )\n )\n\n self.use_l1 = False\n self.l1_loss = nn.L1Loss(reduction=\"none\")\n self.bcewithlog_loss = nn.BCEWithLogitsLoss(reduction=\"none\")\n self.iou_loss = IOUloss(reduction=\"none\")\n self.strides = strides\n self.grids = [torch.zeros(1)] * len(in_channels)\n\n def initialize_biases(self, prior_prob):\n for conv in self.cls_preds:\n b = conv.bias.view(self.n_anchors, -1)\n b.data.fill_(-math.log((1 - prior_prob) / prior_prob))\n conv.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)\n\n for conv in self.obj_preds:\n b = conv.bias.view(self.n_anchors, -1)\n b.data.fill_(-math.log((1 - prior_prob) / prior_prob))\n conv.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)\n\n def forward(self, xin, labels=None, imgs=None):\n outputs = []\n origin_preds = []\n x_shifts = []\n y_shifts = []\n expanded_strides = []\n\n for k, (cls_conv, reg_conv, stride_this_level, x) in enumerate(\n zip(self.cls_convs, self.reg_convs, self.strides, xin)\n ):\n x = self.stems[k](x)\n cls_x = x\n reg_x = x\n\n cls_feat = cls_conv(cls_x)\n cls_output = self.cls_preds[k](cls_feat)\n\n reg_feat = reg_conv(reg_x)\n reg_output = self.reg_preds[k](reg_feat)\n obj_output = self.obj_preds[k](reg_feat)\n\n if self.training:\n output = torch.cat([reg_output, obj_output, cls_output], 1)\n output, grid = self.get_output_and_grid(\n output, k, stride_this_level, xin[0].type()\n )\n x_shifts.append(grid[:, :, 0])\n y_shifts.append(grid[:, :, 1])\n expanded_strides.append(\n torch.zeros(1, grid.shape[1])\n .fill_(stride_this_level)\n .type_as(xin[0])\n )\n if self.use_l1:\n batch_size = reg_output.shape[0]\n hsize, wsize = reg_output.shape[-2:]\n reg_output = reg_output.view(\n batch_size, self.n_anchors, 4, hsize, wsize\n )\n reg_output = reg_output.permute(0, 1, 3, 4, 2).reshape(\n batch_size, -1, 4\n )\n origin_preds.append(reg_output.clone())\n\n else:\n output = torch.cat(\n [reg_output, obj_output.sigmoid(), cls_output.sigmoid()], 1\n )\n\n outputs.append(output)\n\n if self.training:\n return self.get_losses(\n imgs,\n x_shifts,\n y_shifts,\n expanded_strides,\n labels,\n torch.cat(outputs, 1),\n origin_preds,\n dtype=xin[0].dtype,\n )\n else:\n self.hw = [x.shape[-2:] for x in outputs]\n # [batch, n_anchors_all, 85]\n outputs = torch.cat(\n [x.flatten(start_dim=2) for x in outputs], dim=2\n ).permute(0, 2, 1)\n if self.decode_in_inference:\n return self.decode_outputs(outputs, dtype=xin[0].type())\n else:\n return outputs\n\n def get_output_and_grid(self, output, k, stride, dtype):\n grid = self.grids[k]\n\n batch_size = output.shape[0]\n n_ch = 5 + self.num_classes\n hsize, wsize = output.shape[-2:]\n if grid.shape[2:4] != output.shape[2:4]:\n yv, xv = meshgrid([torch.arange(hsize), torch.arange(wsize)])\n grid = torch.stack((xv, yv), 2).view(1, 1, hsize, wsize, 2).type(dtype)\n self.grids[k] = grid\n\n output = output.view(batch_size, self.n_anchors, n_ch, hsize, wsize)\n output = output.permute(0, 1, 3, 4, 2).reshape(\n batch_size, self.n_anchors * hsize * wsize, -1\n )\n grid = grid.view(1, -1, 2)\n output[..., :2] = (output[..., :2] + grid) * stride\n output[..., 2:4] = torch.exp(output[..., 2:4]) * stride\n return output, grid\n\n def decode_outputs(self, outputs, dtype):\n grids = []\n strides = []\n for (hsize, wsize), stride in zip(self.hw, self.strides):\n yv, xv = meshgrid([torch.arange(hsize), torch.arange(wsize)])\n grid = torch.stack((xv, yv), 2).view(1, -1, 2)\n grids.append(grid)\n shape = grid.shape[:2]\n strides.append(torch.full((*shape, 1), stride))\n\n grids = torch.cat(grids, dim=1).type(dtype)\n strides = torch.cat(strides, dim=1).type(dtype)\n\n outputs[..., :2] = (outputs[..., :2] + grids) * strides\n outputs[..., 2:4] = torch.exp(outputs[..., 2:4]) * strides\n return outputs\n\n def get_losses(\n self,\n imgs,\n x_shifts,\n y_shifts,\n expanded_strides,\n labels,\n outputs,\n origin_preds,\n dtype,\n ):\n bbox_preds = outputs[:, :, :4] # [batch, n_anchors_all, 4]\n obj_preds = outputs[:, :, 4].unsqueeze(-1) # [batch, n_anchors_all, 1]\n cls_preds = outputs[:, :, 5:] # [batch, n_anchors_all, n_cls]\n\n # calculate targets\n nlabel = (labels.sum(dim=2) > 0).sum(dim=1) # number of objects\n\n total_num_anchors = outputs.shape[1]\n x_shifts = torch.cat(x_shifts, 1) # [1, n_anchors_all]\n y_shifts = torch.cat(y_shifts, 1) # [1, n_anchors_all]\n expanded_strides = torch.cat(expanded_strides, 1)\n if self.use_l1:\n origin_preds = torch.cat(origin_preds, 1)\n\n cls_targets = []\n reg_targets = []\n l1_targets = []\n obj_targets = []\n fg_masks = []\n\n num_fg = 0.0\n num_gts = 0.0\n\n for batch_idx in range(outputs.shape[0]):\n num_gt = int(nlabel[batch_idx])\n num_gts += num_gt\n if num_gt == 0:\n cls_target = outputs.new_zeros((0, self.num_classes))\n reg_target = outputs.new_zeros((0, 4))\n l1_target = outputs.new_zeros((0, 4))\n obj_target = outputs.new_zeros((total_num_anchors, 1))\n fg_mask = outputs.new_zeros(total_num_anchors).bool()\n else:\n gt_bboxes_per_image = labels[batch_idx, :num_gt, 1:5]\n gt_classes = labels[batch_idx, :num_gt, 0]\n bboxes_preds_per_image = bbox_preds[batch_idx]\n\n try:\n (\n gt_matched_classes,\n fg_mask,\n pred_ious_this_matching,\n matched_gt_inds,\n num_fg_img,\n ) = self.get_assignments( # noqa\n batch_idx,\n num_gt,\n total_num_anchors,\n gt_bboxes_per_image,\n gt_classes,\n bboxes_preds_per_image,\n expanded_strides,\n x_shifts,\n y_shifts,\n cls_preds,\n bbox_preds,\n obj_preds,\n labels,\n imgs,\n )\n except RuntimeError as e:\n # TODO: the string might change, consider a better way\n if \"CUDA out of memory. \" not in str(e):\n raise # RuntimeError might not caused by CUDA OOM\n\n logger.error(\n \"OOM RuntimeError is raised due to the huge memory cost during label assignment. \\\n CPU mode is applied in this batch. If you want to avoid this issue, \\\n try to reduce the batch size or image size.\"\n )\n torch.cuda.empty_cache()\n (\n gt_matched_classes,\n fg_mask,\n pred_ious_this_matching,\n matched_gt_inds,\n num_fg_img,\n ) = self.get_assignments( # noqa\n batch_idx,\n num_gt,\n total_num_anchors,\n gt_bboxes_per_image,\n gt_classes,\n bboxes_preds_per_image,\n expanded_strides,\n x_shifts,\n y_shifts,\n cls_preds,\n bbox_preds,\n obj_preds,\n labels,\n imgs,\n \"cpu\",\n )\n\n torch.cuda.empty_cache()\n num_fg += num_fg_img\n\n cls_target = F.one_hot(\n gt_matched_classes.to(torch.int64), self.num_classes\n ) * pred_ious_this_matching.unsqueeze(-1)\n obj_target = fg_mask.unsqueeze(-1)\n reg_target = gt_bboxes_per_image[matched_gt_inds]\n if self.use_l1:\n l1_target = self.get_l1_target(\n outputs.new_zeros((num_fg_img, 4)),\n gt_bboxes_per_image[matched_gt_inds],\n expanded_strides[0][fg_mask],\n x_shifts=x_shifts[0][fg_mask],\n y_shifts=y_shifts[0][fg_mask],\n )\n\n cls_targets.append(cls_target)\n reg_targets.append(reg_target)\n obj_targets.append(obj_target.to(dtype))\n fg_masks.append(fg_mask)\n if self.use_l1:\n l1_targets.append(l1_target)\n\n cls_targets = torch.cat(cls_targets, 0)\n reg_targets = torch.cat(reg_targets, 0)\n obj_targets = torch.cat(obj_targets, 0)\n fg_masks = torch.cat(fg_masks, 0)\n if self.use_l1:\n l1_targets = torch.cat(l1_targets, 0)\n\n num_fg = max(num_fg, 1)\n loss_iou = (\n self.iou_loss(bbox_preds.view(-1, 4)[fg_masks], reg_targets)\n ).sum() / num_fg\n loss_obj = (\n self.bcewithlog_loss(obj_preds.view(-1, 1), obj_targets)\n ).sum() / num_fg\n loss_cls = (\n self.bcewithlog_loss(\n cls_preds.view(-1, self.num_classes)[fg_masks], cls_targets\n )\n ).sum() / num_fg\n if self.use_l1:\n loss_l1 = (\n self.l1_loss(origin_preds.view(-1, 4)[fg_masks], l1_targets)\n ).sum() / num_fg\n else:\n loss_l1 = 0.0\n\n reg_weight = 5.0\n loss = reg_weight * loss_iou + loss_obj + loss_cls + loss_l1\n\n return (\n loss,\n reg_weight * loss_iou,\n loss_obj,\n loss_cls,\n loss_l1,\n num_fg / max(num_gts, 1),\n )\n\n def get_l1_target(self, l1_target, gt, stride, x_shifts, y_shifts, eps=1e-8):\n l1_target[:, 0] = gt[:, 0] / stride - x_shifts\n l1_target[:, 1] = gt[:, 1] / stride - y_shifts\n l1_target[:, 2] = torch.log(gt[:, 2] / stride + eps)\n l1_target[:, 3] = torch.log(gt[:, 3] / stride + eps)\n return l1_target\n\n @torch.no_grad()\n def get_assignments(\n self,\n batch_idx,\n num_gt,\n total_num_anchors,\n gt_bboxes_per_image,\n gt_classes,\n bboxes_preds_per_image,\n expanded_strides,\n x_shifts,\n y_shifts,\n cls_preds,\n bbox_preds,\n obj_preds,\n labels,\n imgs,\n mode=\"gpu\",\n ):\n\n if mode == \"cpu\":\n print(\"------------CPU Mode for This Batch-------------\")\n gt_bboxes_per_image = gt_bboxes_per_image.cpu().float()\n bboxes_preds_per_image = bboxes_preds_per_image.cpu().float()\n gt_classes = gt_classes.cpu().float()\n expanded_strides = expanded_strides.cpu().float()\n x_shifts = x_shifts.cpu()\n y_shifts = y_shifts.cpu()\n\n fg_mask, is_in_boxes_and_center = self.get_in_boxes_info(\n gt_bboxes_per_image,\n expanded_strides,\n x_shifts,\n y_shifts,\n total_num_anchors,\n num_gt,\n )\n\n bboxes_preds_per_image = bboxes_preds_per_image[fg_mask]\n cls_preds_ = cls_preds[batch_idx][fg_mask]\n obj_preds_ = obj_preds[batch_idx][fg_mask]\n num_in_boxes_anchor = bboxes_preds_per_image.shape[0]\n\n if mode == \"cpu\":\n gt_bboxes_per_image = gt_bboxes_per_image.cpu()\n bboxes_preds_per_image = bboxes_preds_per_image.cpu()\n\n pair_wise_ious = bboxes_iou(gt_bboxes_per_image, bboxes_preds_per_image, False)\n\n gt_cls_per_image = (\n F.one_hot(gt_classes.to(torch.int64), self.num_classes)\n .float()\n .unsqueeze(1)\n .repeat(1, num_in_boxes_anchor, 1)\n )\n pair_wise_ious_loss = -torch.log(pair_wise_ious + 1e-8)\n\n if mode == \"cpu\":\n cls_preds_, obj_preds_ = cls_preds_.cpu(), obj_preds_.cpu()\n\n with torch.cuda.amp.autocast(enabled=False):\n cls_preds_ = (\n cls_preds_.float().unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()\n * obj_preds_.float().unsqueeze(0).repeat(num_gt, 1, 1).sigmoid_()\n )\n pair_wise_cls_loss = F.binary_cross_entropy(\n cls_preds_.sqrt_(), gt_cls_per_image, reduction=\"none\"\n ).sum(-1)\n del cls_preds_\n\n cost = (\n pair_wise_cls_loss\n + 3.0 * pair_wise_ious_loss\n + 100000.0 * (~is_in_boxes_and_center)\n )\n\n (\n num_fg,\n gt_matched_classes,\n pred_ious_this_matching,\n matched_gt_inds,\n ) = self.dynamic_k_matching(cost, pair_wise_ious, gt_classes, num_gt, fg_mask)\n del pair_wise_cls_loss, cost, pair_wise_ious, pair_wise_ious_loss\n\n if mode == \"cpu\":\n gt_matched_classes = gt_matched_classes.cpu()\n fg_mask = fg_mask.cpu()\n pred_ious_this_matching = pred_ious_this_matching.cpu()\n matched_gt_inds = matched_gt_inds.cpu()\n\n return (\n gt_matched_classes,\n fg_mask,\n pred_ious_this_matching,\n matched_gt_inds,\n num_fg,\n )\n\n def get_in_boxes_info(\n self,\n gt_bboxes_per_image,\n expanded_strides,\n x_shifts,\n y_shifts,\n total_num_anchors,\n num_gt,\n ):\n expanded_strides_per_image = expanded_strides[0]\n x_shifts_per_image = x_shifts[0] * expanded_strides_per_image\n y_shifts_per_image = y_shifts[0] * expanded_strides_per_image\n x_centers_per_image = (\n (x_shifts_per_image + 0.5 * expanded_strides_per_image)\n .unsqueeze(0)\n .repeat(num_gt, 1)\n ) # [n_anchor] -> [n_gt, n_anchor]\n y_centers_per_image = (\n (y_shifts_per_image + 0.5 * expanded_strides_per_image)\n .unsqueeze(0)\n .repeat(num_gt, 1)\n )\n\n gt_bboxes_per_image_l = (\n (gt_bboxes_per_image[:, 0] - 0.5 * gt_bboxes_per_image[:, 2])\n .unsqueeze(1)\n .repeat(1, total_num_anchors)\n )\n gt_bboxes_per_image_r = (\n (gt_bboxes_per_image[:, 0] + 0.5 * gt_bboxes_per_image[:, 2])\n .unsqueeze(1)\n .repeat(1, total_num_anchors)\n )\n gt_bboxes_per_image_t = (\n (gt_bboxes_per_image[:, 1] - 0.5 * gt_bboxes_per_image[:, 3])\n .unsqueeze(1)\n .repeat(1, total_num_anchors)\n )\n gt_bboxes_per_image_b = (\n (gt_bboxes_per_image[:, 1] + 0.5 * gt_bboxes_per_image[:, 3])\n .unsqueeze(1)\n .repeat(1, total_num_anchors)\n )\n\n b_l = x_centers_per_image - gt_bboxes_per_image_l\n b_r = gt_bboxes_per_image_r - x_centers_per_image\n b_t = y_centers_per_image - gt_bboxes_per_image_t\n b_b = gt_bboxes_per_image_b - y_centers_per_image\n bbox_deltas = torch.stack([b_l, b_t, b_r, b_b], 2)\n\n is_in_boxes = bbox_deltas.min(dim=-1).values > 0.0\n is_in_boxes_all = is_in_boxes.sum(dim=0) > 0\n # in fixed center\n\n center_radius = 2.5\n\n gt_bboxes_per_image_l = (gt_bboxes_per_image[:, 0]).unsqueeze(1).repeat(\n 1, total_num_anchors\n ) - center_radius * expanded_strides_per_image.unsqueeze(0)\n gt_bboxes_per_image_r = (gt_bboxes_per_image[:, 0]).unsqueeze(1).repeat(\n 1, total_num_anchors\n ) + center_radius * expanded_strides_per_image.unsqueeze(0)\n gt_bboxes_per_image_t = (gt_bboxes_per_image[:, 1]).unsqueeze(1).repeat(\n 1, total_num_anchors\n ) - center_radius * expanded_strides_per_image.unsqueeze(0)\n gt_bboxes_per_image_b = (gt_bboxes_per_image[:, 1]).unsqueeze(1).repeat(\n 1, total_num_anchors\n ) + center_radius * expanded_strides_per_image.unsqueeze(0)\n\n c_l = x_centers_per_image - gt_bboxes_per_image_l\n c_r = gt_bboxes_per_image_r - x_centers_per_image\n c_t = y_centers_per_image - gt_bboxes_per_image_t\n c_b = gt_bboxes_per_image_b - y_centers_per_image\n center_deltas = torch.stack([c_l, c_t, c_r, c_b], 2)\n is_in_centers = center_deltas.min(dim=-1).values > 0.0\n is_in_centers_all = is_in_centers.sum(dim=0) > 0\n\n # in boxes and in centers\n is_in_boxes_anchor = is_in_boxes_all | is_in_centers_all\n\n is_in_boxes_and_center = (\n is_in_boxes[:, is_in_boxes_anchor] & is_in_centers[:, is_in_boxes_anchor]\n )\n return is_in_boxes_anchor, is_in_boxes_and_center\n\n def dynamic_k_matching(self, cost, pair_wise_ious, gt_classes, num_gt, fg_mask):\n # Dynamic K\n # ---------------------------------------------------------------\n matching_matrix = torch.zeros_like(cost, dtype=torch.uint8)\n\n ious_in_boxes_matrix = pair_wise_ious\n n_candidate_k = min(10, ious_in_boxes_matrix.size(1))\n topk_ious, _ = torch.topk(ious_in_boxes_matrix, n_candidate_k, dim=1)\n dynamic_ks = torch.clamp(topk_ious.sum(1).int(), min=1)\n dynamic_ks = dynamic_ks.tolist()\n for gt_idx in range(num_gt):\n _, pos_idx = torch.topk(\n cost[gt_idx], k=dynamic_ks[gt_idx], largest=False\n )\n matching_matrix[gt_idx][pos_idx] = 1\n\n del topk_ious, dynamic_ks, pos_idx\n\n anchor_matching_gt = matching_matrix.sum(0)\n if (anchor_matching_gt > 1).sum() > 0:\n _, cost_argmin = torch.min(cost[:, anchor_matching_gt > 1], dim=0)\n matching_matrix[:, anchor_matching_gt > 1] *= 0\n matching_matrix[cost_argmin, anchor_matching_gt > 1] = 1\n fg_mask_inboxes = matching_matrix.sum(0) > 0\n num_fg = fg_mask_inboxes.sum().item()\n\n fg_mask[fg_mask.clone()] = fg_mask_inboxes\n\n matched_gt_inds = matching_matrix[:, fg_mask_inboxes].argmax(0)\n gt_matched_classes = gt_classes[matched_gt_inds]\n\n pred_ious_this_matching = (matching_matrix * pair_wise_ious).sum(0)[\n fg_mask_inboxes\n ]\n return num_fg, gt_matched_classes, pred_ious_this_matching, matched_gt_inds\n"
] | [
[
"torch.cuda.empty_cache",
"torch.min",
"torch.stack",
"torch.nn.L1Loss",
"torch.no_grad",
"torch.zeros_like",
"torch.full",
"torch.exp",
"torch.topk",
"torch.log",
"torch.nn.ModuleList",
"torch.cuda.amp.autocast",
"torch.nn.BCEWithLogitsLoss",
"torch.arange",
"torch.zeros",
"torch.cat"
]
] |
svecjan/pytorch | [
"09d221e8d439bc748b162c028f7eece202688adf"
] | [
"torch/utils/data/datapipes/dataframe/datapipes.py"
] | [
"import random\n\nfrom torch.utils.data import (\n DFIterDataPipe,\n IterDataPipe,\n functional_datapipe,\n)\n\ntry:\n import pandas # type: ignore[import]\n # pandas used only for prototyping, will be shortly replaced with TorchArrow\n WITH_PANDAS = True\nexcept ImportError:\n WITH_PANDAS = False\n\n\n@functional_datapipe('_dataframes_as_tuples')\nclass DataFramesAsTuplesPipe(IterDataPipe):\n def __init__(self, source_datapipe):\n self.source_datapipe = source_datapipe\n\n def __iter__(self):\n for df in self.source_datapipe:\n for record in df.to_records(index=False):\n yield record\n\n\n@functional_datapipe('_dataframes_per_row', enable_df_api_tracing=True)\nclass PerRowDataFramesPipe(DFIterDataPipe):\n def __init__(self, source_datapipe):\n self.source_datapipe = source_datapipe\n\n def __iter__(self):\n for df in self.source_datapipe:\n for i in range(len(df.index)):\n yield df[i:i + 1]\n\n\n@functional_datapipe('_dataframes_concat', enable_df_api_tracing=True)\nclass ConcatDataFramesPipe(DFIterDataPipe):\n def __init__(self, source_datapipe, batch=3):\n self.source_datapipe = source_datapipe\n self.batch = batch\n if not WITH_PANDAS:\n Exception('DataFrames prototype requires pandas to function')\n\n def __iter__(self):\n buffer = []\n for df in self.source_datapipe:\n buffer.append(df)\n if len(buffer) == self.batch:\n yield pandas.concat(buffer)\n buffer = []\n if len(buffer):\n yield pandas.concat(buffer)\n\n\n@functional_datapipe('_dataframes_shuffle', enable_df_api_tracing=True)\nclass ShuffleDataFramesPipe(DFIterDataPipe):\n def __init__(self, source_datapipe):\n self.source_datapipe = source_datapipe\n if not WITH_PANDAS:\n Exception('DataFrames prototype requires pandas to function')\n\n def __iter__(self):\n size = None\n all_buffer = []\n for df in self.source_datapipe:\n if size is None:\n size = len(df.index)\n for i in range(len(df.index)):\n all_buffer.append(df[i:i + 1])\n random.shuffle(all_buffer)\n buffer = []\n for df in all_buffer:\n buffer.append(df)\n if len(buffer) == size:\n yield pandas.concat(buffer)\n buffer = []\n if len(buffer):\n yield pandas.concat(buffer)\n\n\n@functional_datapipe('_dataframes_filter', enable_df_api_tracing=True)\nclass FilterDataFramesPipe(DFIterDataPipe):\n def __init__(self, source_datapipe, filter_fn):\n self.source_datapipe = source_datapipe\n self.filter_fn = filter_fn\n if not WITH_PANDAS:\n Exception('DataFrames prototype requires pandas to function')\n\n def __iter__(self):\n size = None\n all_buffer = []\n filter_res = []\n for df in self.source_datapipe:\n if size is None:\n size = len(df.index)\n for i in range(len(df.index)):\n all_buffer.append(df[i:i + 1])\n filter_res.append(self.filter_fn(df.iloc[i]))\n\n buffer = []\n for df, res in zip(all_buffer, filter_res):\n if res:\n buffer.append(df)\n if len(buffer) == size:\n yield pandas.concat(buffer)\n buffer = []\n if len(buffer):\n yield pandas.concat(buffer)\n\n\n@functional_datapipe('_to_dataframes_pipe', enable_df_api_tracing=True)\nclass ExampleAggregateAsDataFrames(DFIterDataPipe):\n def __init__(self, source_datapipe, dataframe_size=10, columns=None):\n self.source_datapipe = source_datapipe\n self.columns = columns\n self.dataframe_size = dataframe_size\n if not WITH_PANDAS:\n Exception('DataFrames prototype requires pandas to function')\n\n def _as_list(self, item):\n try:\n return list(item)\n except Exception: # TODO(VitalyFedyunin): Replace with better iterable exception\n return [item]\n\n def __iter__(self):\n aggregate = []\n for item in self.source_datapipe:\n aggregate.append(self._as_list(item))\n if len(aggregate) == self.dataframe_size:\n yield pandas.DataFrame(aggregate, columns=self.columns)\n aggregate = []\n if len(aggregate) > 0:\n yield pandas.DataFrame(aggregate, columns=self.columns)\n"
] | [
[
"torch.utils.data.functional_datapipe",
"pandas.DataFrame",
"pandas.concat"
]
] |
seeclong/apollo | [
"99c8afb5ebcae2a3c9359a156a957ff03944b27b"
] | [
"modules/tools/mapshow/roadshow.py"
] | [
"#!/usr/bin/env python\n\n###############################################################################\n# Copyright 2017 The Apollo 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\nimport argparse\nimport matplotlib.pyplot as plt\nfrom libs.map import Map\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Raodshow is a tool to display road info on a map.\",\n prog=\"roadshow.py\")\n\n parser.add_argument(\n \"-m\", \"--map\", action=\"store\", type=str, required=True,\n help=\"Specify the map file in txt or binary format\")\n\n args = parser.parse_args()\n\n map = Map()\n map.load(args.map)\n map.draw_roads(plt)\n\n plt.axis('equal')\n plt.show()\n"
] | [
[
"matplotlib.pyplot.axis",
"matplotlib.pyplot.show"
]
] |
awesome-archive/Py3plex | [
"a099acb992441c1630208ba13694acb8e2a38895"
] | [
"py3plex/core/HINMINE/dataStructures.py"
] | [
"## core data structures\n\nimport networkx as nx\nimport numpy as np\nimport scipy.sparse as sp\nfrom .decomposition import get_calculation_method\n\nclass Class:\n def __init__(self, lab_id, name, members):\n self.name = name\n self.id = lab_id\n self.index = -1\n self.members = members # ids of members calculated using hierarchy of labels\n self.member_indices = []\n self.train_indices = [] # indices of training instances with this label\n self.validate_indices = [] # indices of validate instances with this label\n self.test_indices = [] # indices of test instances with this label\n self.train_members = set() # ids of train members (intersection of basic_members and the train set)\n self.test_members = set() # ids of test members (intersection of basic_members and the test set)\n self.validate_members = set() # ids of validate members (intersection of basic_members and the validate set)\n self.not_test_members = set()\n\n def __repr__(self):\n return self.name\n\n def __str__(self):\n return self.name\n\n\nclass HeterogeneousInformationNetwork:\n def __init__(self, network, label_delimiter, weight_tag=False, target_tag=True):\n self.label_list = [] # list of labels.\n self.labels_by_id = {} # IDs of each label\n self.graph = network\n self.target_tag = target_tag\n self.node_list = [] # List of all nodes in decomposition\n self.node_indices = {} # Indices of all nodes in decomposition\n self.basic_type = None # Basic node type (for decomposition)\n self.label_array = None\n self.label_matrix = None\n\n self.train_indices = []\n self.validate_indices = []\n self.test_indices = []\n self.train_ids = set()\n self.validate_ids = set()\n self.test_ids = set()\n\n self.weighted = weight_tag ## include info on weighted edges\n \n self.decomposed = {} # Dictionary of all performed decompositions (self.decomposed['PAP'] is one)\n self.pairs = {}\n self.midpoints = {}\n\n self.validate_pprs = {}\n self.test_pprs = {}\n self.train_pprs = {}\n\n self.validate_distances = {}\n self.test_distances = {}\n\n self.midpoint_files = {}\n self.feature_vectors = {}\n if network != None: \n self.process_network(label_delimiter)\n\n def add_label(self, node, label_id, label_name=None):\n if label_name is None:\n label_name = str(label_id)\n if label_id in self.labels_by_id:\n if self.labels_by_id[label_id] not in self.graph.node[node]['labels']:\n self.graph.node[node]['labels'].append(self.labels_by_id[label_id])\n self.labels_by_id[label_id].members.append(node)\n else:\n new_class = Class(label_id, label_name, [node])\n self.label_list.append(new_class)\n self.labels_by_id[label_id] = new_class\n new_class.index = len(self.label_list) - 1\n self.graph.node[node]['labels'].append(new_class)\n\n def process_network(self, label_delimiter): \n if self.target_tag:\n basic_types = set([self.graph.node[x]['type'] for x in self.graph.node if 'labels' in self.graph.node[x]])\n \n print(\"Target type: {}\".format(basic_types))\n if len(basic_types) != 1:\n ## tukej naredi, da enostavno sejvne grafek, to je uporabno za embedding\n print(basic_types)\n raise Exception('Unclear target type!')\n\n self.basic_type = basic_types.pop() \n self.node_list = [x for x in self.graph.node if self.graph.node[x]['type'] == self.basic_type]\n try:\n self.node_list.sort(key=lambda x: float(x[0]))\n except ValueError:\n self.node_list.sort()\n self.node_indices = dict([(item, index) for index, item in enumerate(self.node_list)])\n\n for node_id in self.node_list:\n if 'labels' in self.graph.node[node_id]:\n if len(self.graph.node[node_id]['labels']) > 0:\n labels = self.graph.node[node_id]['labels'].split(label_delimiter)\n self.graph.node[node_id]['labels'] = []\n for label in labels:\n self.add_label(node_id, label, label_name=label)\n else:\n pass\n \n for lab in self.label_list:\n if lab is not None:\n temp_list = [mem for mem in lab.members if self.graph.node[mem]['type'] == self.basic_type]\n lab.basic_members = set(temp_list)\n self.label_array = - np.ones((max([len(self.graph.node[node]['labels']) for node in self.node_list]), len(self.node_list)))\n for node in self.node_list:\n tmp = self.graph.node[node]['labels']\n self.label_array[:len(tmp), self.node_indices[node]] = [label.index for label in tmp]\n self.create_label_matrix()\n\n def create_label_matrix(self, weights=None):\n\n self.label_matrix = np.zeros((len(self.node_list), len(self.label_list)))\n for i, label in enumerate(self.label_list):\n member_indices = [self.node_indices[x] for x in label.members]\n if weights == 'balanced':\n self.label_matrix[member_indices, i] = 1.0 / max(len(label.train_indices), 1)\n else:\n self.label_matrix[member_indices, i] = 1\n\n \n\n def calculate_schema(self):\n schema = nx.MultiDiGraph()\n for node_start in self.graph.node:\n for node_end in self.graph[node_start]:\n for key in self.graph[node_start][node_end]:\n# print(node_start,node_end,key,self.graph[node_start][node_end])\n start_type = self.graph.node[node_start]['type']\n end_type = self.graph.node[node_end]['type']\n edge_type = self.graph[node_start][node_end][key]['type']\n has_type = False\n if schema.has_edge(start_type, end_type):\n for key in schema[start_type][end_type]:\n if schema[start_type][end_type][key]['type'] == edge_type:\n has_type = True\n break\n # if schema[start_type][end_type]['type'] != edge_type:\n # raise Exception('Multiple edge types between equal node types are not supported!')\n if not has_type:\n schema.add_edge(start_type, end_type, type=edge_type)\n return schema\n\n def calculate_decomposition_candidates(self, max_decomposition_length=10):\n schema = self.calculate_schema()\n under_construction = [{'node_list': [self.basic_type], 'edge_list': []}]\n candidate_lists = []\n for i in range(max_decomposition_length - 1):\n next_gens = []\n for list_so_far in under_construction:\n if list_so_far['node_list'][-1] != self.basic_type or len(list_so_far['node_list']) == 1:\n current = list_so_far['node_list'][-1]\n for neighbor in schema[current]:\n if neighbor == self.basic_type:\n append_to = candidate_lists\n else:\n append_to = next_gens\n for key in schema[current][neighbor]:\n append_to.append({\n 'node_list': list_so_far['node_list'] + [neighbor],\n 'edge_list': list_so_far['edge_list'] + [schema[current][neighbor][key]['type']]\n })\n under_construction = next_gens\n return candidate_lists\n\n def split_to_indices(self, train_indices=(), validate_indices=(), test_indices=()):\n self.train_indices = train_indices\n self.validate_indices = validate_indices\n self.test_indices = test_indices\n\n self.train_ids = set([self.node_list[i] for i in self.train_indices])\n self.validate_ids = set([self.node_list[i] for i in self.validate_indices])\n self.test_ids = set([self.node_list[i] for i in self.test_indices])\n\n # calculate test representatives:\n for train_index in self.train_indices:\n train_node = self.node_list[train_index]\n for label in self.graph.node[train_node]['labels']:\n label.train_indices.append(train_index)\n label.train_members.add(self.node_list[train_index])\n label.not_test_members.add(self.node_list[train_index])\n for validate_index in self.validate_indices:\n validate_node = self.node_list[validate_index]\n for label in self.graph.node[validate_node]['labels']:\n label.validate_indices.append(validate_index)\n label.validate_members.add(self.node_list[validate_index])\n label.not_test_members.add(self.node_list[validate_index])\n for test_index in self.test_indices:\n test_node = self.node_list[test_index]\n for label in self.graph.node[test_node]['labels']:\n label.test_indices.append(test_index)\n label.test_members.add(self.node_list[test_index])\n for label in self.label_list:\n label.not_test_members_num = len(label.not_test_members)\n\n def split_to_parts(self,lst,n):\n return [lst[i::n] for i in range(n)]\n \n\n def decompose_from_iterator(self, name, weighing, summing ,generator=None, degrees=None, parallel=True,pool=None):\n classes = [lab for lab in self.label_list if lab and len(lab.not_test_members) > 0]\n universal_set = list(set(self.train_ids).union(self.validate_ids))\n universal_inv = {}\n for i, item in enumerate(universal_set):\n universal_inv[item] = i\n universal_set = set(universal_set)\n label_matrix = np.zeros((len(universal_set), len(classes)))\n for i, label in enumerate(classes):\n label_matrix[[universal_inv[item] for item in label.not_test_members], i] = 1\n nn = len(self.node_list)\n matrix = sp.csr_matrix((nn, nn))\n n = len(universal_set)\n \n importance_calculator = get_calculation_method(weighing)\n if generator is None:\n raise Exception('No midpoint generator!')\n avgdegree = None\n if weighing != 'okapi':\n degrees = None\n avgdegree = None\n if degrees is not None:\n avgdegree = sum(degrees.values()) * 1.0 / len(degrees)\n i=0\n tmp_container = []\n bsize = 5\n \n if parallel:\n ## parallel for edge type\n \n while True:\n tmp_container = list(next(generator) for _ in range(bsize)) \n\n if len(tmp_container) == 0:\n break\n\n pinput = []\n \n for j in tmp_container:\n pinput.append((classes,universal_set,j,n))\n results = pool.starmap(importance_calculator,pinput)\n \n ## construct main matrix\n for item, importances in zip(tmp_container, results):\n importance = np.sum(importances, axis=0)\n i1 = [self.node_indices[x] for x in item]\n i2 = [[x] for x in i1]\n\n to_add = sp.csr_matrix((nn, nn))\n \n if len(i1) > 1000:\n\n ## split to prevent memory leaks when doing hadamand products\n parts_first = self.split_to_parts(i1,4)\n parts_second = self.split_to_parts(i2,4)\n \n for x in range(len(parts_first)):\n to_add[parts_first[x], parts_second[x]] = importance\n \n else:\n to_add[i2, i1] = importance\n\n \n to_add = to_add.tocsr()\n matrix += to_add\n\n else:\n \n ## non-parallel \n for item in generator:\n \n ## to za vsak class poracun importance\n importances = importance_calculator(classes, universal_set, item, n, degrees=degrees, avgdegree=avgdegree)\n importance = np.sum(importances, axis=0)\n i1 = [self.node_indices[x] for x in item]\n i2 = [[x] for x in i1]\n\n \n \n to_add = sp.csr_matrix((nn, nn))\n to_add[i2, i1] = importance\n to_add = to_add.tocsr() # this prevents memory leaks\n matrix += to_add\n\n\n ## hadamand product\n \n self.decomposed[name] = matrix\n\n def midpoint_generator(self, node_sequence, edge_sequence):\n if len(node_sequence) % 2 == 0:\n raise Exception('In a split of length %i, a midpoint is not well defined!' % len(node_sequence))\n middle_type = node_sequence[int(len(node_sequence) / 2)]\n # forward_sequence = %TODO: INVERSE SEQUENCES!!!!!!!!!\n for node in self.graph:\n if self.graph.node[node]['type'] == middle_type:\n points = [node]\n i = int(len(node_sequence)/2 + 1)\n while i < len(node_sequence):\n current_type = node_sequence[i]\n new_points = []\n for point in points:\n new_points += [x for x in self.graph[point] if self.graph.node[x]['type'] == current_type]\n points = new_points\n i += 1\n if len(points) > 1:\n yield points\n"
] | [
[
"numpy.sum",
"scipy.sparse.csr_matrix"
]
] |
SimoCnt/Leaders-tweets-analysis-during-Covid-19-pandemic | [
"cab6e3d8bf80dcfc487642755fc6567fdc4e26ff"
] | [
"topic_modeling.py"
] | [
"\"\"\"\n@author: Salvatore Calderaro\n@author: Simone Contini\n\"\"\"\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.decomposition import LatentDirichletAllocation as LDA\nfrom textblob import TextBlob\nfrom wordcloud import WordCloud\nfrom deep_translator import GoogleTranslator\nimport os\nimport configobj\nimport numpy as np\nimport pyLDAvis.sklearn\nimport pickle\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\nconfig = configobj.ConfigObj('env.b')\n\nvec_path = config['MODEL_VEC_PATH']\nmodel_path = config['MODEL_PATH']\nwordCloud_path = config['WORDCLOUD_PATH']\ntopics_per_period_path = config['TOPICS_PER_PERIOD_PATH']\nemotions_path = config['EMOTION_PATH']\nemotions_per_topic_path = config['EMOTION_PER_TOPIC_PATH']\nepidemic_path = config['EPIDEMIC_PATH']\n\ncv = pickle.load(open(vec_path, 'rb')) # CountVectorizer\nmodel = pickle.load(open(model_path, 'rb'))\n\n\n\n\"\"\"\nFunzione che applica l'algoritmo LDA (Latent Dirichlet Allocation) ai documenti\ndella lista in input.\n\"\"\"\ndef apply_LDA(documents):\n count_vectorizer = CountVectorizer(min_df=10, max_df=0.95, ngram_range=(1,1))\n feature_matrix = count_vectorizer.fit_transform(documents)\n search_params = {'n_components': [5], 'learning_decay': [.5, .7, .9]}\n lda = LDA()\n model = GridSearchCV(lda, search_params)\n model.fit(feature_matrix)\n best_lda_model = model.best_estimator_\n lda_output = best_lda_model.transform(feature_matrix)\n prob_topic = np.round(lda_output, 2)\n topic_indexes = np.argmax(prob_topic, axis=1)\n n_topics = len(np.unique(topic_indexes))\n\n # Calcolo Perplexity (minore รจ, meglio รจ)\n #print('Perplexity: ', best_lda_model.perplexity(feature_matrix))\n\n # Calcolo Log likelihood (maggiore รจ, meglio รจ)\n #print('Log likelihood: ', best_lda_model.score(feature_matrix))\n\n return count_vectorizer, best_lda_model, topic_indexes, n_topics\n\n\n\n\"\"\"\nFunzione che stampa, per ogni topic, le top 10 word\n\"\"\"\ndef show_top10words_topics(vectorizer, lda_model, n_words):\n keywords = np.array(vectorizer.get_feature_names())\n topic_keywords = []\n\n for topic_weights in lda_model.components_:\n top_keyword_locs = (-topic_weights).argsort()[:n_words]\n topic_keywords.append(list(keywords.take(top_keyword_locs)))\n\n print(topic_keywords)\n\n\n\n\"\"\"\nFunzione che crea una word cloud per i topic presi in input\n\"\"\"\ndef create_wordCloud(topic_indexes, tweets, n_topics, country, lang, period):\n list_phrases_topics = [[] for _ in range(n_topics)]\n i = 0\n for topic in topic_indexes:\n list_phrases_topics[topic].append(tweets[i])\n i += 1\n\n for j in range(len(list_phrases_topics)):\n text_cloud = ''\n\n for feedback in list_phrases_topics[j]:\n text_cloud += ' ' + feedback\n\n cloud = WordCloud(max_font_size = 40).generate(text_cloud)\n\n path = wordCloud_path + country + '/' + country + '_' + str(period) + '_' + 'topic' + str(j) + '.png'\n cloud.to_file(path)\n\n\n\n\"\"\"\nFunzione che, per il periodo preso in input, effettua l'emotion analysis di tutti\ni topic.\n\"\"\"\ndef detect_topic_emotion(topic_indexes, tweets, n_topics, country, lang, period):\n list_phrases_topics = [[] for _ in range(n_topics)]\n i = 0\n for topic in topic_indexes:\n list_phrases_topics[topic].append(tweets[i])\n i += 1\n\n for j in range(len(list_phrases_topics)):\n freq = {\"joy\": 0, \"sadness\": 0, \"fear\": 0, \"anger\": 0, \"surprise\": 0, \"neutral\": 0, \"disgust\": 0, \"shame\": 0}\n for topic_tweets in list_phrases_topics[j]:\n if lang != 'en':\n topic_tweets = GoogleTranslator(source='auto', target='en').translate(topic_tweets)\n\n aus = []\n aus.append(topic_tweets)\n tweet_vec = cv.transform(aus).toarray()\n res = model.predict(tweet_vec)\n freq[res[0]] += 1\n\n labels = freq.keys()\n x_pos = np.arange(len(labels))\n val = freq.values()\n\n fig_title = country + ' ' + str(period) + ' ' + 'Topic' + ' ' + str(j+1) + ' ' + 'Emotion Analysis'\n fig_emo_topic = plt.figure()\n plt.title(fig_title, fontsize=12)\n plt.pie(val)\n plt.legend(labels, loc=\"best\")\n plt.axis('equal')\n plt.tight_layout()\n plt.savefig(emotions_per_topic_path + country + '/' + str(period) + '/' + country + '_' + str(j+1) + '.png', format='png', dpi=1200)\n plt.close(fig_emo_topic)\n\n\n\n\"\"\"\nFunzione che, per il periodo preso in input, effettua l'emotion analysis (attraverso\nl'uso di algoritmi di machine learning) dei tweet\n\"\"\"\ndef detect_emotion_periods(tweets, lang, country, period):\n freq = {\"joy\": 0, \"sadness\": 0, \"fear\": 0, \"anger\": 0, \"surprise\": 0, \"neutral\": 0, \"disgust\": 0, \"shame\": 0}\n\n for tweet in tweets:\n if lang != 'en':\n text = GoogleTranslator(source='auto', target='en').translate(tweet)\n else:\n text = tweet\n\n aus = []\n aus.append(text)\n text_vec = cv.transform(aus).toarray()\n\n res = model.predict(text_vec)\n freq[res[0]] += 1\n\n if period == 1:\n per = '01/01/2020 - 31/05/2020'\n elif period == 2:\n per = '01/06/2020 - 30/09/2020'\n elif period == 3:\n per = '01/10/2020 - 31/12/2020'\n else:\n per = '01/01/2021 - 09/06/2021'\n\n labels = freq.keys()\n x_pos = np.arange(len(labels))\n val = freq.values()\n\n fig_title = country + ' ' + per + ' ' + 'Emotion Analysis'\n fig_emo_topic2 = plt.figure()\n plt.title(fig_title, fontsize=12)\n plt.pie(val)\n plt.legend(labels, loc=\"best\")\n plt.axis('equal')\n plt.tight_layout()\n plt.savefig(emotions_path + country + '/' + country + '_' + str(period) + '.png', format='png', dpi=1200)\n plt.show()\n\n\n\n\"\"\"\nPlot grafici\n\"\"\"\ndef plot_analysis(country, period):\n freq = {\"joy\": 0, \"sadness\": 0, \"fear\": 0, \"anger\": 0, \"surprise\": 0, \"neutral\": 0, \"disgust\": 0, \"shame\": 0}\n labels = freq.keys()\n\n wc_image_path = wordCloud_path + country + '/'\n emo_per_topic_path = emotions_per_topic_path + country + '/' + str(period) + '/'\n emo_image_path = emotions_path + country + '/' + country + '_' + str(period) + '.png'\n epidemic_image_path = epidemic_path + country + '.png'\n\n if period == 1:\n per = '01/01/2020 - 31/05/2020'\n elif period == 2:\n per = '01/06/2020 - 30/09/2020'\n elif period == 3:\n per = '01/10/2020 - 31/12/2020'\n else:\n per = '01/01/2021 - 09/06/2021'\n\n all_files_wc = os.listdir(wc_image_path)\n all_files_pie = os.listdir(emo_per_topic_path)\n cur_wc_files = []\n cur_pie_files = []\n\n for file1 in (all_files_wc):\n if('_' + str(period) in file1):\n cur_wc_files.append(file1)\n\n cur_wc_files.sort(key=lambda x: x.split('_topic')[1])\n all_files_pie.sort(key=lambda x: x.split('_')[1])\n\n list_wordClouds_images = []\n for f in cur_wc_files:\n f = wc_image_path + f\n list_wordClouds_images.append(Image.open(f,'r'))\n\n list_piePerTopic_images = []\n for f in all_files_pie:\n f = emo_per_topic_path + f\n list_piePerTopic_images.append(Image.open(f,'r'))\n\n fig = plt.figure()\n gs1 = fig.add_gridspec(nrows=2,ncols=3)\n ax1 = fig.add_subplot(gs1[0,0])\n ax2 = fig.add_subplot(gs1[0,1])\n ax3 = fig.add_subplot(gs1[0,2])\n ax4 = fig.add_subplot(gs1[1,0])\n ax5 = fig.add_subplot(gs1[1,1])\n ax6 = fig.add_subplot(gs1[1,2])\n\n ax1.imshow(list_wordClouds_images[0])\n ax1.set_title(\"Topic 1\")\n ax1.axis('off')\n\n ax2.imshow(list_wordClouds_images[1])\n ax2.set_title(\"Topic 2\")\n ax2.axis('off')\n\n ax3.imshow(list_wordClouds_images[2])\n ax3.set_title(\"Topic 3\")\n ax3.axis('off')\n\n ax4.imshow(list_piePerTopic_images[0])\n ax4.set_title(\"Emotion Pie Topic 1\")\n ax4.axis('off')\n\n ax5.imshow(list_piePerTopic_images[1])\n ax5.set_title(\"Emotion Pie Topic 2\")\n ax5.axis('off')\n\n ax6.imshow(list_piePerTopic_images[2])\n ax6.set_title(\"Emotion Pie Topic 3\")\n ax6.axis('off')\n\n sub_title = 'List of topics ' + per + ' - ' + country\n fig.suptitle(sub_title)\n plt.savefig(topics_per_period_path + country + '/' + country + '_' + str(period) + '1.png', format='png', dpi=1200)\n plt.show()\n\n fig2 = plt.figure()\n gs2 = fig2.add_gridspec(nrows=2,ncols=2)\n ax1 = fig2.add_subplot(gs2[0,0])\n ax2 = fig2.add_subplot(gs2[0,1])\n ax3 = fig2.add_subplot(gs2[1,0])\n ax4 = fig2.add_subplot(gs2[1,1])\n\n ax1.imshow(list_wordClouds_images[3])\n ax1.set_title(\"Topic 4\")\n ax1.axis('off')\n\n ax2.imshow(list_wordClouds_images[4])\n ax2.set_title(\"Topic 5\")\n ax2.axis('off')\n\n ax3.imshow(list_piePerTopic_images[3])\n ax3.set_title(\"Emotion Pie Topic 4\")\n ax3.axis('off')\n\n ax4.imshow(list_piePerTopic_images[4])\n ax4.set_title(\"Emotion Pie Topic 5\")\n ax4.axis('off')\n\n sub_title = 'List of topics ' + per + ' - ' + country\n fig2.suptitle(sub_title)\n plt.savefig(topics_per_period_path + country + '/' + country + '_' + str(period) + '2.png', format='png', dpi=1200)\n plt.show()\n"
] | [
[
"matplotlib.pyplot.legend",
"sklearn.feature_extraction.text.CountVectorizer",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.pie",
"numpy.argmax",
"sklearn.decomposition.LatentDirichletAllocation",
"matplotlib.pyplot.title",
"matplotlib.pyplot.show",
"sklearn.model_selection.GridSearchCV",
"matplotlib.pyplot.close",
"numpy.round",
"numpy.unique"
]
] |
carchrae/tensorflow | [
"04f2870814d2773e09dcfa00cbe76a66a2c4de88"
] | [
"tensorflow/python/keras/optimizer_v2/adadelta_test.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\"\"\"Tests for Adadelta Optimizer.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.keras.optimizer_v2 import adadelta\nfrom tensorflow.python.ops import embedding_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import resource_variable_ops\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import test\n\n_DATA_TYPES = [dtypes.half, dtypes.float32, dtypes.float64]\n# TODO(b/143684500): Eigen to support complex sqrt\nif (not test_util.IsBuiltWithNvcc() and not test.is_built_with_rocm()):\n _DATA_TYPES += [dtypes.complex64, dtypes.complex128]\n\n\nclass AdadeltaOptimizerTest(test.TestCase):\n\n def doTestBasic(self, use_resource=False, use_callable_params=False):\n num_updates = 4 # number of ADADELTA steps to perform\n for dtype in _DATA_TYPES:\n for grad in [0.2, 0.1, 0.01]:\n for lr in [1.0, 0.5, 0.1]:\n var0_init = [1.0, 2.0]\n var1_init = [3.0, 4.0]\n if use_resource:\n var0 = resource_variable_ops.ResourceVariable(\n var0_init, dtype=dtype)\n var1 = resource_variable_ops.ResourceVariable(\n var1_init, dtype=dtype)\n else:\n var0 = variables.Variable(var0_init, dtype=dtype)\n var1 = variables.Variable(var1_init, dtype=dtype)\n\n grads = constant_op.constant([grad, grad], dtype=dtype)\n\n accum = 0.0\n accum_update = 0.0\n\n # ADADELTA gradient optimizer\n rho = 0.95\n epsilon = 1e-8\n if use_callable_params:\n adadelta_opt = adadelta.Adadelta(\n learning_rate=lambda: lr, # pylint: disable=cell-var-from-loop\n rho=lambda: rho, # pylint: disable=cell-var-from-loop\n epsilon=epsilon) # pylint: disable=cell-var-from-loop\n else:\n adadelta_opt = adadelta.Adadelta(\n learning_rate=lr, rho=rho, epsilon=epsilon)\n if not context.executing_eagerly():\n adadelta_update = adadelta_opt.apply_gradients(\n zip([grads, grads], [var0, var1]))\n self.evaluate(variables.global_variables_initializer())\n\n # Assign slots\n slot = [None] * 2\n slot_update = [None] * 2\n slot[0] = adadelta_opt.get_slot(var0, \"accum_grad\")\n self.assertEqual(slot[0].shape, var0.shape)\n\n slot_update[0] = adadelta_opt.get_slot(var0, \"accum_var\")\n self.assertEqual(slot_update[0].shape, var0.shape)\n\n slot[1] = adadelta_opt.get_slot(var1, \"accum_grad\")\n self.assertEqual(slot[1].shape, var1.shape)\n\n slot_update[1] = adadelta_opt.get_slot(var1, \"accum_var\")\n self.assertEqual(slot_update[1].shape, var1.shape)\n\n # Fetch params to validate initial values\n self.assertAllClose(var0_init, self.evaluate(var0))\n self.assertAllClose(var1_init, self.evaluate(var1))\n\n update = [None] * num_updates\n tot_update = 0\n for step in range(num_updates):\n # Run adadelta update for comparison\n if not context.executing_eagerly():\n self.evaluate(adadelta_update)\n else:\n adadelta_opt.apply_gradients(zip([grads, grads], [var0, var1]))\n\n # Perform initial update without previous accum values\n accum = accum * rho + (grad**2) * (1 - rho)\n update[step] = (\n np.sqrt(accum_update + epsilon) *\n (1. / np.sqrt(accum + epsilon)) * grad)\n accum_update = (\n accum_update * rho + (update[step]**2) * (1.0 - rho))\n tot_update += update[step] * lr\n\n if not context.executing_eagerly():\n # Check that the accumulators have been updated\n # TODO(lxuechen): This is hard to test in eager mode\n for slot_idx in range(2):\n self.assertAllCloseAccordingToType(\n np.array([accum, accum], dtype=dtype.as_numpy_dtype(0)),\n self.evaluate(slot[slot_idx]),\n rtol=1e-5)\n\n self.assertAllCloseAccordingToType(\n np.array(\n [accum_update, accum_update],\n dtype=dtype.as_numpy_dtype(0)),\n self.evaluate(slot_update[slot_idx]),\n rtol=1e-5)\n\n # Check that the parameters have been updated\n self.assertAllCloseAccordingToType(\n np.array(\n [var0_init[0] - tot_update, var0_init[1] - tot_update],\n dtype=dtype.as_numpy_dtype(0)),\n self.evaluate(var0),\n rtol=1e-5)\n\n self.assertAllCloseAccordingToType(\n np.array(\n [var1_init[0] - tot_update, var1_init[1] - tot_update],\n dtype=dtype.as_numpy_dtype(0)),\n self.evaluate(var1),\n rtol=1e-5)\n\n @test_util.run_in_graph_and_eager_modes(reset_test=True)\n def testResourceBasic(self):\n self.doTestBasic(use_resource=True)\n\n def testBasicCallableParams(self):\n with context.eager_mode():\n self.doTestBasic(use_resource=True, use_callable_params=True)\n\n @test_util.run_deprecated_v1\n def testMinimizeSparseResourceVariable(self):\n for dtype in _DATA_TYPES:\n var0 = resource_variable_ops.ResourceVariable([[1.0, 2.0]], dtype=dtype)\n x = constant_op.constant([[4.0], [5.0]], dtype=dtype)\n\n def loss():\n pred = math_ops.matmul(embedding_ops.embedding_lookup([var0], [0]), x) # pylint: disable=cell-var-from-loop\n return pred * pred\n\n sgd_op = adadelta.Adadelta(1.0, 1.0, 1.0).minimize(loss, var_list=[var0])\n self.evaluate(variables.global_variables_initializer())\n # Fetch params to validate initial values\n self.assertAllCloseAccordingToType([[1.0, 2.0]], self.evaluate(var0))\n # Run 1 step of sgd\n self.evaluate(sgd_op)\n # Validate updated params\n self.assertAllCloseAccordingToType([[-111, -138]], self.evaluate(var0))\n\n def testConstructAdadeltaWithLR(self):\n opt = adadelta.Adadelta(lr=1.0, rho=0.9, epsilon=1.)\n opt_2 = adadelta.Adadelta(learning_rate=0.1, rho=0.9, epsilon=1., lr=1.0)\n opt_3 = adadelta.Adadelta(learning_rate=0.1, rho=0.9, epsilon=1.)\n self.assertIsInstance(opt.lr, variables.Variable)\n self.assertIsInstance(opt_2.lr, variables.Variable)\n self.assertIsInstance(opt_3.lr, variables.Variable)\n\n self.evaluate(variables.global_variables_initializer())\n self.assertAllClose(self.evaluate(opt.lr), (1.0))\n self.assertAllClose(self.evaluate(opt_2.lr), (1.0))\n self.assertAllClose(self.evaluate(opt_3.lr), (0.1))\n\n def testConstructAdadeltaWithEpsilonValues(self):\n opt = adadelta.Adadelta(epsilon=None)\n self.assertEqual(opt.epsilon, 1e-7)\n\n opt = adadelta.Adadelta(epsilon=1e-8)\n self.assertEqual(opt.epsilon, 1e-8)\n\n\nif __name__ == \"__main__\":\n test.main()\n"
] | [
[
"tensorflow.python.platform.test.is_built_with_rocm",
"tensorflow.python.eager.context.eager_mode",
"tensorflow.python.framework.test_util.run_in_graph_and_eager_modes",
"tensorflow.python.keras.optimizer_v2.adadelta.Adadelta",
"tensorflow.python.ops.embedding_ops.embedding_lookup",
"tensorflow.python.ops.variables.global_variables_initializer",
"tensorflow.python.framework.test_util.IsBuiltWithNvcc",
"tensorflow.python.platform.test.main",
"tensorflow.python.ops.resource_variable_ops.ResourceVariable",
"numpy.sqrt",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.ops.variables.Variable",
"tensorflow.python.framework.constant_op.constant"
]
] |
abhishekvermasg/automl | [
"b4cd80b396836aada750aef47c2287bfe1ac4105"
] | [
"efficientdet/keras/anchors.py"
] | [
"# Copyright 2020 Google Research. 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\"\"\"Anchor definition.\"\"\"\nimport collections\nimport numpy as np\nimport tensorflow as tf\n\nimport utils\nfrom object_detection import argmax_matcher\nfrom object_detection import box_list\nfrom object_detection import faster_rcnn_box_coder\nfrom object_detection import region_similarity_calculator\nfrom object_detection import target_assigner\n\nMAX_DETECTION_POINTS = 5000\n\n\ndef decode_box_outputs(pred_boxes, anchor_boxes):\n \"\"\"Transforms relative regression coordinates to absolute positions.\n\n Network predictions are normalized and relative to a given anchor; this\n reverses the transformation and outputs absolute coordinates for the input\n image.\n\n Args:\n pred_boxes: predicted box regression targets.\n anchor_boxes: anchors on all feature levels.\n Returns:\n outputs: bounding boxes.\n \"\"\"\n anchor_boxes = tf.cast(anchor_boxes, pred_boxes.dtype)\n ycenter_a = (anchor_boxes[..., 0] + anchor_boxes[..., 2]) / 2\n xcenter_a = (anchor_boxes[..., 1] + anchor_boxes[..., 3]) / 2\n ha = anchor_boxes[..., 2] - anchor_boxes[..., 0]\n wa = anchor_boxes[..., 3] - anchor_boxes[..., 1]\n ty, tx, th, tw = tf.unstack(pred_boxes, num=4, axis=-1)\n\n w = tf.math.exp(tw) * wa\n h = tf.math.exp(th) * ha\n ycenter = ty * ha + ycenter_a\n xcenter = tx * wa + xcenter_a\n ymin = ycenter - h / 2.\n xmin = xcenter - w / 2.\n ymax = ycenter + h / 2.\n xmax = xcenter + w / 2.\n return tf.stack([ymin, xmin, ymax, xmax], axis=-1)\n\n\nclass Anchors():\n \"\"\"Multi-scale anchors class.\"\"\"\n\n def __init__(self, min_level, max_level, num_scales, aspect_ratios,\n anchor_scale, image_size):\n \"\"\"Constructs multiscale anchors.\n\n Args:\n min_level: integer number of minimum level of the output feature pyramid.\n max_level: integer number of maximum level of the output feature pyramid.\n num_scales: integer number representing intermediate scales added\n on each level. For instances, num_scales=2 adds two additional\n anchor scales [2^0, 2^0.5] on each level.\n aspect_ratios: list of representing the aspect ratio anchors added\n on each level. For instances, aspect_ratios = [1.0, 2.0, 0..5]\n adds three anchors on each level.\n anchor_scale: float number representing the scale of size of the base\n anchor to the feature stride 2^level. Or a list, one value per layer.\n image_size: integer number or tuple of integer number of input image size.\n \"\"\"\n self.min_level = min_level\n self.max_level = max_level\n self.num_scales = num_scales\n self.aspect_ratios = aspect_ratios\n if isinstance(anchor_scale, (list, tuple)):\n assert len(anchor_scale) == max_level - min_level + 1\n self.anchor_scales = anchor_scale\n else:\n self.anchor_scales = [anchor_scale] * (max_level - min_level + 1)\n self.image_size = utils.parse_image_size(image_size)\n self.feat_sizes = utils.get_feat_sizes(image_size, max_level)\n self.config = self._generate_configs()\n self.boxes = self._generate_boxes()\n\n def _generate_configs(self):\n \"\"\"Generate configurations of anchor boxes.\"\"\"\n anchor_configs = {}\n feat_sizes = self.feat_sizes\n for level in range(self.min_level, self.max_level + 1):\n anchor_configs[level] = []\n for scale_octave in range(self.num_scales):\n for aspect in self.aspect_ratios:\n anchor_configs[level].append(\n ((feat_sizes[0]['height'] / float(feat_sizes[level]['height']),\n feat_sizes[0]['width'] / float(feat_sizes[level]['width'])),\n scale_octave / float(self.num_scales), aspect,\n self.anchor_scales[level - self.min_level]))\n return anchor_configs\n\n def _generate_boxes(self):\n \"\"\"Generates multiscale anchor boxes.\"\"\"\n boxes_all = []\n for _, configs in self.config.items():\n boxes_level = []\n for config in configs:\n stride, octave_scale, aspect, anchor_scale = config\n base_anchor_size_x = anchor_scale * stride[1] * 2**octave_scale\n base_anchor_size_y = anchor_scale * stride[0] * 2**octave_scale\n if isinstance(aspect, list):\n aspect_x, aspect_y = aspect\n else:\n aspect_x = np.sqrt(aspect)\n aspect_y = 1.0 / aspect_x\n anchor_size_x_2 = base_anchor_size_x * aspect_x / 2.0\n anchor_size_y_2 = base_anchor_size_y * aspect_y / 2.0\n\n x = np.arange(stride[1] / 2, self.image_size[1], stride[1])\n y = np.arange(stride[0] / 2, self.image_size[0], stride[0])\n xv, yv = np.meshgrid(x, y)\n xv = xv.reshape(-1)\n yv = yv.reshape(-1)\n\n boxes = np.vstack((yv - anchor_size_y_2, xv - anchor_size_x_2,\n yv + anchor_size_y_2, xv + anchor_size_x_2))\n boxes = np.swapaxes(boxes, 0, 1)\n boxes_level.append(np.expand_dims(boxes, axis=1))\n # concat anchors on the same level to the reshape NxAx4\n boxes_level = np.concatenate(boxes_level, axis=1)\n boxes_all.append(boxes_level.reshape([-1, 4]))\n\n anchor_boxes = np.vstack(boxes_all)\n anchor_boxes = tf.convert_to_tensor(anchor_boxes, dtype=tf.float32)\n return anchor_boxes\n\n def get_anchors_per_location(self):\n return self.num_scales * len(self.aspect_ratios)\n\n\nclass AnchorLabeler(object):\n \"\"\"Labeler for multiscale anchor boxes.\"\"\"\n\n def __init__(self, anchors, num_classes, match_threshold=0.5):\n \"\"\"Constructs anchor labeler to assign labels to anchors.\n\n Args:\n anchors: an instance of class Anchors.\n num_classes: integer number representing number of classes in the dataset.\n match_threshold: float number between 0 and 1 representing the threshold\n to assign positive labels for anchors.\n \"\"\"\n similarity_calc = region_similarity_calculator.IouSimilarity()\n matcher = argmax_matcher.ArgMaxMatcher(\n match_threshold,\n unmatched_threshold=match_threshold,\n negatives_lower_than_unmatched=True,\n force_match_for_each_row=True)\n box_coder = faster_rcnn_box_coder.FasterRcnnBoxCoder()\n\n self._target_assigner = target_assigner.TargetAssigner(\n similarity_calc, matcher, box_coder)\n self._anchors = anchors\n self._match_threshold = match_threshold\n self._num_classes = num_classes\n\n def _unpack_labels(self, labels):\n \"\"\"Unpacks an array of labels into multiscales labels.\"\"\"\n labels_unpacked = collections.OrderedDict()\n anchors = self._anchors\n count = 0\n for level in range(anchors.min_level, anchors.max_level + 1):\n feat_size = anchors.feat_sizes[level]\n steps = feat_size['height'] * feat_size[\n 'width'] * anchors.get_anchors_per_location()\n indices = tf.range(count, count + steps)\n count += steps\n labels_unpacked[level] = tf.reshape(\n tf.gather(labels, indices),\n [feat_size['height'], feat_size['width'], -1])\n return labels_unpacked\n\n def label_anchors(self, gt_boxes, gt_labels):\n \"\"\"Labels anchors with ground truth inputs.\n\n Args:\n gt_boxes: A float tensor with shape [N, 4] representing groundtruth boxes.\n For each row, it stores [y0, x0, y1, x1] for four corners of a box.\n gt_labels: A integer tensor with shape [N, 1] representing groundtruth\n classes.\n Returns:\n cls_targets_dict: ordered dictionary with keys\n [min_level, min_level+1, ..., max_level]. The values are tensor with\n shape [height_l, width_l, num_anchors]. The height_l and width_l\n represent the dimension of class logits at l-th level.\n box_targets_dict: ordered dictionary with keys\n [min_level, min_level+1, ..., max_level]. The values are tensor with\n shape [height_l, width_l, num_anchors * 4]. The height_l and\n width_l represent the dimension of bounding box regression output at\n l-th level.\n num_positives: scalar tensor storing number of positives in an image.\n \"\"\"\n gt_box_list = box_list.BoxList(gt_boxes)\n anchor_box_list = box_list.BoxList(self._anchors.boxes)\n\n # cls_weights, box_weights are not used\n cls_targets, _, box_targets, _, matches = self._target_assigner.assign(\n anchor_box_list, gt_box_list, gt_labels)\n\n # class labels start from 1 and the background class = -1\n cls_targets -= 1\n cls_targets = tf.cast(cls_targets, tf.int32)\n\n # Unpack labels.\n cls_targets_dict = self._unpack_labels(cls_targets)\n box_targets_dict = self._unpack_labels(box_targets)\n num_positives = tf.reduce_sum(\n tf.cast(tf.not_equal(matches.match_results, -1), tf.float32))\n\n return cls_targets_dict, box_targets_dict, num_positives\n"
] | [
[
"numpy.vstack",
"tensorflow.gather",
"tensorflow.stack",
"tensorflow.unstack",
"tensorflow.range",
"numpy.concatenate",
"numpy.swapaxes",
"numpy.arange",
"tensorflow.cast",
"numpy.expand_dims",
"tensorflow.convert_to_tensor",
"tensorflow.not_equal",
"numpy.sqrt",
"tensorflow.math.exp",
"numpy.meshgrid"
]
] |
rahul-jha98/sphereface_pytorch | [
"bcacf44722fe53e2c30faca725933bf695b45620"
] | [
"train.py"
] | [
"from __future__ import print_function\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\ntorch.backends.cudnn.bencmark = True\n\nimport os,sys,cv2,random,datetime\nimport argparse\nimport numpy as np\n\nfrom dataset import ImageDataset\nfrom matlab_cp2tform import get_similarity_transform_for_cv2\nimport net_sphere\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\nparser = argparse.ArgumentParser(description='PyTorch sphereface')\nparser.add_argument('--net','-n', default='sphere20a', type=str)\nparser.add_argument('--dataset', default='/content/CASIA-WebFace.zip', type=str)\nparser.add_argument('--lr', default=0.1, type=float, help='learning rate')\nparser.add_argument('--bs', default=256, type=int, help='')\nargs = parser.parse_args()\nuse_cuda = torch.cuda.is_available()\n\n\ndef alignment(src_img,src_pts):\n of = 2\n ref_pts = [ [30.2946+of, 51.6963+of],[65.5318+of, 51.5014+of],\n [48.0252+of, 71.7366+of],[33.5493+of, 92.3655+of],[62.7299+of, 92.2041+of] ]\n crop_size = (96+of*2, 112+of*2)\n\n s = np.array(src_pts).astype(np.float32)\n r = np.array(ref_pts).astype(np.float32)\n\n tfm = get_similarity_transform_for_cv2(s, r)\n face_img = cv2.warpAffine(src_img, tfm, crop_size)\n return face_img\n\n\ndef dataset_load(name,filename,pindex,cacheobj,zfile):\n position = filename.rfind('.zip:')\n zipfilename = filename[0:position+4]\n nameinzip = filename[position+5:]\n\n split = nameinzip.split('\\t')\n nameinzip = split[0]\n classid = int(split[1])\n src_pts = []\n for i in range(5):\n src_pts.append([int(split[2*i+2]),int(split[2*i+3])])\n\n data = np.frombuffer(zfile.read('CASIA-WebFace/'+nameinzip),np.uint8)\n img = cv2.imdecode(data,1)\n img = alignment(img,src_pts)\n\n if ':train' in name:\n if random.random()>0.5: img = cv2.flip(img,1)\n if random.random()>0.5:\n rx = random.randint(0,2*2)\n ry = random.randint(0,2*2)\n img = img[ry:ry+112,rx:rx+96,:]\n else:\n img = img[2:2+112,2:2+96,:]\n else:\n img = img[2:2+112,2:2+96,:]\n\n\n img = img.transpose(2, 0, 1).reshape((1,3,112,96))\n img = ( img - 127.5 ) / 128.0\n label = np.zeros((1,1),np.float32)\n label[0,0] = classid\n return (img,label)\n\n\ndef printoneline(*argv):\n s = ''\n for arg in argv: s += str(arg) + ' '\n s = s[:-1]\n sys.stdout.write('\\r'+s)\n sys.stdout.flush()\n\ndef save_model(model,filename):\n state = model.state_dict()\n for key in state: state[key] = state[key].clone().cpu()\n torch.save(state, filename)\n\ndef dt():\n return datetime.datetime.now().strftime('%H:%M:%S')\n\n\n\ndef train(epoch,args):\n net.train()\n train_loss = 0\n correct = 0\n total = 0\n batch_idx = 0\n ds = ImageDataset(args.dataset,dataset_load,'/content/sphereface_pytorch/data/casia_landmark.txt',name=args.net+':train',\n bs=args.bs,shuffle=True,nthread=6,imagesize=128)\n while True:\n img,label = ds.get()\n if img is None: break\n inputs = torch.from_numpy(img).float()\n targets = torch.from_numpy(label[:,0]).long()\n if use_cuda: inputs, targets = inputs.cuda(), targets.cuda()\n\n optimizer.zero_grad()\n inputs, targets = Variable(inputs), Variable(targets)\n outputs = net(inputs)\n loss = criterion(outputs, targets)\n lossd = loss.data\n loss.backward()\n optimizer.step()\n\n train_loss += loss.data\n outputs = outputs[0] # 0=cos_theta 1=phi_theta\n _, predicted = torch.max(outputs.data, 1)\n total += targets.size(0)\n correct += predicted.eq(targets.data).cpu().sum()\n\n printoneline(dt(),'Te=%d Loss=%.4f Regular Loss=%.4f | AccT=%.4f%% (%d/%d) %.4f %.2f %d'\n % (epoch,train_loss/(batch_idx+1), criterion.lamb * criterion.regularLoss, 100.0*correct/total, correct, total, \n lossd, criterion.angular.lamb, criterion.it))\n batch_idx += 1\n print('')\n\n\nnet = getattr(net_sphere,args.net)()\n# net.load_state_dict(torch.load('sphere20a_0.pth'))\nnet.cuda()\nif(args.net=='sphere20a'):\n criterion = net_sphere.AngleLoss()\nelse:\n criterion = net_sphere.SphereAndRgularLoss()\n\n\nprint('start: time={}'.format(dt()))\nfor epoch in range(0, 20):\n if epoch in [0,10,15,18]:\n if epoch!=0: args.lr *= 0.1\n optimizer = optim.SGD(net.parameters(), lr=args.lr, momentum=0.9, weight_decay=5e-4)\n\n train(epoch,args)\n save_model(net, '{}_{}.pth'.format(args.net,epoch))\n\nprint('finish: time={}\\n'.format(dt()))\n\n"
] | [
[
"numpy.zeros",
"torch.save",
"torch.autograd.Variable",
"torch.cuda.is_available",
"torch.from_numpy",
"torch.max",
"numpy.array"
]
] |
dengdifan/SMAC3 | [
"4739741fe9f6b0b92d419bac8f0a6252858a55dc"
] | [
"test/test_runhistory/test_runhistory2epm.py"
] | [
"__author__ = \"Katharina Eggensperger\"\n__copyright__ = \"Copyright 2015, ML4AAD\"\n__license__ = \"GPLv3\"\n__maintainer__ = \"Katharina Eggensperger\"\n__email__ = \"[email protected]\"\n__version__ = \"0.0.1\"\n\nimport unittest\n\nimport numpy as np\n\nfrom smac.tae import StatusType\nfrom smac.runhistory import runhistory, runhistory2epm\n\nfrom ConfigSpace import Configuration, ConfigurationSpace\nfrom ConfigSpace.hyperparameters import UniformIntegerHyperparameter\nfrom smac.scenario.scenario import Scenario\nfrom smac.epm.rfr_imputator import RFRImputator\nfrom smac.epm.rf_with_instances import RandomForestWithInstances\nfrom smac.epm.util_funcs import get_types\n\n\ndef get_config_space():\n cs = ConfigurationSpace()\n cs.add_hyperparameter(UniformIntegerHyperparameter(name='a',\n lower=0,\n upper=100))\n cs.add_hyperparameter(UniformIntegerHyperparameter(name='b',\n lower=0,\n upper=100))\n return cs\n\n\nclass RunhistoryTest(unittest.TestCase):\n\n def setUp(self):\n unittest.TestCase.setUp(self)\n\n self.rh = runhistory.RunHistory()\n self.cs = get_config_space()\n self.config1 = Configuration(self.cs,\n values={'a': 0, 'b': 100})\n self.config2 = Configuration(self.cs,\n values={'a': 100, 'b': 0})\n self.config3 = Configuration(self.cs,\n values={'a': 100, 'b': 100})\n self.config4 = Configuration(self.cs,\n values={'a': 23, 'b': 23})\n self.config5 = Configuration(self.cs,\n values={'a': 5, 'b': 10})\n self.scen = Scenario({'run_obj': 'runtime', 'cutoff_time': 20,\n 'cs': self.cs})\n self.types, self.bounds = get_types(self.cs, None)\n self.scen = Scenario({'run_obj': 'runtime', 'cutoff_time': 20, 'cs': self.cs,\n 'output_dir': ''})\n\n def test_log_runtime_with_imputation(self):\n '''\n adding some rundata to RunHistory2EPM4LogCost and impute censored data\n '''\n self.imputor = RFRImputator(\n rng=np.random.RandomState(seed=12345),\n cutoff=np.log(self.scen.cutoff),\n threshold=np.log(self.scen.cutoff * self.scen.par_factor),\n model=RandomForestWithInstances(\n configspace=self.cs,\n types=self.types,\n bounds=self.bounds,\n instance_features=None,\n seed=12345,\n ratio_features=1.0,\n )\n )\n\n rh2epm = runhistory2epm.RunHistory2EPM4LogCost(num_params=2,\n scenario=self.scen,\n impute_censored_data=True,\n impute_state=[StatusType.TIMEOUT, ],\n success_states=[StatusType.SUCCESS, ],\n imputor=self.imputor)\n\n self.rh.add(config=self.config1, cost=1, time=1,\n status=StatusType.SUCCESS, instance_id=23,\n seed=None,\n additional_info=None)\n\n X, y = rh2epm.transform(self.rh)\n self.assertTrue(np.allclose(X, np.array([[0.005, 0.995]]), atol=0.001))\n self.assertTrue(np.allclose(y, np.array([[0.]]))) # 10^0 = 1\n\n # rh2epm should use time and not cost field later\n self.rh.add(config=self.config3, cost=200, time=20,\n status=StatusType.TIMEOUT, instance_id=1,\n seed=45,\n additional_info={\"start_time\": 20})\n\n X, y = rh2epm.transform(self.rh)\n self.assertTrue(\n np.allclose(X, np.array([[0.005, 0.995], [0.995, 0.995]]), atol=0.001))\n # ln(20 * 10)\n self.assertTrue(np.allclose(y, np.array([[0.], [5.2983]]), atol=0.001))\n\n self.rh.add(config=self.config2, cost=100, time=10,\n status=StatusType.TIMEOUT, instance_id=1,\n seed=12354,\n additional_info={\"start_time\": 10})\n\n X, y = rh2epm.transform(self.rh)\n np.testing.assert_array_almost_equal(X, np.array([[0.005, 0.995],\n [0.995, 0.005],\n [0.995, 0.995]]),\n decimal=3)\n\n np.testing.assert_array_almost_equal(y, np.array([[0.], [2.727], [5.2983]]),\n decimal=3)\n\n def test_log_cost_without_imputation(self):\n '''\n adding some rundata to RunHistory2EPM4LogCost\n '''\n\n rh2epm = runhistory2epm.RunHistory2EPM4LogCost(num_params=2,\n success_states=[StatusType.SUCCESS, ],\n impute_censored_data=False,\n scenario=self.scen)\n\n self.rh.add(config=self.config1, cost=1, time=1,\n status=StatusType.SUCCESS, instance_id=23,\n seed=None,\n additional_info=None)\n\n X, y = rh2epm.transform(self.rh)\n self.assertTrue(np.allclose(X, np.array([[0.005, 0.995]]), atol=0.001))\n self.assertTrue(np.allclose(y, np.array([[0.]]))) # 10^0 = 1\n\n # rh2epm should use time and not cost field later\n self.rh.add(config=self.config3, cost=200, time=20,\n status=StatusType.TIMEOUT, instance_id=1,\n seed=45,\n additional_info={\"start_time\": 20})\n\n X, y = rh2epm.transform(self.rh)\n self.assertTrue(\n np.allclose(X, np.array([[0.005, 0.995], [0.995, 0.995]]), atol=0.001))\n # ln(20 * 10)\n self.assertTrue(np.allclose(y, np.array([[0.], [5.2983]]), atol=0.001))\n\n self.rh.add(config=self.config2, cost=100, time=10,\n status=StatusType.TIMEOUT, instance_id=1,\n seed=12354,\n additional_info={\"start_time\": 10})\n\n X, y = rh2epm.transform(self.rh)\n # last entry gets skipped since imputation is disabled\n self.assertTrue(np.allclose(\n X, np.array([[0.005, 0.995], [0.995, 0.995]]), atol=0.001))\n self.assertTrue(\n np.allclose(y, np.array([[0.], [5.2983]]), atol=0.001))\n\n def test_cost_with_imputation(self):\n '''\n adding some rundata to RunHistory2EPM4Cost and impute censored data\n '''\n\n self.imputor = RFRImputator(\n rng=np.random.RandomState(seed=12345),\n cutoff=self.scen.cutoff,\n threshold=self.scen.cutoff * self.scen.par_factor,\n model=RandomForestWithInstances(\n configspace=self.cs,\n types=self.types,\n bounds=self.bounds,\n instance_features=None,\n seed=12345,\n n_points_per_tree=90,\n ratio_features=1.0,\n )\n )\n\n rh2epm = runhistory2epm.RunHistory2EPM4Cost(num_params=2,\n scenario=self.scen,\n impute_censored_data=True,\n success_states=[StatusType.SUCCESS, ],\n impute_state=[StatusType.TIMEOUT],\n imputor=self.imputor)\n\n self.rh.add(config=self.config1, cost=1, time=1,\n status=StatusType.SUCCESS, instance_id=23,\n seed=None,\n additional_info=None)\n\n X, y = rh2epm.transform(self.rh)\n self.assertTrue(np.allclose(X, np.array([[0.005, 0.995]]), atol=0.001))\n self.assertTrue(np.allclose(y, np.array([[1.]])))\n\n # rh2epm should use time and not cost field later\n self.rh.add(config=self.config3, cost=200, time=20,\n status=StatusType.TIMEOUT, instance_id=1,\n seed=45,\n additional_info={\"start_time\": 20})\n\n X, y = rh2epm.transform(self.rh)\n self.assertTrue(\n np.allclose(X, np.array([[0.005, 0.995], [0.995, 0.995]]), atol=0.001))\n self.assertTrue(np.allclose(y, np.array([[1.], [200.]]), atol=0.001))\n\n self.rh.add(config=self.config2, cost=100, time=10,\n status=StatusType.TIMEOUT, instance_id=1,\n seed=12354,\n additional_info={\"start_time\": 10})\n\n X, y = rh2epm.transform(self.rh)\n np.testing.assert_array_almost_equal(X, np.array([[0.005, 0.995],\n [0.995, 0.005],\n [0.995, 0.995]]),\n decimal=3)\n np.testing.assert_array_almost_equal(y, np.array([[1.], [11.], [200.]]),\n decimal=1)\n\n def test_cost_without_imputation(self):\n '''\n adding some rundata to RunHistory2EPM4Cost without imputation\n '''\n\n rh2epm = runhistory2epm.RunHistory2EPM4Cost(num_params=2,\n success_states=[StatusType.SUCCESS,\n StatusType.CRASHED,\n StatusType.MEMOUT],\n impute_censored_data=False,\n scenario=self.scen)\n\n self.rh.add(config=self.config1, cost=1, time=1,\n status=StatusType.SUCCESS, instance_id=23,\n seed=None,\n additional_info=None)\n\n X, y = rh2epm.transform(self.rh)\n self.assertTrue(np.allclose(X, np.array([[0.005, 0.995]]), atol=0.001))\n self.assertTrue(np.allclose(y, np.array([[1.]])))\n\n # rh2epm should use cost and not time\n self.rh.add(config=self.config3, cost=200, time=20,\n status=StatusType.TIMEOUT, instance_id=1,\n seed=45,\n additional_info={\"start_time\": 20})\n\n X, y = rh2epm.transform(self.rh)\n np.testing.assert_allclose(X, np.array([[0.005, 0.995], [0.995, 0.995]]), atol=0.001)\n # log_10(20 * 10)\n np.testing.assert_allclose(y, np.array([[1.], [200.]]), atol=0.001)\n\n self.rh.add(config=self.config2, cost=100, time=10,\n status=StatusType.TIMEOUT, instance_id=1,\n seed=12354,\n additional_info={\"start_time\": 10})\n\n X, y = rh2epm.transform(self.rh)\n # last entry gets skipped since imputation is disabled\n self.assertTrue(np.allclose(\n X, np.array([[0.005, 0.995], [0.995, 0.995]]), atol=0.001))\n self.assertTrue(\n np.allclose(y, np.array([[1.], [200.]]), atol=0.001))\n\n def test_cost_quality(self):\n '''\n adding some rundata to RunHistory2EPM4LogCost\n '''\n self.scen = Scenario({\"cutoff_time\": 20, 'cs': self.cs, 'run_obj': 'quality',\n 'output_dir': ''})\n\n rh2epm = runhistory2epm.RunHistory2EPM4Cost(num_params=2,\n success_states=[StatusType.SUCCESS,\n StatusType.CRASHED,\n StatusType.MEMOUT],\n impute_censored_data=False,\n scenario=self.scen)\n\n self.rh.add(config=self.config1, cost=1, time=10,\n status=StatusType.SUCCESS, instance_id=23,\n seed=None,\n additional_info=None)\n\n X, y = rh2epm.transform(self.rh)\n self.assertTrue(np.allclose(X, np.array([[0.005, 0.995]]), atol=0.001))\n # should use the cost field and not runtime\n self.assertTrue(np.allclose(y, np.array([[1.]])))\n\n # rh2epm should use cost and not time field later\n self.rh.add(config=self.config3, cost=200, time=20,\n status=StatusType.TIMEOUT, instance_id=1,\n seed=45,\n additional_info={\"start_time\": 20})\n\n X, y = rh2epm.transform(self.rh)\n self.assertTrue(\n np.allclose(X, np.array([[0.005, 0.995], [0.995, 0.995]]), atol=0.001))\n # log_10(20 * 10)\n self.assertTrue(np.allclose(y, np.array([[1.], [200.]]), atol=0.001))\n\n # TODO: unit test for censored data in quality scenario\n\n def test_get_X_y(self):\n '''\n add some data to RH and check returned values in X,y format\n '''\n\n self.scen = Scenario({'cutoff_time': 20, 'cs': self.cs,\n 'run_obj': 'runtime',\n 'instances': [['1'], ['2']],\n 'features': {\n '1': [1, 1],\n '2': [2, 2]\n },\n 'output_dir': ''})\n\n rh2epm = runhistory2epm.RunHistory2EPM4Cost(num_params=2,\n success_states=[StatusType.SUCCESS, ],\n impute_state=[StatusType.CAPPED, ],\n impute_censored_data=False,\n scenario=self.scen)\n\n self.rh.add(config=self.config1, cost=1, time=10,\n status=StatusType.SUCCESS, instance_id='1',\n seed=None,\n additional_info=None)\n\n self.rh.add(config=self.config1, cost=2, time=10,\n status=StatusType.SUCCESS, instance_id='2',\n seed=None,\n additional_info=None)\n\n self.rh.add(config=self.config2, cost=1, time=10,\n status=StatusType.TIMEOUT, instance_id='1',\n seed=None,\n additional_info=None)\n\n self.rh.add(config=self.config2, cost=0.1, time=10,\n status=StatusType.CAPPED, instance_id='2',\n seed=None,\n additional_info=None)\n\n X, y, c = rh2epm.get_X_y(self.rh)\n\n X_sol = np.array([[0, 100, 1, 1],\n [0, 100, 2, 2],\n [100, 0, 1, 1],\n [100, 0, 2, 2]])\n self.assertTrue(np.all(X == X_sol))\n\n y_sol = np.array([1, 2, 1, 0.1])\n self.assertTrue(np.all(y == y_sol))\n\n c_sol = np.array([False, False, True, True])\n self.assertTrue(np.all(c == c_sol))\n\n def test_budget_selection(self):\n '''\n adding some rundata and check budget selection\n '''\n\n rh2epm = runhistory2epm.RunHistory2EPM4Cost(num_params=2,\n success_states=[StatusType.SUCCESS,\n StatusType.CRASHED,\n StatusType.MEMOUT],\n impute_censored_data=False,\n scenario=self.scen)\n\n self.rh.add(config=self.config1, cost=1, time=1,\n status=StatusType.SUCCESS, instance_id=1,\n seed=None, budget=1,\n additional_info=None)\n self.rh.add(config=self.config1, cost=2, time=2,\n status=StatusType.SUCCESS, instance_id=1,\n seed=None, budget=2,\n additional_info=None)\n\n X, y = rh2epm.transform(self.rh, budget_subset=[1])\n self.assertTrue(np.allclose(X, np.array([[0.005, 0.995]]), atol=0.001))\n self.assertTrue(np.allclose(y, np.array([[1]])))\n\n X, y = rh2epm.transform(self.rh, budget_subset=[2])\n self.assertTrue(np.allclose(X, np.array([[0.005, 0.995]]), atol=0.001))\n self.assertTrue(np.allclose(y, np.array([[2]])))\n\n def test_run_selection(self):\n '''\n adding some rundata and check budget selection\n '''\n self.rh.add(config=self.config1, cost=1, time=1,\n status=StatusType.SUCCESS, instance_id=1,\n seed=None, budget=1,\n additional_info=None)\n self.rh.add(config=self.config2, cost=2, time=2,\n status=StatusType.CRASHED, instance_id=1,\n seed=None, budget=2,\n additional_info=None)\n self.rh.add(config=self.config3, cost=3, time=3,\n status=StatusType.MEMOUT, instance_id=1,\n seed=None, budget=2,\n additional_info=None)\n self.rh.add(config=self.config4, cost=4, time=4,\n status=StatusType.DONOTADVANCE, instance_id=1,\n seed=None, budget=3,\n additional_info=None)\n self.rh.add(config=self.config5, cost=20, time=20,\n status=StatusType.TIMEOUT, instance_id=1,\n seed=None, budget=4,\n additional_info=None)\n\n for s, v in [(StatusType.SUCCESS, 1), (StatusType.CRASHED, 2), (StatusType.MEMOUT, 3),\n (StatusType.DONOTADVANCE, 4), ]:\n rh2epm = runhistory2epm.RunHistory2EPM4Cost(num_params=2,\n success_states=[s, ],\n impute_censored_data=False,\n scenario=self.scen)\n X, y = rh2epm.transform(self.rh, budget_subset=None)\n self.assertSetEqual(set(y.flatten()), {v, 20})\n\n for s, v in [(StatusType.SUCCESS, [1, ]), (StatusType.CRASHED, []),\n (StatusType.MEMOUT, []), (StatusType.DONOTADVANCE, []),\n (StatusType.TIMEOUT, []), ]:\n rh2epm = runhistory2epm.RunHistory2EPM4Cost(num_params=2,\n success_states=[s, ],\n impute_censored_data=False,\n scenario=self.scen)\n X, y = rh2epm.transform(self.rh, budget_subset=[1])\n self.assertSetEqual(set(y.flatten()), set(v))\n\n # Test defaults set in SMAC facade\n rh2epm = runhistory2epm.RunHistory2EPM4Cost(num_params=2,\n success_states=[StatusType.SUCCESS,\n StatusType.CRASHED,\n StatusType.MEMOUT,\n StatusType.DONOTADVANCE,\n ],\n consider_for_higher_budgets_state=[\n StatusType.TIMEOUT,\n StatusType.CRASHED,\n StatusType.MEMOUT,\n StatusType.DONOTADVANCE,\n ],\n impute_censored_data=False,\n scenario=self.scen)\n X, y = rh2epm.transform(self.rh, budget_subset=[1])\n self.assertSetEqual(set(y.flatten()), {1, })\n self.assertTrue(len(y) == 1)\n X, y = rh2epm.transform(self.rh, budget_subset=[2])\n self.assertSetEqual(set(y.flatten()), {2, 3})\n self.assertTrue(len(y) == 2)\n X, y = rh2epm.transform(self.rh, budget_subset=[3])\n self.assertSetEqual(set(y.flatten()), {2, 3, 4})\n self.assertTrue(len(y) == 3)\n X, y = rh2epm.transform(self.rh, budget_subset=[4])\n self.assertSetEqual(set(y.flatten()), {2, 3, 4, 20})\n self.assertTrue(len(y) == 4)\n X, y = rh2epm.transform(self.rh, budget_subset=[5])\n self.assertSetEqual(set(y.flatten()), {2, 3, 4, 20})\n self.assertTrue(len(y) == 4)\n self.assertRaises(ValueError, rh2epm.transform, self.rh, budget_subset=[4, 5])\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
] | [
[
"numpy.array",
"numpy.random.RandomState",
"numpy.all",
"numpy.log"
]
] |
ulandz/vnpy | [
"bd6399e77364e434b89b8e866faad2556d1935aa"
] | [
"vnpy/app/cta_strategy/backtesting.py"
] | [
"from collections import defaultdict\nfrom datetime import date, datetime, timedelta\nfrom dateutil.relativedelta import relativedelta\nfrom typing import Callable\nfrom itertools import product\nfrom functools import lru_cache\nfrom time import time\nimport platform\nimport multiprocessing\n#empyrical้ฃ้ฉๆๆ ่ฎก็ฎๆจกๅ\nfrom empyrical import (sortino_ratio,omega_ratio,annual_volatility,cagr,conditional_value_at_risk,downside_risk,stability_of_timeseries,tail_ratio,value_at_risk)\nimport random\nimport os\nimport traceback\nimport numpy as np\nnp.seterr(divide='ignore',invalid='ignore')\nimport matplotlib.pyplot as plt\n#matplotlib ็พๅๆ ทๅผ๏ผbmh๏ผggplot\nplt.style.use(\"ggplot\")\nimport scipy.stats as scs\nimport seaborn as sns\nfrom pandas import DataFrame\nfrom deap import creator, base, tools, algorithms\nimport redis\nimport zlib\nimport pickle\nREDIS_CLIENT =redis.Redis(\"localhost\",12580)\n\nfrom vnpy.trader.constant import (Direction, Offset, Exchange, Interval, Status,OrderType)\nfrom vnpy.trader.database import database_manager\nfrom vnpy.trader.object import OrderData, TradeData, BarData, TickData\nfrom vnpy.trader.utility import (extract_vt_symbol,round_to)\nfrom vnpy.app.cta_strategy.base import (BacktestingMode, EngineType, STOPORDER_PREFIX, StopOrder, StopOrderStatus)\nfrom vnpy.app.cta_strategy.template import CtaTemplate\nsns.set_style('whitegrid')\ncreator.create('FitnessMax', base.Fitness, weights=(1.0,)) #ไผๅๆนๅ1ๆฑๆๅคงๅผ๏ผ-1ๆฑๆๅฐๅผ\ncreator.create('Individual', list, fitness=creator.FitnessMax)\n#ๅนดๆปไบคๆๆฅ\nTRADING_DAY = 365#365๏ผ252\nclass OptimizationSetting:\n '''\n ๅๆตไผๅ่ฎพ็ฝฎ\n '''\n\n def __init__(self):\n ''''''\n self.params = {}\n self.target_name = ''\n\n def add_parameter(self, name: str, start: float, end: float = None, step: float = None ):\n \"\"\"\n ่ฎพ็ฝฎไผๅๅๆฐ\n \"\"\"\n if not end and not step:\n self.params[name] = [start]\n return\n\n if start >= end:\n print('ๅๆฐไผๅ่ตทๅง็นๅฟ
้กปๅฐไบ็ปๆญข็น')\n return\n\n if step <= 0:\n print('ๅๆฐไผๅๆญฅ่ฟๅฟ
้กปๅคงไบ0')\n return\n\n value = start\n value_list = []\n\n while value <= end:\n value_list.append(value)\n value += step\n\n self.params[name] = value_list\n\n def set_target(self, target_name: str):\n \"\"\"่ฎพ็ฝฎไผๅ็ฎๆ \"\"\"\n self.target_name = target_name\n\n def generate_setting(self):\n\n keys = self.params.keys()\n values = self.params.values()\n products = list(product(*values))\n\n settings = []\n for p in products:\n setting = dict(zip(keys, p))\n settings.append(setting)\n\n return settings\n \n def generate_setting_ga(self):\n '''''' \n settings_ga = []\n settings = self.generate_setting() \n for d in settings: \n param = [tuple(i) for i in d.items()]\n settings_ga.append(param)\n return settings_ga\n\nclass BacktestingEngine:\n \"\"\"\n ๅๆตๅผๆ\n \"\"\"\n engine_type = EngineType.BACKTESTING\n gateway_name = 'BACKTESTING'\n def __init__(self):\n self.vt_symbol = ''\n self.symbol = ''\n self.exchange = None\n self.start = None\n self.end = None\n self.rate = 0\n self.slippage = 0\n self.size = 1\n self.price_tick = 0\n self.capital = 100000\n self.strategy_class = None\n self.strategy = None\n self.tick: TickData\n self.bar: BarData\n self.datetime = None\n\n self.interval = None\n self.days = 0\n self.callback = None\n self.history_data = []\n\n self.stop_order_count = 0\n self.stop_orders = {}\n self.active_stop_orders = {}\n\n self.limit_order_count = 0\n self.limit_orders = {}\n self.active_limit_orders = {}\n\n self.trade_count = 0\n self.trades = {}\n\n self.logs = []\n\n self.daily_results = {}\n self.daily_df = None\n #ไฟๅญๅๆต็ปๆ๏ผไผๅ็ปๆ่ทฏๅพ\n self.result_path = None\n # ๆไป็ไบๅๅงๅ\n self.long_avg_cost = 0 #ๅคๅคดๆไปๅไปท\n self.short_avg_cost = 0 #็ฉบๅคดๆไปๅไปท\n self.long_pos = 0 #ๅคๅคดไปไฝ\n self.short_pos = 0 #็ฉบๅคดไปไฝ\n self.long_profit_total = 0 #ๅคๅคดๆป็ไบ\n self.short_profit_total = 0 #็ฉบๅคดๆป็ไบ\n #ๅๅผๆๆ \n self.net_value = 0\n self.net_value_list = []\n #ๆๅบฆ็ไบๅๆฐ\n self.last_month_date = None\n self.month_pnl = 0\n self.month_dict = {}\n def set_capital(self,capital):\n \"\"\"่ฎพ็ฝฎๅๅง่ต้\"\"\"\n self.capital = capital\n def clear_data(self):\n '''\n Clear all data of last backtesting.\n '''\n self.strategy = None\n self.tick = None\n self.bar = None\n self.datetime = None\n\n self.stop_order_count = 0\n self.stop_orders.clear()\n self.active_stop_orders.clear()\n\n self.limit_order_count = 0\n self.limit_orders.clear()\n self.active_limit_orders.clear()\n\n self.trade_count = 0\n self.trades.clear()\n\n self.logs.clear()\n self.daily_results.clear()\n\n def set_parameters(self, vt_symbol: str, start: datetime, rate: float, slippage: float, size: float, price_tick: float, capital: int = 0, end: datetime = None, mode: BacktestingMode = BacktestingMode.BAR, ):\n ''''''\n self.mode = mode\n self.vt_symbol = vt_symbol\n if self.mode == BacktestingMode.BAR:\n self.interval = Interval.MINUTE\n self.rate = rate\n self.slippage = slippage\n self.size = size\n self.price_tick = price_tick\n self.start = start\n\n self.symbol, exchange,gateway_name = extract_vt_symbol(vt_symbol)\n self.exchange = Exchange(exchange)\n\n if capital:\n self.capital = capital\n\n if end:\n self.end = end\n\n if mode:\n self.mode = mode\n def add_strategy(self, strategy_class: type, setting: dict):\n ''''''\n self.strategy_class = strategy_class \n self.strategy = strategy_class(self, strategy_class.__name__, self.vt_symbol, setting )\n #ๅๅงๅ็ญ็ฅ็ไบๅๆฐ\n self.strategy.capital = 0 #ๅๅง่ต้\n self.strategy.balance = self.capital #ๆป่ต้ \n self.strategy.long_pos = 0 #ๅคๅคดไปไฝ\n self.strategy.short_pos = 0 #็ฉบๅคดไปไฝ\n self.strategy.long_profit = 0 #ๅคๅคดๆถ็\n self.strategy.short_profit = 0 #็ฉบๅคดๆถ็\n self.strategy.size = self.size #ๆฏๆไนๆฐ\n self.strategy.price_tick = self.price_tick #ๆๅฐไปทๆ ผๅๅจ\n self.strategy.active_limit_orders = self.active_limit_orders #ๆชๆไบค้ไปทๅ\n self.strategy.active_stop_orders = self.active_stop_orders #ๆชๆไบคๅๆญขๅ\n if setting:\n unactive_param = [loss_param for loss_param in list(setting.keys()) if loss_param not in self.strategy.parameters]\n assert not unactive_param,f\"ไธๅจ็ญ็ฅๅๆฐๅ่กจๅ
็ๅๆตๅๆฐ:{unactive_param}\" \n def load_data(self):\n \"\"\"ๅ ่ฝฝๅๅฒๆฐๆฎ\"\"\"\n self.output(\"ๅผๅงๅ ่ฝฝๅๅฒๆฐๆฎ\")\n if not self.end:\n self.end = datetime.now()\n self.history_data.clear() #่ฝฝๅ
ฅๆฐๆฎๅๆธ
้คๅๅฒๆฐๆฎ\n assert self.start < self.end,\"ๅๆตๅผๅงๆถ้ดๅฟ
้กปๅฐไบ็ปๆๆถ้ด๏ผ่ฏทๆ ธๅฎ๏ผ\"\n if self.mode == BacktestingMode.BAR:\n self.history_data = load_bar_data(self.symbol, self.exchange, self.interval, self.start, self.end)\n else:\n self.history_data = load_tick_data(self.symbol, self.exchange, self.start, self.end)\n\n self.output(f\"ๅๅฒๆฐๆฎๅ ่ฝฝๅฎๆ๏ผๆฐๆฎ้๏ผ{len(self.history_data)}\")\n\n def run_backtesting(self):\n \"\"\"ๅๆพๅๅฒๆฐๆฎ\"\"\"\n if self.mode == BacktestingMode.BAR:\n func = self.new_bar\n else:\n func = self.new_tick\n\n self.strategy.on_init()\n\n # Use the first [days] of history data for initializing strategy\n day_count = 0\n ix = 0\n for ix, data in enumerate(self.history_data):\n if self.datetime and data.datetime.day != self.datetime.day:\n day_count += 1\n if day_count >= self.days:\n break\n self.datetime = data.datetime\n try:\n self.callback(data)\n except Exception:\n self.output(\"่งฆๅๅผๅธธ๏ผๅๆต็ปๆญข\")\n self.output(traceback.format_exc())\n return\n\n self.strategy.inited = True\n self.output('็ญ็ฅๅๅงๅๅฎๆ')\n\n self.strategy.on_start()\n self.strategy.trading = True\n self.output('ๅผๅงๅๆพๅๅฒๆฐๆฎ')\n #ๅๆพhistory_dataๆฐๆฎๅฐon_tick/on_bar\n for data in self.history_data[ix:]:\n try:\n func(data)\n except Exception:\n self.output(\"่งฆๅๅผๅธธ๏ผๅๆต็ปๆญข\")\n self.output(traceback.format_exc())\n return\n self.output('ๅๅฒๆฐๆฎๅๆพ็ปๆ')\n\n def calculate_result(self):\n \"\"\"\n ่ฟๅdaily_df:DataFrame\n \"\"\"\n self.output('ๅผๅง่ฎก็ฎ้ๆฅ็ฏๅธ็ไบ')\n\n if not self.trades:\n self.output('ๆไบค่ฎฐๅฝไธบ็ฉบ๏ผๆ ๆณ่ฎก็ฎ')\n return\n\n # Add trade data into daily reuslt.\n for trade in self.trades.values():\n trade_date = trade.datetime.date()\n daily_result = self.daily_results[trade_date]\n daily_result.add_trade(trade)\n\n # Calculate daily result by iteration.\n pre_close = 0\n start_pos = 0\n\n for daily_result in self.daily_results.values():\n daily_result.calculate_pnl(pre_close, start_pos, self.size, self.rate, self.slippage )\n\n pre_close = daily_result.close_price\n start_pos = daily_result.end_pos\n\n # Generate dataframe\n results = defaultdict(list)\n\n for daily_result in self.daily_results.values():\n for key, value in daily_result.__dict__.items():\n results[key].append(value)\n\n self.daily_df = DataFrame.from_dict(results).set_index('date')\n\n self.output('้ๆฅ็ฏๅธ็ไบ่ฎก็ฎๅฎๆ')\n return self.daily_df\n #----------------------------------------------------------------------\n def statistics_status(self,array):\n \"\"\"่ฟๅarrayๅๅผ๏ผๆ ๅๅทฎ๏ผๅๅบฆ๏ผๅณฐๅบฆ\"\"\"\n stats = scs.describe(array)\n return stats[2],np.sqrt(stats[3]),stats[4],stats[5] \n #----------------------------------------------------------------------\n def calculate_statistics(self, df: DataFrame = None,strategy_name=None,write_result=True):\n \"\"\"่ฎก็ฎๅๆต็ปๆ\"\"\"\n from pyecharts.charts import (Bar,Line,Graph,Gauge,Page)#ๆฑ็ถๅพ๏ผๆ็บฟๅพ๏ผๅ
ณ็ณปๅพ๏ผไปช่กจ็,ๅคๅพๅ่กจ\n from pyecharts import options as opts\n self.output('ๅผๅง่ฎก็ฎ็ญ็ฅ็ป่ฎกๆๆ ') \n if df is None:\n #ๅๅงๅ็ป่ฎกๅ้\n start_date = ''\n end_date = ''\n total_days = 0\n profit_days = 0\n loss_days = 0\n end_balance = 0\n max_drawdown = 0\n max_drawdown_percent = 0\n max_drawdown_duration = 0\n total_net_pnl = 0\n daily_net_pnl = 0\n total_commission = 0\n daily_commission = 0\n total_slippage = 0\n daily_slippage = 0\n total_turnover = 0\n daily_turnover = 0\n total_trade_count = 0\n daily_trade_count = 0\n total_return = 0\n annual_return = 0\n return_mean = 0\n return_std = 0\n return_skew = 0\n return_kurt = 0\n sharpe_ratio = 0\n calmar_ratio = 0\n return_drawdown = 0\n return_drawdown_ratio = 0\n sortino_info = 0\n omega_info = 0\n annual_volatility_info = 0\n cagr_info = 0\n annual_downside_risk = 0\n c_var = 0\n var_info = 0\n calmar_ratio = 0\n stability_return = 0\n tail_ratio_info = 0\n else:\n # Calculate balance related time series data\n trades_list =[] #ๆไบคๆ็ปๅ่กจ\n df['balance'] = df['net_pnl'].cumsum() + self.capital #ๆป่ต้\n df['return'] = (np.log(df['balance']) - np.log(df['balance'].shift(1))).fillna(0) #ๅๆถ็็\n df['highlevel'] = (df['balance'].rolling( min_periods=1, window=len(df), center=False).max()) #ๅๅผ้ซ็น\n df['drawdown'] = df['balance'] - df['highlevel']\n df['ddpercent'] = df['drawdown'] / df['highlevel'] * 100 #ๅๆค็พๅๆฏ\n # Calculate statistics value\n start_date = df.index[0]\n end_date = df.index[-1]\n\n total_days = len(df)\n profit_days = len(df[df['net_pnl'] > 0])\n loss_days = len(df[df['net_pnl'] < 0])\n\n end_balance = df['balance'].iloc[-1] #ๆ็ปๆถ็\n max_drawdown = df['drawdown'].min() #ๆๅคงๅๆค\n max_drawdown_percent = df['ddpercent'].min() #ๆๅคงๅๆค็\n #ๆๅคงๅๆคๆ๏ผไผๅๆถmax_drawdown_endๅฏ่ฝไธบNAN้่ฆๅๅผๅธธๅค็\n max_drawdown_end = df[\"drawdown\"].idxmin()\n if isinstance(max_drawdown_end,date):\n max_drawdown_start = df[\"balance\"][:max_drawdown_end].idxmax()\n max_drawdown_duration = (max_drawdown_end - max_drawdown_start).days\n else:\n max_drawdown_start = \"\"\n max_drawdown_end = \"\"\n max_drawdown_duration = 0\n\n total_net_pnl = df['net_pnl'].sum() #ๆปๅๅผ\n daily_net_pnl = total_net_pnl / total_days #ๆฅๅๅผ\n\n total_commission = df['commission'].sum() #ๆปๆ็ปญ่ดน\n daily_commission = total_commission / total_days\n\n total_slippage = df['slippage'].sum() #ๆปๆป็น\n daily_slippage = total_slippage / total_days\n\n total_turnover = df['turnover'].sum()\n daily_turnover = total_turnover / total_days\n\n total_trade_count = df['trade_count'].sum() #ๆปไบคๆๆฌกๆฐ\n daily_trade_count = total_trade_count / total_days\n\n total_return = (end_balance / self.capital - 1) * 100 #ๆปๆถ็็\n annual_return = total_return / total_days * TRADING_DAY #ๅนดๅๆถ็็ \n #ๆถ็็ๅๅผ๏ผๆ ๅๅทฎ๏ผๅๅบฆ๏ผๅณฐๅบฆ\n return_mean,return_std,return_skew, return_kurt = self.statistics_status(df['return'].values) \n #sortino_info\n sortino_info = sortino_ratio(df['return'])\n omega_info = omega_ratio(df['return'])\n #ๅนดๅๆณขๅจ็\n annual_volatility_info = annual_volatility(df['return'])\n #ๅนดๅๅคๅๅข้ฟ็\n cagr_info = cagr(df['return'])\n #ๅนดๅไธ่ก้ฃ้ฉ็\n annual_downside_risk = downside_risk(df['return'])\n \"\"\"CVaRๅณๆกไปถ้ฃ้ฉไปทๅผ๏ผๅ
ถๅซไนไธบๅจๆ่ต็ปๅ็ๆๅคฑ่ถ
่ฟๆไธช็ปๅฎVaRๅผ็ๆกไปถไธ๏ผ่ฏฅๆ่ต็ปๅ็ๅนณๅๆๅคฑๅผใ\"\"\"\n c_var = conditional_value_at_risk(df['return'])\n \"\"\"้ฃ้ฉไปทๅผ๏ผVaR๏ผๆฏๅฏนๆ่ตๆๅคฑ้ฃ้ฉ็ไธ็งๅบฆ้ใๅฎไผฐ่ฎกๅจๆญฃๅธธ็ๅธๅบๆกไปถไธ๏ผๅจ่ฎพๅฎ็ๆถ้ดๆฎต๏ผไพๅฆไธๅคฉ๏ผไธญ๏ผ\n ไธ็ปๆ่ตๅฏ่ฝ๏ผไปฅ็ปๅฎ็ๆฆ็๏ผๆๅคฑๅคๅฐใ้่ไธไธญ็ๅ
ฌๅธๅ็็ฎกๆบๆ้ๅธธไฝฟ็จVaRๆฅ่กก้ๅผฅ่กฅๅฏ่ฝๆๅคฑๆ้็่ตไบงๆฐ้\"\"\"\n var_info = value_at_risk(df['return'])\n #calmar_ratio:ๅนดๅๆถ็็ไธๅๅฒๆๅคงๅๆค็ไน้ด็ๆฏ็\n calmar_ratio = annual_return / abs(max_drawdown_percent)\n #ๆถ็็จณๅฎ็\n stability_return = stability_of_timeseries(df['return'])\n #ๅฐพ้จๆฏ็0.25 == 1/4,ๆถ็1๏ผ้ฃ้ฉ4\n tail_ratio_info = tail_ratio(df['return'])\n if return_std:\n sharpe_ratio = return_mean / return_std * np.sqrt(TRADING_DAY)\n else:\n sharpe_ratio = 0\n #ๆถ็ๅๆคๆฏ\n return_drawdown = -total_net_pnl/max_drawdown\n #ๆถ็็ๅๆค็ๆฏ\n return_drawdown_ratio = -total_return / max_drawdown_percent\n for index in range(len(df['balance'])):\n if index == 0:\n nets_pnl = 1\n else:\n nets_pnl = df['balance'][index]/df['balance'][index-1]-1\n self.net_value += nets_pnl\n self.net_value_list.append(round(float(self.net_value),3))\n #----------------------------------------------------------------------\n if write_result:\n self.output('-' * 70)\n if hasattr(self.strategy,'strategy_name'):\n self.output(f\"็ญ็ฅๅ็งฐ๏ผ{self.strategy.strategy_name},ไบคๆๆ ็๏ผ{self.vt_symbol}\")\n else:\n self.output(f\"็ญ็ฅๅ็งฐ๏ผ{strategy_name},ไบคๆๆ ็๏ผ{self.vt_symbol}\")\n self.output(f\"้ฆไธชไบคๆๆฅ๏ผ\\t{start_date}๏ผๆๅไบคๆๆฅ๏ผ\\t{end_date}๏ผๆปไบคๆๆฅ๏ผ\\t{total_days}\")\n self.output(f\"็ๅฉไบคๆๆฅ๏ผ\\t{profit_days}๏ผไบๆไบคๆๆฅ๏ผ\\t{loss_days}\")\n self.output(f\"่ตทๅง่ต้๏ผ\\t{self.capital:,.3f}๏ผ็ปๆ่ต้๏ผ\\t{end_balance:,.3f}\")\n self.output(f\"ๆป็ไบ๏ผ\\t{total_net_pnl:,.3f}\")\n self.output(f\"ๆปๆถ็็๏ผ\\t{total_return:,.3f}%,ๅคๅฉๅๅผ๏ผ\\t{self.net_value_list[-1]:,.3f}\")\n self.output(f\"ๆถ็ๅๆคๆฏ๏ผ\\t{return_drawdown:,.3f}\")\n self.output(f\"ๆถ็็ๅๆค็ๆฏ๏ผ\\t{return_drawdown_ratio:,.3f}\")\n self.output(f\"ๆๅคงๅๆค่ต้: \\t{max_drawdown:,.3f},ๆๅคงๅๆคๆฅๆ:\\t{max_drawdown_start}่ณ{max_drawdown_end},ๆๅคงๅๆคๅคฉๆฐ: \\t{max_drawdown_duration}\")\n self.output(f\"ๆๅคงๅๆค็: {max_drawdown_percent:,.3f}%\")\n self.output(f\"ๆปๆ็ปญ่ดน๏ผ\\t{total_commission:,.3f}\")\n self.output(f\"ๆปๆป็น๏ผ\\t{total_slippage:,.3f}\")\n self.output(f\"ๆปๆไบค้้ข๏ผ\\t{total_turnover:,.3f}\")\n self.output(f\"ๆปๆไบค็ฌๆฐ๏ผ\\t{total_trade_count}\")\n self.output(f\"ๆฅๅ็ไบ๏ผ\\t{daily_net_pnl:,.3f}\")\n self.output(f\"ๆฅๅๆ็ปญ่ดน๏ผ\\t{daily_commission:,.3f}\")\n self.output(f\"ๆฅๅๆป็น๏ผ\\t{daily_slippage:,.3f}\")\n self.output(f\"ๆฅๅๆไบค้้ข๏ผ\\t{daily_turnover:,.3f}\")\n self.output(f\"ๆฅๅๆไบค็ฌๆฐ๏ผ\\t{daily_trade_count:,.3f}\")\n self.output(f\"ๅนดๅๆถ็็๏ผ\\t{annual_return:,.3f}%\")\n self.output(f\"ๆฅๅๆถ็็๏ผ\\t{return_mean*100:,.3f}%๏ผๆถ็็ๆ ๅๅทฎ๏ผ\\t{return_std*100:,.3f}%๏ผๆถ็็ๅๅบฆ๏ผ\\t{return_skew:,.3f}๏ผๆถ็็ๅณฐๅบฆ๏ผ\\t{return_kurt:,.3f}\")\n self.output(f\"sharpe_ratio๏ผ\\t{sharpe_ratio:,.3f}\")\n self.output(f\"calmar_ratio๏ผ\\t{calmar_ratio:,.3f}\")\n self.output(f\"sortino_info๏ผ\\t{sortino_info:,.3f}\")\n self.output(f\"omega_info๏ผ\\t{omega_info:,.3f}\")\n self.output(f\"ๅนดๅๆณขๅจ็๏ผ\\t{annual_volatility_info:,.3f}\")\n self.output(f\"ๅนดๅๅคๅๅข้ฟ็๏ผ\\t{cagr_info:,.3f}\")\n self.output(f\"ๅนดๅไธ่ก้ฃ้ฉ็๏ผ\\t{annual_downside_risk:,.3f}\")\n self.output(f\"c_var๏ผ\\t{c_var:,.3f}\")\n self.output(f\"var_info๏ผ\\t{var_info:,.3f}\")\n self.output(f\"ๆถ็็จณๅฎ็๏ผ\\t{stability_return:,.3f}\")\n self.output(f\"ๅฐพ้จๆฏ็๏ผ\\t{tail_ratio_info:,.3f}\")\n #ๅๆต็ป่ฎก็ปๆๅไบคๆๆ็ปไฟๅญๅฐbacktesting_resultๆไปถๅคน\n if hasattr(self.strategy,'strategy_name'):\n symbol,exchange,gateway_name = extract_vt_symbol(self.vt_symbol)\n path_symbol = f\"{symbol}_{exchange.value}\"\n if platform.uname().system == \"Windows\":\n self.result_path = f\"C:\\\\ProgramData\\\\Anaconda3\\\\Lib\\\\site-packages\\\\vnpy-2.1.0-py3.7.egg\\\\vnpy\\\\app\\\\cta_strategy\\\\backtesting_result\\\\{datetime.now().date()}_bcaktesting_{path_symbol}_{self.strategy.strategy_name}.csv\"\n elif platform.uname().system == \"Linux\":\n self.result_path = f\"/home/xldistance/anaconda3/lib/python3.7/site-packages/vnpy/app/cta_strategy/backtesting_result/{datetime.now().date()}_bcaktesting_{path_symbol}_{self.strategy.strategy_name}.csv\"\n else:\n if platform.uname().system == \"Windows\":\n self.result_path = f\"C:\\\\ProgramData\\\\Anaconda3\\\\Lib\\\\site-packages\\\\vnpy-2.1.0-py3.7.egg\\\\vnpy\\\\app\\\\cta_strategy\\\\backtesting_result\\\\{datetime.now().date()}_bcaktesting_{strategy_name}.csv\"\n elif platform.uname().system == \"Linux\":\n self.result_path = f\"/home/xldistance/anaconda3/lib/python3.7/site-packages/vnpy/app/cta_strategy/backtesting_result/{datetime.now().date()}_bcaktesting_{strategy_name}.csv\"\n df.to_csv(self.result_path,encoding='utf_8_sig') #ไฟๅญๅๆต็ป่ฎกๆฐๆฎๅฐCSV\n #ไบคๆ็ฑป่ฝฌๅไธบๅฏ่ฏปๅญๅ
ธๅญๅฐๆฌๅฐcsv\n for trade_class in df['trades']:\n if trade_class:\n for trade in trade_class:\n trades_list.append(trade.__dict__)\n DataFrame(trades_list).to_csv(self.result_path.replace('_bcaktesting_','_trade_dict_'),encoding='utf_8_sig')\n #----------------------------------------------------------------------\n #pyecharts็ปๅพๅๅ
ฅhtml,mark_pointๆ ่ฎฐ็น๏ผmark_point_symbolๆ ่ฎฐ็นๅพๅฝข'circle', 'diamond', 'rounddiamond', 'triangle','pin', 'arrow'ๅฏ้\n bar_1 = Bar()\n bar_1.add_xaxis(df['balance'].index.tolist())\n if hasattr(self.strategy,'strategy_name'):\n bar_1.add_yaxis(f\"็ญ็ฅ:{self.vt_symbol}_{self.strategy.strategy_name}\\n\\nๆป่ต้\\n\\n่ตทๆญขๆถ้ด๏ผ{df['balance'].index[0]}่ณ{df['balance'].index[-1]}\",df['balance'].tolist()) #ไธปๆ ้ข\n else:\n bar_1.add_yaxis(f\"็ญ็ฅ:{self.vt_symbol}_{strategy_name}\\n\\nๆป่ต้\\n\\n่ตทๆญขๆถ้ด๏ผ{df['balance'].index[0]}่ณ{df['balance'].index[-1]}\",df['balance'].tolist()) #ไธปๆ ้ข\n bar_1.set_global_opts(opts.TitleOpts(title=f\"่ต้\\n\\nๆปๆถ็็๏ผ{total_return:,.3f}%\"),toolbox_opts=opts.ToolboxOpts()) #ๅฏๆ ้ข๏ผToolboxOpts่ฎพ็ฝฎๅทฅๅ
ท็ฎฑ้
็ฝฎ้กน \n bar_1.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) #็ณปๅ้
็ฝฎ้กน \n #ๆไบค่ฎฐๅฝ็ปๅพ\n trade_datetime = []\n trade_price = []\n for trade in trades_list:\n trade_datetime.append(trade[\"datetime\"])\n trade_price.append(trade[\"price\"])\n trades_opts_data = [opts.MarkPointItem(\n name = f\"orderid:{trade['orderid']}๏ผๆ ็๏ผ{trade['vt_symbol']}๏ผๆนๅ๏ผ{trade['direction'].value}๏ผ{trade['offset'].value}๏ผไปทๆ ผ๏ผ{trade['price']}๏ผๆไบค้๏ผ{trade['volume']}\", #ๆไบค่ฏฆ็ปไฟกๆฏๆทปๅ ๅฐname\n itemstyle_opts = opts.ItemStyleOpts(color= \"#ec0000\" if trade[\"direction\"].value == \"ๅค\" else \"#00da3c\"),\n coord = [trade[\"datetime\"],trade[\"price\"] * random.randrange(1000,1010) / 1000], #ๆ ๆณจ็ๅๆ \n value = trade[\"direction\"].value + trade[\"offset\"].value\n ) for trade in trades_list]\n\n bar_2 = Line()\n bar_2.add_xaxis(trade_datetime)\n bar_2.add_yaxis(f\"ไบคๆไปทๆ ผ๏ผไบคๆๆถ้ด๏ผ{trade_datetime[0]}่ณ{trade_datetime[-1]}\\n\\nๆไบค็ฌๆฐ๏ผ{len(trades_list)}\",trade_price) #ไธปๆ ้ข\n bar_2.set_global_opts(opts.TitleOpts(title=\"ไบคๆ่ฎฐๅฝ\"),toolbox_opts=opts.ToolboxOpts()) #่ฎพ็ฝฎๅทฅๅ
ท็ฎฑ้
็ฝฎ้กน\n bar_2.set_series_opts(label_opts=opts.LabelOpts(is_show=False), #ๆ ็ญพ้
็ฝฎ้กน\n markpoint_opts = opts.MarkPointOpts(data = trades_opts_data,\n #ๆ ่ฎฐ็ๅพๅฝขๅๅฝข๏ผ\"circle'\"๏ผๆนๅฝข๏ผ\"rect'\"๏ผ ๅ่งๆนๅฝข๏ผ\"roundRect'\"๏ผไธ่งๅฝข๏ผ\"triangle'\"๏ผ่ฑๅฝข๏ผ\"diamond'\"๏ผๆฐดๆปด๏ผ\"pin'\"๏ผ็ฎญๅคด๏ผ'arrow'\n symbol = \"pin\"\n ),\n itemstyle_opts = opts.ItemStyleOpts(color = \"#ec0000\",color0 = \"#00da3c\"),\n ) #็ณปๅ้
็ฝฎ้กน \n\n\n bar_3 = Bar()\n bar_3.add_xaxis(df['balance'].index.tolist())\n bar_3.add_yaxis(f\"ๅคๅฉๅๅผๆ้ซ็น๏ผ{max(self.net_value_list)}\\tๅคๅฉๅๅผๆไฝ็น๏ผ{min(self.net_value_list)}\",self.net_value_list)\n bar_3.set_global_opts(opts.TitleOpts(title=\"ๅคๅฉๅๅผ\"),toolbox_opts=opts.ToolboxOpts()) #่ฎพ็ฝฎๅทฅๅ
ท็ฎฑ้
็ฝฎ้กน \n bar_3.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) #็ณปๅ้
็ฝฎ้กน \n\n bar_4 = Bar()\n bar_4.add_xaxis(df['drawdown'].index.tolist())\n bar_4.add_yaxis(f\"ๅๆค่ต้\\n\\nๆๅคงๅๆค่ต้๏ผ{max_drawdown:,.3f}\\nๆๅคงๅๆคๆฅๆ: \\t{max_drawdown_start}่ณ{max_drawdown_end},ๆๅคงๅๆคๅคฉๆฐ: \\t{max_drawdown_duration}\",df['drawdown'].tolist())\n bar_4.set_global_opts(opts.TitleOpts(title=\"่ต้\"),toolbox_opts=opts.ToolboxOpts()) #่ฎพ็ฝฎๅทฅๅ
ท็ฎฑ้
็ฝฎ้กน \n bar_4.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) #็ณปๅ้
็ฝฎ้กน \n\n bar_5 = Bar()\n bar_5.add_xaxis(df['ddpercent'].index.tolist())\n bar_5.add_yaxis(f\"ๅๆค็พๅๆฏ\\n\\nๆๅคงๅๆค็๏ผ{max_drawdown_percent:,.3f}%\",df['ddpercent'].tolist())\n bar_5.set_global_opts(opts.TitleOpts(title=\"ๅๆค็พๅๆฏ\"),toolbox_opts=opts.ToolboxOpts()) #่ฎพ็ฝฎๅทฅๅ
ท็ฎฑ้
็ฝฎ้กน \n bar_5.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) #็ณปๅ้
็ฝฎ้กน \n\n bar_6 = Bar()\n bar_6.add_xaxis(df['net_pnl'].index.tolist())\n bar_6.add_yaxis(f\"ๆฅ็ไบ\\n\\nๆๅคงๆฅ็ๅฉ๏ผ{df['net_pnl'].max():,.3f}\\n\\nๆๅคงๆฅไบๆ๏ผ{df['net_pnl'].min():,.3f}\",df['net_pnl'].tolist())\n bar_6.set_global_opts(opts.TitleOpts(title=\"ๆฅ็ไบ\"),toolbox_opts=opts.ToolboxOpts()) #่ฎพ็ฝฎๅทฅๅ
ท็ฎฑ้
็ฝฎ้กน \n bar_6.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) #็ณปๅ้
็ฝฎ้กน \n\n for pnl_index in df['net_pnl'].index:\n month_date = f\"{pnl_index.year}-{pnl_index.month}\"\n if month_date == self.last_month_date:\n self.month_pnl += df['net_pnl'][pnl_index]\n else:\n #ๆไปฝๅไธไฟๅญๅฎ้
ๆไปฝๆถ็\n self.month_dict.update({month_date:self.month_pnl})\n for key,value in list(self.month_dict.items()):\n if isinstance(key,datetime):\n continue\n key = datetime.strptime(key,\"%Y-%m\") - relativedelta(months = 1)\n self.month_dict.update({key:value})\n #month_dictๅ ้คๅๅง็str้ฎๅผๅฏน\n for key,value in list(self.month_dict.items()):\n if isinstance(key,str):\n self.month_dict.pop(key)\n self.month_pnl = df['net_pnl'][pnl_index]\n self.last_month_date = month_date\n self.month_dict.pop(list(self.month_dict.keys())[0])\n max_month_pnl = max(self.month_dict.values())\n min_month_pnl = min(self.month_dict.values())\n bar_7 = Bar()\n bar_7.add_xaxis(list(self.month_dict.keys()))\n bar_7.add_yaxis(f\"ๆ็ไบ\\n\\nๆๅคงๆ็ๅฉ๏ผ{max_month_pnl:,.3f}\\n\\nๆๅคงๆไบๆ๏ผ{min_month_pnl:,.3f}\",list(self.month_dict.values()))\n bar_7.set_global_opts(opts.TitleOpts(title=\"ๆ็ไบ\"),toolbox_opts=opts.ToolboxOpts()) #่ฎพ็ฝฎๅทฅๅ
ท็ฎฑ้
็ฝฎ้กน \n bar_7.set_series_opts(label_opts=opts.LabelOpts(is_show=False)\n ) #็ณปๅ้
็ฝฎ้กน \n\n hist,bin_edges= np.histogram(df['net_pnl'], bins=50) \n bar_8 = Bar()\n bar_8.add_xaxis(bin_edges[1:].tolist())\n bar_8.add_yaxis(\"็ไบๅๅธ็ดๆนๅพ\",hist.tolist())\n bar_8.set_global_opts(opts.TitleOpts(title=\"้ขๆฐ\"),toolbox_opts=opts.ToolboxOpts()) #่ฎพ็ฝฎๅทฅๅ
ท็ฎฑ้
็ฝฎ้กน \n bar_8.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) #็ณปๅ้
็ฝฎ้กน \n\n bar_9 = Bar()\n bar_9.add_xaxis(df['commission'].index.tolist())\n bar_9.add_yaxis(f\"ๆฏๆฅๆ็ปญ่ดน\\n\\nๆฅๆ้ซๆ็ปญ่ดน:{df['commission'].max():,.3f}\",df['commission'].tolist())\n bar_9.set_global_opts(opts.TitleOpts(title=\"ๆ็ปญ่ดน\"),toolbox_opts=opts.ToolboxOpts()) #่ฎพ็ฝฎๅทฅๅ
ท็ฎฑ้
็ฝฎ้กน\n bar_9.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) #็ณปๅ้
็ฝฎ้กน \n\n page = Page()\n page.add(bar_1)\n page.add(bar_2)\n page.add(bar_3)\n page.add(bar_4)\n page.add(bar_5)\n page.add(bar_6)\n page.add(bar_7)\n page.add(bar_8)\n page.add(bar_9)\n #ๅพ่กจ็ปๆไฟๅญไธบhtml\n page.render(self.result_path.replace('.csv','.html'))\n #----------------------------------------------------------------------\n statistics = {\n 'start_date': start_date,\n 'end_date': end_date,\n 'total_days': total_days,\n 'profit_days': profit_days,\n 'loss_days': loss_days,\n 'capital': self.capital,\n 'end_balance': end_balance,\n 'max_drawdown': max_drawdown,\n 'max_drawdown_percent': max_drawdown_percent,\n \"max_drawdown_duration\": max_drawdown_duration, \n 'total_net_pnl': total_net_pnl,\n 'daily_net_pnl': daily_net_pnl,\n 'total_commission': total_commission,\n 'daily_commission': daily_commission,\n 'total_slippage': total_slippage,\n 'daily_slippage': daily_slippage,\n 'total_turnover': total_turnover,\n 'daily_turnover': daily_turnover,\n 'total_trade_count': total_trade_count,\n 'daily_trade_count': daily_trade_count,\n 'total_return': total_return,\n 'annual_return': annual_return,\n 'return_mean': return_mean,\n 'return_std': return_std,\n 'return_skew': return_skew,\n 'return_kurt': return_kurt,\n 'sharpe_ratio': sharpe_ratio,\n 'calmar_ratio': calmar_ratio,\n 'sortino_info': sortino_info,\n 'omega_info': omega_info,\n 'annual_volatility_info': annual_volatility_info,\n 'cagr_info': cagr_info,\n 'annual_downside_risk': annual_downside_risk,\n 'c_var': c_var,\n 'var_info': var_info,\n 'stability_return': stability_return,\n 'tail_ratio_info': tail_ratio_info,\n 'return_drawdown': return_drawdown,\n 'return_drawdown_ratio': return_drawdown_ratio,\n }\n for key,value in statistics.items():\n if value in (np.inf,-np.inf):\n value = 0\n statistics[key] = np.nan_to_num(value)\n self.output(\"็ญ็ฅ็ป่ฎกๆๆ ่ฎก็ฎๅฎๆ\") \n return statistics\n #----------------------------------------------------------------------\n def get_information_ratio(self,returns,benchmark=0.00008):\n #benchmarkๅบๅๆถ็็\n diff = returns - benchmark\n return np.mean(diff) / np.std(diff) * np.sqrt(TRADING_DAY)\n #----------------------------------------------------------------------\n def show_chart(self, df: DataFrame = None):\n \"\"\"matplotlib็ปๅพ\"\"\"\n if df is None:\n return\n\n plt.figure(figsize=(10, 16))\n\n balance_plot = plt.subplot(5, 1, 1)\n balance_plot.set_title('Balance')\n df['balance'].plot(legend=True)\n\n drawdown_plot = plt.subplot(5, 1, 2)\n drawdown_plot.set_title('Drawdown')\n drawdown_plot.fill_between(range(len(df)), df['drawdown'].values)\n\n drawdown_percent = plt.subplot(5, 1, 3)\n drawdown_percent.set_title('DrawdownPercent')\n drawdown_percent.fill_between(range(len(df)), df['ddpercent'].values)\n\n pnl_plot = plt.subplot(5, 1, 4)\n pnl_plot.set_title('Daily Pnl')\n df['net_pnl'].plot(kind='bar', legend=False, grid=False, xticks=[])\n\n distribution_plot = plt.subplot(5, 1, 5)\n distribution_plot.set_title('Daily Pnl Distribution')\n df['net_pnl'].hist(bins=50)\n\n plt.show()\n\n def run_optimization(self, optimization_setting: OptimizationSetting,target_reverse =True):\n \"\"\"ๅค่ฟ็จไผๅ\"\"\"\n # Get optimization setting and target\n settings = optimization_setting.generate_setting()\n target_name = optimization_setting.target_name\n\n if not settings:\n self.output('ไผๅๅๆฐ็ปๅไธบ็ฉบ๏ผ่ฏทๆฃๆฅ')\n return\n\n if not target_name:\n self.output('ไผๅ็ฎๆ ๆช่ฎพ็ฝฎ๏ผ่ฏทๆฃๆฅ')\n return\n\n # Use multiprocessing pool for running backtesting with different setting\n pool = multiprocessing.Pool(multiprocessing.cpu_count(), maxtasksperchild=1)\n\n results = []\n for setting in settings:\n result = (pool.apply_async(optimize, (\n target_name,\n self.strategy_class,\n setting,\n self.vt_symbol,\n self.start,\n self.rate,\n self.slippage,\n self.size,\n self.price_tick,\n self.capital,\n self.end,\n self.mode\n )))\n results.append(result)\n\n pool.close()\n pool.join()\n\n # Sort results and output\n result_values = [result.get() for result in results]\n result_values.sort(reverse=target_reverse, key=lambda result: result[1])\n\n for value in result_values:\n msg = f'ๅๆฐ๏ผ{value[0]}, ็ฎๆ ๏ผ{value[1]}'\n self.output(msg)\n\n return result_values\n\n def run_ga_optimization(self, optimization_setting: OptimizationSetting, population_size=200, ngen_size=30):\n \"\"\"้ไผ ็ฎๆณไผๅ\"\"\"\n # Get optimization setting and target\n settings = optimization_setting.generate_setting_ga()\n target_name = optimization_setting.target_name\n\n if not settings:\n self.output('ไผๅๅๆฐ็ปๅไธบ็ฉบ๏ผ่ฏทๆฃๆฅ')\n return\n\n if not target_name:\n self.output('ไผๅ็ฎๆ ๆช่ฎพ็ฝฎ๏ผ่ฏทๆฃๆฅ')\n return\n\n # Define parameter generation function\n def generate_parameter():\n ''''''\n return random.choice(settings)\n \n def mutate_individual(individual, indpb):\n ''''''\n size = len(individual)\n paramlist = generate_parameter()\n for i in range(size):\n if random.random() < indpb:\n individual[i] = paramlist[i]\n return individual,\n\n # Create ga object function\n global ga_target_name\n global ga_strategy_class\n global ga_setting\n global ga_vt_symbol\n global ga_interval\n global ga_start\n global ga_rate\n global ga_slippage\n global ga_size\n global ga_price_tick\n global ga_capital\n global ga_end\n global ga_mode\n\n ga_target_name = target_name\n ga_strategy_class = self.strategy_class\n ga_setting = settings[0]\n ga_vt_symbol = self.vt_symbol\n ga_interval = self.interval\n ga_start = self.start\n ga_rate = self.rate\n ga_slippage = self.slippage\n ga_size = self.size\n ga_price_tick = self.price_tick\n ga_capital = self.capital\n ga_end = self.end\n ga_mode = self.mode\n\n # Set up genetic algorithem\n toolbox = base.Toolbox() \n toolbox.register('individual', tools.initIterate, creator.Individual, generate_parameter) \n toolbox.register('population', tools.initRepeat, list, toolbox.individual) \n toolbox.register('mate', tools.cxTwoPoint) \n toolbox.register('mutate', mutate_individual, indpb=1) \n toolbox.register('evaluate', ga_optimize) \n toolbox.register('select', tools.selNSGA2) \n\n total_size = len(settings)\n pop_size = population_size #ๆ็พค้้ข็ไธชไฝๆฐ้\n lambda_ = int(pop_size * 0.5) #ๆฏไธไปฃไบง็็ๅญๅฅณๆฐ\n mu = int(pop_size * 0.25) #ๆฏไธไปฃ้ๆฉ็ไธชไฝๆฐ\n\n cxpb = 0.5 #็ง็พคๅ
้จไธชไฝ็ไบคๅๆฆ็ \n mutpb = 1 - cxpb #็ง็พคๅ
้จไธชไฝ็ๅๅผๆฆ็ \n ngen = ngen_size #ไบง็็ง็พคไปฃๆฐ,NGEN = 10่ฆ่ท10ไธช่ฝฎๅ\n \n pop = toolbox.population(pop_size) \n hof = tools.ParetoFront() # end result of pareto front\n\n stats = tools.Statistics(lambda ind: ind.fitness.values)\n np.set_printoptions(suppress=True)\n stats.register('mean', np.mean, axis=0)\n stats.register('std', np.std, axis=0)\n stats.register('min', np.min, axis=0)\n stats.register('max', np.max, axis=0)\n\n # Multiprocessing is not supported yet.\n # pool = multiprocessing.Pool(multiprocessing.cpu_count())\n # toolbox.register('map', pool.map)\n\n # Run ga optimization\n self.output(f'ๅๆฐไผๅ็ฉบ้ด๏ผ{total_size}')\n self.output(f'ๆฏไปฃๆ็พคๆปๆฐ๏ผ{pop_size}')\n self.output(f'ไผ่ฏ็ญ้ไธชๆฐ๏ผ{mu}')\n self.output(f'่ฟญไปฃๆฌกๆฐ๏ผ{ngen}')\n self.output(f'ไบคๅๆฆ็๏ผ{cxpb:.0%}')\n self.output(f'็ชๅๆฆ็๏ผ{mutpb:.0%}')\n\n start = time()\n\n algorithms.eaMuPlusLambda(\n pop, \n toolbox, \n mu, \n lambda_, \n cxpb, \n mutpb, \n ngen, \n stats,\n halloffame=hof\n ) \n \n end = time()\n cost = int((end - start))\n\n self.output(f'้ไผ ็ฎๆณไผๅๅฎๆ๏ผ่ๆถ{cost}็ง')\n \n # Return result list\n results = []\n\n for parameter_values in hof:\n setting = dict(parameter_values)\n target_value = ga_optimize(parameter_values)[0]\n results.append((setting, target_value, {}))\n self.output(results)\n return results\n\n def update_daily_close(self, price: float):\n ''''''\n d = self.datetime.date()\n\n daily_result = self.daily_results.get(d, None)\n if daily_result:\n daily_result.close_price = price\n else:\n self.daily_results[d] = DailyResult(d, price)\n\n def new_bar(self, bar: BarData):\n ''''''\n self.bar = bar\n self.datetime = bar.datetime\n\n self.cross_limit_order() #ๅ
ๆฎๅ้ไปทๅ\n self.cross_stop_order() #ๅๆฎๅๅๆญขๅ\n self.strategy.on_bar(bar) #ๆจ้K็บฟๅฐ็ญ็ฅไธญ\n self.update_postion() #ๆดๆฐๆไปๆฐๆฎ \n self.update_daily_close(bar.close_price)\n\n def new_tick(self, tick: TickData):\n ''''''\n self.tick = tick\n self.datetime = tick.datetime\n\n self.cross_limit_order()\n self.cross_stop_order()\n self.strategy.on_tick(tick)\n self.update_postion() #ๆดๆฐๆไปๆฐๆฎ \n self.update_daily_close(tick.last_price)\n\n def cross_limit_order(self):\n '''\n Cross limit order with last bar/tick data.\n '''\n if self.mode == BacktestingMode.BAR:\n long_cross_price = self.bar.low_price\n short_cross_price = self.bar.high_price\n long_best_price = self.bar.open_price\n short_best_price = self.bar.open_price\n else:\n long_cross_price = self.tick.ask_price_1\n short_cross_price = self.tick.bid_price_1\n long_best_price = long_cross_price\n short_best_price = short_cross_price\n\n for order in list(self.active_limit_orders.values()):\n is_submitting = False\n # Push order update with status 'not traded' (pending).\n if order.status == Status.SUBMITTING:\n is_submitting = True\n order.status = Status.NOTTRADED \n self.strategy.on_order(order)\n\n # Check whether limit orders can be filled.\n long_cross = (\n order.direction == Direction.LONG \n and order.price >= long_cross_price \n and 0 < long_cross_price < 9999999\n )\n\n short_cross = (\n order.direction == Direction.SHORT \n and order.price <= short_cross_price \n and 0 < short_cross_price < 9999999\n )\n\n if not long_cross and not short_cross:\n continue\n\n # Push order udpate with status 'all traded' (filled).\n order.traded = order.volume\n order.status = Status.ALLTRADED\n self.active_limit_orders.pop(order.vt_orderid) \n self.strategy.on_order(order)\n\n # Push trade update\n self.trade_count += 1\n #็ดๆฅๆไบคไฝฟ็จorder.priceไฝไธบไบคๆไปท\n trade_price = order.price\n #่ฎก็ฎๆๅๆไบคไปท\n if long_cross:\n if is_submitting:\n trade_price = min(order.price, long_best_price)\n pos_change = order.volume\n elif short_cross:\n if is_submitting:\n trade_price = max(order.price, short_best_price)\n pos_change = -order.volume\n trade = TradeData(\n symbol=order.symbol,\n exchange=order.exchange,\n orderid=order.orderid,\n tradeid=str(self.trade_count),\n direction=order.direction,\n offset=order.offset,\n price=trade_price,\n volume=order.volume,\n date=self.datetime.strftime('%Y%m%d'),\n time=self.datetime.strftime('%H:%M:%S'),\n gateway_name=self.gateway_name,\n )\n trade.datetime = self.datetime\n\n self.strategy.pos += pos_change\n self.strategy.on_trade(trade)\n\n self.trades[trade.vt_tradeid] = trade\n # ๆดๆฐๆไปๆฐๆฎ\n self.update_postion(trade=trade)\n def cross_stop_order(self):\n '''\n Cross stop order with last bar/tick data.\n '''\n if self.mode == BacktestingMode.BAR:\n long_cross_price = self.bar.high_price\n short_cross_price = self.bar.low_price\n long_best_price = self.bar.open_price\n short_best_price = self.bar.open_price\n else:\n long_cross_price = self.tick.last_price\n short_cross_price = self.tick.last_price\n long_best_price = long_cross_price\n short_best_price = short_cross_price\n\n for stop_order in list(self.active_stop_orders.values()):\n # Check whether stop order can be triggered.\n long_cross = (\n stop_order.direction == Direction.LONG \n and stop_order.price <= long_cross_price\n )\n\n short_cross = (\n stop_order.direction == Direction.SHORT \n and stop_order.price >= short_cross_price\n )\n\n if not long_cross and not short_cross:\n continue\n\n # Create order data.\n self.limit_order_count += 1\n\n order = OrderData(\n symbol=self.symbol,\n exchange=self.exchange,\n orderid=str(self.limit_order_count),\n direction=stop_order.direction,\n offset=stop_order.offset,\n price=stop_order.price,\n volume=stop_order.volume,\n traded=stop_order.volume,\n status=Status.ALLTRADED,\n gateway_name=self.gateway_name,\n )\n order.datetime = self.datetime\n self.limit_orders[order.vt_orderid] = order\n\n # Create trade data.\n if long_cross:\n trade_price = max(stop_order.price, long_best_price)\n pos_change = order.volume\n else:\n trade_price = min(stop_order.price, short_best_price)\n pos_change = -order.volume\n self.trade_count += 1\n\n trade = TradeData(\n symbol=order.symbol,\n exchange=order.exchange,\n orderid=order.orderid,\n tradeid=str(self.trade_count),\n direction=order.direction,\n offset=order.offset,\n price=trade_price,\n volume=order.volume,\n date=self.datetime.strftime('%Y%m%d'),\n time=self.datetime.strftime('%H:%M:%S'),\n gateway_name=self.gateway_name,\n )\n trade.datetime = self.datetime\n\n self.trades[trade.vt_tradeid] = trade\n\n # Update stop order.\n stop_order.vt_orderids.append(order.vt_orderid)\n stop_order.status = StopOrderStatus.TRIGGERED\n if stop_order.stop_orderid in self.active_stop_orders:\n self.active_stop_orders.pop(stop_order.stop_orderid)\n # Push update to strategy.\n self.strategy.on_stop_order(stop_order)\n self.strategy.on_order(order)\n\n self.strategy.pos += pos_change\n self.strategy.on_trade(trade)\n # ๆดๆฐๆไปๆฐๆฎ\n self.update_postion(trade=trade)\n #----------------------------------------------------------------------\n def update_postion(self, trade =None):\n \"\"\"ๆไป็ๆง\"\"\"\n if trade:\n if trade.direction == Direction.LONG:\n # ๅๅคๅ\n if trade.offset == Offset.OPEN:\n long_cost = self.long_avg_cost * self.long_pos\n long_cost += trade.price * trade.volume\n # ๅนณๅๆๆฌ\n self.long_pos += trade.volume\n if self.long_pos > 0:\n self.long_avg_cost = round(long_cost / float(self.long_pos), 3)\n\n else:\n self.short_pos -= trade.volume\n else:\n # ๅ็ฉบๅ\n if trade.offset == Offset.OPEN:\n short_cost = self.short_avg_cost * self.short_pos\n short_cost += trade.price * trade.volume\n # ๅนณๅๆๆฌ\n self.short_pos += trade.volume\n if self.short_pos > 0:\n self.short_avg_cost = round(short_cost / float(self.short_pos), 3)\n else:\n self.long_pos -= trade.volume\n # ๅค/็ฉบไปๆถ็\n if self.mode == BacktestingMode.BAR:\n last_price = self.bar.close_price\n else:\n last_price = self.tick.last_price\n long_profit = (last_price - self.long_avg_cost) * self.long_pos * self.size\n short_profit = (self.short_avg_cost - last_price) * self.short_pos * self.size\n if trade:\n if trade.direction == Direction.LONG:\n self.long_profit_total += long_profit \n if trade.direction == Direction.SHORT:\n self.short_profit_total += short_profit \n self.strategy.long_pos = self.long_pos\n self.strategy.short_pos = self.short_pos\n self.strategy.long_profit = long_profit\n self.strategy.short_profit = short_profit\n self.strategy.balance = self.capital + self.long_profit_total + self.short_profit_total\n\n def load_bar(\n self, vt_symbol: str, days: int, interval: Interval, callback: Callable\n ):\n ''''''\n self.days = days\n self.callback = callback\n\n def load_tick(self, vt_symbol: str, days: int, callback: Callable):\n ''''''\n self.days = days\n self.callback = callback\n\n def send_order(self,vt_symbol, direction: Direction, offset: Offset, price: float, volume: float, stop: bool,line:bool, lock: bool,strategy:CtaTemplate,order_type:OrderType):\n \"\"\"\n ๅ้ๅงๆๅ\n \"\"\"\n #ไปทๆ ผ๏ผๅๅ้ๅๆดๅฐๆๅฐๅๅจ\n price = round_to(price, self.price_tick)\n volume = round_to(volume, 1)\n #่ฟๆปค้ๆญฃๅธธไธๅไปทๆ ผไธๅงๆ้\n if not price or not volume:\n return []\n #ๅนณไปๆถไปไฝไธบ0็ดๆฅ่ฟๅ\n if offset == Offset.CLOSE:\n if self.strategy.pos == 0:\n return\n if stop:\n vt_orderid = self.send_stop_order(vt_symbol,direction, offset, price, volume,self,OrderType.STOP)\n else:\n vt_orderid = self.send_limit_order(vt_symbol,direction, offset, price, volume,self,OrderType.LIMIT)\n return [vt_orderid]\n\n def send_stop_order(self, vt_symbol, direction: Direction, offset: Offset, price: float, volume: float, strategy: CtaTemplate, order_type: OrderType, ):\n \"\"\"\n ๅ้ๆฌๅฐๅๆญขๅ\n \"\"\"\n self.stop_order_count += 1\n stop_order = StopOrder(\n vt_symbol=self.vt_symbol,\n direction=direction,\n offset=offset,\n price=price,\n volume=volume,\n stop_orderid=f'{STOPORDER_PREFIX}.{self.stop_order_count}',\n strategy_name=self.strategy.strategy_name,\n )\n self.strategy.on_stop_order(stop_order)\n self.active_stop_orders[stop_order.stop_orderid] = stop_order\n self.stop_orders[stop_order.stop_orderid] = stop_order\n return stop_order.stop_orderid\n\n def send_limit_order(self, vt_symbol, direction: Direction, offset: Offset, price: float, volume: float, strategy: CtaTemplate, order_type: OrderType, ):\n ''''''\n self.limit_order_count += 1\n \n order = OrderData(\n symbol=self.symbol,\n exchange=self.exchange,\n orderid=str(self.limit_order_count),\n direction=direction,\n offset=offset,\n price=price,\n volume=volume,\n traded=volume,\n status=Status.NOTTRADED,\n gateway_name=self.gateway_name,\n )\n order.datetime = self.datetime\n self.active_limit_orders[order.vt_orderid] = order\n self.limit_orders[order.vt_orderid] = order\n\n return order.vt_orderid\n\n def cancel_order(self, strategy: CtaTemplate, vt_orderid: str):\n \"\"\"\n ็จvt_orderidๆค้ๅงๆๅ\n \"\"\"\n if vt_orderid.startswith(STOPORDER_PREFIX):\n self.cancel_stop_order(strategy, vt_orderid)\n else:\n self.cancel_limit_order(strategy, vt_orderid)\n\n def cancel_stop_order(self, strategy: CtaTemplate, vt_orderid: str):\n ''''''\n if vt_orderid not in self.active_stop_orders:\n return\n stop_order = self.active_stop_orders.pop(vt_orderid)\n stop_order.status = StopOrderStatus.CANCELLED\n \n self.strategy.on_stop_order(stop_order)\n\n def cancel_limit_order(self, strategy: CtaTemplate, vt_orderid: str):\n ''''''\n if vt_orderid not in self.active_limit_orders:\n return\n order = self.active_limit_orders.pop(vt_orderid) \n order.status = Status.CANCELLED\n self.strategy.on_order(order)\n\n def cancel_all(self, strategy: CtaTemplate):\n '''\n Cancel all orders, both limit and stop.\n '''\n vt_orderids = list(self.active_limit_orders.keys())\n for vt_orderid in vt_orderids:\n self.cancel_limit_order(strategy, vt_orderid)\n\n stop_orderids = list(self.active_stop_orders.keys())\n for vt_orderid in stop_orderids:\n self.cancel_stop_order(strategy, vt_orderid)\n\n def write_log(self, msg: str, strategy: CtaTemplate = None):\n \"\"\"\n Write log message.\n \"\"\"\n msg = '{0}\\t{1}'.format(self.datetime,msg)\n self.logs.append(msg)\n \n def send_email(self, msg: str, strategy: CtaTemplate = None):\n '''\n Send email to default receiver.\n '''\n pass\n\n def sync_strategy_data(self, strategy: CtaTemplate = None):\n pass\n def get_engine_type(self):\n '''\n Return engine type.\n '''\n return self.engine_type\n\n def put_strategy_event(self, strategy: CtaTemplate):\n '''\n Put an event to update strategy status.\n '''\n pass\n\n def output(self, msg):\n '''\n Output message of backtesting engine.\n '''\n print(f'{datetime.now()}\\t{msg}')\n def get_all_trades(self):\n \"\"\"\n Return all trade data of current backtesting result.\n \"\"\"\n return list(self.trades.values())\n\n def get_all_orders(self):\n \"\"\"\n Return all limit order data of current backtesting result.\n \"\"\"\n return list(self.limit_orders.values())\n\n def get_all_daily_results(self):\n \"\"\"\n Return all daily result data.\n \"\"\"\n return list(self.daily_results.values())\n\n\nclass DailyResult:\n ''''''\n\n def __init__(self, date: date, close_price: float):\n ''''''\n self.date = date\n self.close_price = close_price\n self.pre_close = 0\n\n self.trades = []\n self.trade_count = 0\n\n self.start_pos = 0\n self.end_pos = 0\n\n self.turnover = 0\n self.commission = 0\n self.slippage = 0\n\n self.trading_pnl = 0\n self.holding_pnl = 0\n self.total_pnl = 0\n self.net_pnl = 0\n def add_trade(self, trade: TradeData):\n ''''''\n self.trades.append(trade)\n\n def calculate_pnl(\n self,\n pre_close: float,\n start_pos: float,\n size: int,\n rate: float,\n slippage: float,\n ):\n ''''''\n self.pre_close = pre_close\n\n # Holding pnl is the pnl from holding position at day start\n self.start_pos = start_pos\n self.end_pos = start_pos\n self.holding_pnl = self.start_pos * (self.close_price - self.pre_close) * size\n\n # Trading pnl is the pnl from new trade during the day\n self.trade_count = len(self.trades)\n\n for trade in self.trades:\n if trade.direction == Direction.LONG:\n pos_change = trade.volume\n else:\n pos_change = -trade.volume\n\n turnover = trade.price * trade.volume * size\n\n self.trading_pnl += pos_change * (self.close_price - trade.price) * size\n self.end_pos += pos_change\n self.turnover += turnover\n self.commission += turnover * rate\n self.slippage += trade.volume * size * slippage\n\n # Net pnl takes account of commission and slippage cost\n self.total_pnl = self.trading_pnl + self.holding_pnl\n self.net_pnl = self.total_pnl - self.commission - self.slippage\n\n\ndef optimize(\n target_name: str,\n strategy_class: CtaTemplate,\n setting: dict,\n vt_symbol: str,\n start: datetime,\n rate: float,\n slippage: float,\n size: float,\n price_tick: float,\n capital: int,\n end: datetime,\n mode: BacktestingMode\n):\n '''\n Function for running in multiprocessing.pool\n '''\n engine = BacktestingEngine()\n engine.clear_data()\n engine.set_parameters(\n vt_symbol=vt_symbol,\n start=start,\n rate=rate,\n slippage=slippage,\n size=size,\n price_tick=price_tick,\n capital=capital,\n end=end,\n mode=mode\n )\n engine.add_strategy(strategy_class, setting)\n engine.load_data()\n engine.run_backtesting()\n daily_df = engine.calculate_result()\n statistics = engine.calculate_statistics(daily_df,write_result=False)\n target_value = statistics[target_name]\n return (str(setting), target_value, statistics)\n\n\n@lru_cache(maxsize=1000000)\ndef _ga_optimize(parameter_values: tuple):\n ''''''\n setting = dict(parameter_values)\n\n result = optimize(\n ga_target_name,\n ga_strategy_class,\n setting,\n ga_vt_symbol,\n ga_start,\n ga_rate,\n ga_slippage,\n ga_size,\n ga_price_tick,\n ga_capital,\n ga_end,\n ga_mode\n )\n return (result[1],)\n\n\ndef ga_optimize(parameter_values: list):\n ''''''\n return _ga_optimize(tuple(parameter_values))\n\n@lru_cache(maxsize=10)\ndef load_bar_data(\n symbol: str,\n exchange: Exchange,\n interval: Interval,\n start: datetime,\n end: datetime\n):\n \"\"\"barๆฐๆฎredisๅบๅๅๅญๅ\"\"\"\n file_name = f\"{symbol}_{exchange.value}_{start.date()}_{end.date()}_bar\"\n redis_data = REDIS_CLIENT.hget(file_name, file_name)\n if not redis_data:\n bar_data = database_manager.load_bar_data( symbol, exchange, interval, start, end )\n REDIS_CLIENT.hset(file_name, file_name, zlib.compress(pickle.dumps(bar_data), 5)) \n else:\n bar_data = pickle.loads(zlib.decompress(redis_data))\n return bar_data\n \"\"\"ๆฐๆฎ็ผๅญไธบpklๆ ผๅผๅฐๆฌๅฐ็กฌ็\"\"\"\n\"\"\" dir_path = f\"H:\\\\pickle_data\\\\\"\n file_name = f\"{symbol}_{exchange.value}_{start.date()}_{end.date()}_bar\"\n pickle_path = dir_path + file_name + \".pkl\"\n data_size =0 \n if not os.path.exists(pickle_path):\n bar_data = database_manager.load_bar_data( symbol, exchange, interval, start, end )\n pickle_file = open(pickle_path,'wb') \n pickle.dump(bar_data,pickle_file)\n pickle_file.close()\n else: \n pickle_file = open(pickle_path,'rb')\n bar_data =pickle.load(pickle_file)\n pickle_file.close()\n #pickle_dataๆไปถๅคนๅคงไบ50Gๅ ้ค็ผๅญๆฐๆฎ\n for dirpath, dirnames, filenames in os.walk(dir_path):\n for file_name in filenames: #ๅฝๅ็ฎๅฝๆๆๆไปถๅ\n data_size += os.path.getsize(dirpath + file_name)\n if data_size / (1024 ** 3) > 50:\n for dirpath, dirnames, filenames in os.walk(dir_path):\n for file_name in filenames: \n os.remove(dirpath + file_name) \n return bar_data\"\"\"\n\n@lru_cache(maxsize=10)\ndef load_tick_data(\n symbol: str,\n exchange: Exchange,\n start: datetime,\n end: datetime\n):\n \"\"\"tickๆฐๆฎredisๅบๅๅๅญๅ\"\"\"\n file_name = f\"{symbol}_{exchange.value}_{start.date()}_{end.date()}_tick\"\n redis_data = REDIS_CLIENT.hget(file_name, file_name)\n if not redis_data:\n tick_data = database_manager.load_tick_data( symbol, exchange, start, end )\n REDIS_CLIENT.hset(file_name, file_name, zlib.compress(pickle.dumps(tick_data), 5)) \n else:\n tick_data = pickle.loads(zlib.decompress(redis_data))\n return tick_data\n \"\"\"ๆฐๆฎ็ผๅญไธบpklๆ ผๅผๅฐๆฌๅฐ็กฌ็\"\"\"\n\"\"\" dir_path = f\"H:\\\\pickle_data\\\\\"\n file_name = f\"{symbol}_{exchange.value}_{start.date()}_{end.date()}_tick\"\n pickle_path = dir_path + file_name + \".pkl\"\n data_size =0 \n if not os.path.exists(pickle_path):\n tick_data = database_manager.load_tick_data( symbol, exchange, start, end )\n pickle_file = open(pickle_path,'wb') \n pickle.dump(tick_data,pickle_file)\n pickle_file.close()\n else: \n pickle_file = open(pickle_path,'rb')\n tick_data =pickle.load(pickle_file)\n pickle_file.close()\n #pickle_dataๆไปถๅคนๅคงไบ50Gๅ ้ค็ผๅญๆฐๆฎ\n for dirpath, dirnames, filenames in os.walk(dir_path):\n for file_name in filenames: #ๅฝๅ็ฎๅฝๆๆๆไปถๅ\n data_size += os.path.getsize(dirpath + file_name)\n if data_size / (1024 ** 3) > 50:\n for dirpath, dirnames, filenames in os.walk(dir_path):\n for file_name in filenames: \n os.remove(dirpath + file_name) \n return tick_data\"\"\"\n# GA related global value\nga_end = None\nga_mode = None\nga_target_name = None\nga_strategy_class = None\nga_setting = None\nga_vt_symbol = None\nga_interval = None\nga_start = None\nga_rate = None\nga_slippage = None\nga_size = None\nga_price_tick = None\nga_capital = None"
] | [
[
"matplotlib.pyplot.style.use",
"numpy.mean",
"numpy.histogram",
"scipy.stats.describe",
"matplotlib.pyplot.figure",
"pandas.DataFrame",
"numpy.set_printoptions",
"numpy.seterr",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"numpy.log",
"numpy.sqrt",
"numpy.std",
"numpy.nan_to_num",
"pandas.DataFrame.from_dict"
]
] |
GabrielUlisses/pandas | [
"6430d5324ae2b602b314a7851e9c1f4c5313cceb"
] | [
"pandas/tests/util/test_hashing.py"
] | [
"import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import DataFrame, Index, MultiIndex, Series\nimport pandas._testing as tm\nfrom pandas.core.util.hashing import hash_tuples\nfrom pandas.util import hash_array, hash_pandas_object\n\n\[email protected](\n params=[\n Series([1, 2, 3] * 3, dtype=\"int32\"),\n Series([None, 2.5, 3.5] * 3, dtype=\"float32\"),\n Series([\"a\", \"b\", \"c\"] * 3, dtype=\"category\"),\n Series([\"d\", \"e\", \"f\"] * 3),\n Series([True, False, True] * 3),\n Series(pd.date_range(\"20130101\", periods=9)),\n Series(pd.date_range(\"20130101\", periods=9, tz=\"US/Eastern\")),\n Series(pd.timedelta_range(\"2000\", periods=9)),\n ]\n)\ndef series(request):\n return request.param\n\n\[email protected](params=[True, False])\ndef index(request):\n return request.param\n\n\ndef _check_equal(obj, **kwargs):\n \"\"\"\n Check that hashing an objects produces the same value each time.\n\n Parameters\n ----------\n obj : object\n The object to hash.\n kwargs : kwargs\n Keyword arguments to pass to the hashing function.\n \"\"\"\n a = hash_pandas_object(obj, **kwargs)\n b = hash_pandas_object(obj, **kwargs)\n tm.assert_series_equal(a, b)\n\n\ndef _check_not_equal_with_index(obj):\n \"\"\"\n Check the hash of an object with and without its index is not the same.\n\n Parameters\n ----------\n obj : object\n The object to hash.\n \"\"\"\n if not isinstance(obj, Index):\n a = hash_pandas_object(obj, index=True)\n b = hash_pandas_object(obj, index=False)\n\n if len(obj):\n assert not (a == b).all()\n\n\ndef test_consistency():\n # Check that our hash doesn't change because of a mistake\n # in the actual code; this is the ground truth.\n result = hash_pandas_object(Index([\"foo\", \"bar\", \"baz\"]))\n expected = Series(\n np.array(\n [3600424527151052760, 1374399572096150070, 477881037637427054],\n dtype=\"uint64\",\n ),\n index=[\"foo\", \"bar\", \"baz\"],\n )\n tm.assert_series_equal(result, expected)\n\n\ndef test_hash_array(series):\n arr = series.values\n tm.assert_numpy_array_equal(hash_array(arr), hash_array(arr))\n\n\[email protected](\n \"arr2\", [np.array([3, 4, \"All\"]), np.array([3, 4, \"All\"], dtype=object)]\n)\ndef test_hash_array_mixed(arr2):\n result1 = hash_array(np.array([\"3\", \"4\", \"All\"]))\n result2 = hash_array(arr2)\n\n tm.assert_numpy_array_equal(result1, result2)\n\n\[email protected](\"val\", [5, \"foo\", pd.Timestamp(\"20130101\")])\ndef test_hash_array_errors(val):\n msg = \"must pass a ndarray-like\"\n with pytest.raises(TypeError, match=msg):\n hash_array(val)\n\n\ndef test_hash_tuples():\n tuples = [(1, \"one\"), (1, \"two\"), (2, \"one\")]\n result = hash_tuples(tuples)\n\n expected = hash_pandas_object(MultiIndex.from_tuples(tuples)).values\n tm.assert_numpy_array_equal(result, expected)\n\n result = hash_tuples(tuples[0])\n assert result == expected[0]\n\n\[email protected](\"val\", [5, \"foo\", pd.Timestamp(\"20130101\")])\ndef test_hash_tuples_err(val):\n msg = \"must be convertible to a list-of-tuples\"\n with pytest.raises(TypeError, match=msg):\n hash_tuples(val)\n\n\ndef test_multiindex_unique():\n mi = MultiIndex.from_tuples([(118, 472), (236, 118), (51, 204), (102, 51)])\n assert mi.is_unique is True\n\n result = hash_pandas_object(mi)\n assert result.is_unique is True\n\n\ndef test_multiindex_objects():\n mi = MultiIndex(\n levels=[[\"b\", \"d\", \"a\"], [1, 2, 3]],\n codes=[[0, 1, 0, 2], [2, 0, 0, 1]],\n names=[\"col1\", \"col2\"],\n )\n recons = mi._sort_levels_monotonic()\n\n # These are equal.\n assert mi.equals(recons)\n assert Index(mi.values).equals(Index(recons.values))\n\n\[email protected](\n \"obj\",\n [\n Series([1, 2, 3]),\n Series([1.0, 1.5, 3.2]),\n Series([1.0, 1.5, np.nan]),\n Series([1.0, 1.5, 3.2], index=[1.5, 1.1, 3.3]),\n Series([\"a\", \"b\", \"c\"]),\n Series([\"a\", np.nan, \"c\"]),\n Series([\"a\", None, \"c\"]),\n Series([True, False, True]),\n Series(dtype=object),\n Index([1, 2, 3]),\n Index([True, False, True]),\n DataFrame({\"x\": [\"a\", \"b\", \"c\"], \"y\": [1, 2, 3]}),\n DataFrame(),\n tm.makeMissingDataframe(),\n tm.makeMixedDataFrame(),\n tm.makeTimeDataFrame(),\n tm.makeTimeSeries(),\n tm.makeTimedeltaIndex(),\n tm.makePeriodIndex(),\n Series(tm.makePeriodIndex()),\n Series(pd.date_range(\"20130101\", periods=3, tz=\"US/Eastern\")),\n MultiIndex.from_product(\n [range(5), [\"foo\", \"bar\", \"baz\"], pd.date_range(\"20130101\", periods=2)]\n ),\n MultiIndex.from_product([pd.CategoricalIndex(list(\"aabc\")), range(3)]),\n ],\n)\ndef test_hash_pandas_object(obj, index):\n _check_equal(obj, index=index)\n _check_not_equal_with_index(obj)\n\n\ndef test_hash_pandas_object2(series, index):\n _check_equal(series, index=index)\n _check_not_equal_with_index(series)\n\n\[email protected](\n \"obj\", [Series([], dtype=\"float64\"), Series([], dtype=\"object\"), Index([])]\n)\ndef test_hash_pandas_empty_object(obj, index):\n # These are by-definition the same with\n # or without the index as the data is empty.\n _check_equal(obj, index=index)\n\n\[email protected](\n \"s1\",\n [\n Series([\"a\", \"b\", \"c\", \"d\"]),\n Series([1000, 2000, 3000, 4000]),\n Series(pd.date_range(0, periods=4)),\n ],\n)\[email protected](\"categorize\", [True, False])\ndef test_categorical_consistency(s1, categorize):\n # see gh-15143\n #\n # Check that categoricals hash consistent with their values,\n # not codes. This should work for categoricals of any dtype.\n s2 = s1.astype(\"category\").cat.set_categories(s1)\n s3 = s2.cat.set_categories(list(reversed(s1)))\n\n # These should all hash identically.\n h1 = hash_pandas_object(s1, categorize=categorize)\n h2 = hash_pandas_object(s2, categorize=categorize)\n h3 = hash_pandas_object(s3, categorize=categorize)\n\n tm.assert_series_equal(h1, h2)\n tm.assert_series_equal(h1, h3)\n\n\ndef test_categorical_with_nan_consistency():\n c = pd.Categorical.from_codes(\n [-1, 0, 1, 2, 3, 4], categories=pd.date_range(\"2012-01-01\", periods=5, name=\"B\")\n )\n expected = hash_array(c, categorize=False)\n\n c = pd.Categorical.from_codes([-1, 0], categories=[pd.Timestamp(\"2012-01-01\")])\n result = hash_array(c, categorize=False)\n\n assert result[0] in expected\n assert result[1] in expected\n\n\[email protected](\"obj\", [pd.Timestamp(\"20130101\")])\ndef test_pandas_errors(obj):\n msg = \"Unexpected type for hashing\"\n with pytest.raises(TypeError, match=msg):\n hash_pandas_object(obj)\n\n\ndef test_hash_keys():\n # Using different hash keys, should have\n # different hashes for the same data.\n #\n # This only matters for object dtypes.\n obj = Series(list(\"abc\"))\n\n a = hash_pandas_object(obj, hash_key=\"9876543210123456\")\n b = hash_pandas_object(obj, hash_key=\"9876543210123465\")\n\n assert (a != b).all()\n\n\ndef test_invalid_key():\n # This only matters for object dtypes.\n msg = \"key should be a 16-byte string encoded\"\n\n with pytest.raises(ValueError, match=msg):\n hash_pandas_object(Series(list(\"abc\")), hash_key=\"foo\")\n\n\ndef test_already_encoded(index):\n # If already encoded, then ok.\n obj = Series(list(\"abc\")).str.encode(\"utf8\")\n _check_equal(obj, index=index)\n\n\ndef test_alternate_encoding(index):\n obj = Series(list(\"abc\"))\n _check_equal(obj, index=index, encoding=\"ascii\")\n\n\[email protected](\"l_exp\", range(8))\[email protected](\"l_add\", [0, 1])\ndef test_same_len_hash_collisions(l_exp, l_add):\n length = 2 ** (l_exp + 8) + l_add\n s = tm.rands_array(length, 2)\n\n result = hash_array(s, \"utf8\")\n assert not result[0] == result[1]\n\n\ndef test_hash_collisions():\n # Hash collisions are bad.\n #\n # https://github.com/pandas-dev/pandas/issues/14711#issuecomment-264885726\n hashes = [\n \"Ingrid-9Z9fKIZmkO7i7Cn51Li34pJm44fgX6DYGBNj3VPlOH50m7HnBlPxfIwFMrcNJNMP6PSgLmwWnInciMWrCSAlLEvt7JkJl4IxiMrVbXSa8ZQoVaq5xoQPjltuJEfwdNlO6jo8qRRHvD8sBEBMQASrRa6TsdaPTPCBo3nwIBpE7YzzmyH0vMBhjQZLx1aCT7faSEx7PgFxQhHdKFWROcysamgy9iVj8DO2Fmwg1NNl93rIAqC3mdqfrCxrzfvIY8aJdzin2cHVzy3QUJxZgHvtUtOLxoqnUHsYbNTeq0xcLXpTZEZCxD4PGubIuCNf32c33M7HFsnjWSEjE2yVdWKhmSVodyF8hFYVmhYnMCztQnJrt3O8ZvVRXd5IKwlLexiSp4h888w7SzAIcKgc3g5XQJf6MlSMftDXm9lIsE1mJNiJEv6uY6pgvC3fUPhatlR5JPpVAHNSbSEE73MBzJrhCAbOLXQumyOXigZuPoME7QgJcBalliQol7YZ9\", # noqa: E501\n \"Tim-b9MddTxOWW2AT1Py6vtVbZwGAmYCjbp89p8mxsiFoVX4FyDOF3wFiAkyQTUgwg9sVqVYOZo09Dh1AzhFHbgij52ylF0SEwgzjzHH8TGY8Lypart4p4onnDoDvVMBa0kdthVGKl6K0BDVGzyOXPXKpmnMF1H6rJzqHJ0HywfwS4XYpVwlAkoeNsiicHkJUFdUAhG229INzvIAiJuAHeJDUoyO4DCBqtoZ5TDend6TK7Y914yHlfH3g1WZu5LksKv68VQHJriWFYusW5e6ZZ6dKaMjTwEGuRgdT66iU5nqWTHRH8WSzpXoCFwGcTOwyuqPSe0fTe21DVtJn1FKj9F9nEnR9xOvJUO7E0piCIF4Ad9yAIDY4DBimpsTfKXCu1vdHpKYerzbndfuFe5AhfMduLYZJi5iAw8qKSwR5h86ttXV0Mc0QmXz8dsRvDgxjXSmupPxBggdlqUlC828hXiTPD7am0yETBV0F3bEtvPiNJfremszcV8NcqAoARMe\", # noqa: E501\n ]\n\n # These should be different.\n result1 = hash_array(np.asarray(hashes[0:1], dtype=object), \"utf8\")\n expected1 = np.array([14963968704024874985], dtype=np.uint64)\n tm.assert_numpy_array_equal(result1, expected1)\n\n result2 = hash_array(np.asarray(hashes[1:2], dtype=object), \"utf8\")\n expected2 = np.array([16428432627716348016], dtype=np.uint64)\n tm.assert_numpy_array_equal(result2, expected2)\n\n result = hash_array(np.asarray(hashes, dtype=object), \"utf8\")\n tm.assert_numpy_array_equal(result, np.concatenate([expected1, expected2], axis=0))\n\n\ndef test_hash_with_tuple():\n # GH#28969 array containing a tuple raises on call to arr.astype(str)\n # apparently a numpy bug github.com/numpy/numpy/issues/9441\n\n df = pd.DataFrame({\"data\": [tuple(\"1\"), tuple(\"2\")]})\n result = hash_pandas_object(df)\n expected = Series([10345501319357378243, 8331063931016360761], dtype=np.uint64)\n tm.assert_series_equal(result, expected)\n\n df2 = pd.DataFrame({\"data\": [tuple([1]), tuple([2])]})\n result = hash_pandas_object(df2)\n expected = Series([9408946347443669104, 3278256261030523334], dtype=np.uint64)\n tm.assert_series_equal(result, expected)\n\n # require that the elements of such tuples are themselves hashable\n\n df3 = pd.DataFrame({\"data\": [tuple([1, []]), tuple([2, {}])]})\n with pytest.raises(TypeError, match=\"unhashable type: 'list'\"):\n hash_pandas_object(df3)\n\n\ndef test_hash_object_none_key():\n # https://github.com/pandas-dev/pandas/issues/30887\n result = pd.util.hash_pandas_object(Series([\"a\", \"b\"]), hash_key=None)\n expected = Series([4578374827886788867, 17338122309987883691], dtype=\"uint64\")\n tm.assert_series_equal(result, expected)\n"
] | [
[
"pandas._testing.assert_numpy_array_equal",
"pandas.timedelta_range",
"pandas.Series",
"pandas._testing.makePeriodIndex",
"numpy.asarray",
"pandas._testing.assert_series_equal",
"pandas._testing.makeMissingDataframe",
"pandas.Timestamp",
"pandas._testing.makeMixedDataFrame",
"pandas.util.hash_pandas_object",
"pandas.date_range",
"pandas._testing.makeTimedeltaIndex",
"pandas.MultiIndex.from_tuples",
"pandas.core.util.hashing.hash_tuples",
"pandas.Index",
"numpy.array",
"pandas._testing.makeTimeDataFrame",
"pandas._testing.makeTimeSeries",
"pandas.DataFrame",
"pandas._testing.rands_array",
"pandas.MultiIndex",
"pandas.util.hash_array",
"numpy.concatenate"
]
] |
carterbox/xdesign | [
"2ab9f5835b518a7c5b564243d365c8ee4410156f"
] | [
"src/xdesign/metrics/fullref.py"
] | [
"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"Defines full-referene image quality metricsself.\n\nThese methods require a ground truth in order to make a quality assessment.\n\n.. moduleauthor:: Daniel J Ching <[email protected]>\n\"\"\"\n\n__author__ = \"Daniel Ching\"\n__copyright__ = \"Copyright (c) 2016, UChicago Argonne, LLC.\"\n__docformat__ = 'restructuredtext en'\n__all__ = [\n 'pcc',\n 'ImageQuality',\n 'ssim',\n 'msssim',\n]\n\nimport warnings\n\nimport numpy as np\nfrom scipy import ndimage\n\nwarnings.filterwarnings(\n 'ignore',\n 'From scipy 0\\.13\\.0, the output shape of zoom\\(\\) '\n 'is calculated with round\\(\\) instead of int\\(\\)'\n)\n\n\ndef pcc(A, B, masks=None):\n \"\"\"Return the Pearson product-moment correlation coefficients (PCC).\n\n Parameters\n -------------\n A, B : ndarray\n The two images to be compared\n masks : list of ndarrays, optional\n If supplied, the data under each mask is computed separately.\n\n Returns\n ----------------\n covariances : array, list of arrays\n\n \"\"\"\n covariances = []\n if masks is None:\n data = np.vstack((np.ravel(A), np.ravel(B)))\n return np.corrcoef(data)\n\n for m in masks:\n weights = m[m > 0]\n masked_B = B[m > 0]\n masked_A = A[m > 0]\n data = np.vstack((masked_A, masked_B))\n # covariances.append(np.cov(data,aweights=weights))\n covariances.append(np.corrcoef(data))\n\n return covariances\n\n\nclass ImageQuality(object):\n \"\"\"Store information about image quality.\n\n Attributes\n ----------\n img0 : array\n img1 : array\n Stacks of reference and deformed images.\n metrics : dict\n A dictionary with image quality information organized by scale.\n ``metric[scale] = (mean_quality, quality_map)``\n method : string\n The metric used to calculate the quality\n\n \"\"\"\n\n def __init__(self, original, reconstruction):\n self.img0 = original.astype(np.float)\n self.img1 = reconstruction.astype(np.float)\n\n self.scales = None\n self.mets = None\n self.maps = None\n self.method = ''\n\n def quality(self, method=\"MSSSIM\", L=1.0, **kwargs):\n \"\"\"Compute the full-reference image quality of each image pair.\n\n Available methods include SSIM :cite:`wang:02`, MSSSIM :cite:`wang:03`,\n VIFp :cite:`Sheikh:15`, and FSIM :cite:`zhang:11`.\n\n Parameters\n ----------\n method : string, optional, (default: MSSSIM)\n The quality metric desired for this comparison.\n Options include: SSIM, MSSSIM, VIFp, FSIM\n L : scalar\n The dynamic range of the data. This value is 1 for float\n representations and 2^bitdepth for integer representations.\n\n \"\"\"\n dictionary = {\n \"SSIM\": ssim,\n \"MSSSIM\": msssim,\n \"VIFp\": vifp,\n \"FSIM\": fsim\n }\n try:\n method_func = dictionary[method]\n except KeyError:\n ValueError(\"That method is not implemented.\")\n\n self.method = method\n\n if self.img0.ndim > 2:\n self.mets = list()\n self.maps = list()\n\n for i in range(self.img0.shape[2]):\n\n scales, mets, maps = method_func(\n self.img0[:, :, i], self.img1[:, :, i], L=L, **kwargs\n )\n\n self.scales = scales\n self.mets.append(mets)\n self.maps.append(maps)\n\n self.mets = np.stack(self.mets, axis=1)\n\n newmaps = []\n for level in range(len(self.maps[0])):\n this_level = []\n for m in self.maps:\n this_level.append(m[level])\n\n this_level = np.stack(this_level, axis=2)\n newmaps.append(this_level)\n\n self.maps = newmaps\n\n else:\n self.scales, self.mets, self.maps = method_func(\n self.img0, self.img1, L=L, **kwargs\n )\n\n\ndef _join_metrics(A, B):\n \"\"\"Join two image metric dictionaries.\"\"\"\n for key in list(B.keys()):\n if key in A:\n A[key][0] = np.concatenate((A[key][0], B[key][0]))\n\n A[key][1] = np.concatenate(\n (np.atleast_3d(A[key][1]), np.atleast_3d(B[key][1])), axis=2\n )\n\n else:\n A[key] = B[key]\n\n return A\n\n\ndef vifp(img0, img1, nlevels=5, sigma=1.2, L=None):\n \"\"\"Return the Visual Information Fidelity (VIFp) of two images.\n\n in a multiscale pixel domain with scalar.\n\n Parameters\n ----------\n img0 : array\n img1 : array\n Two images for comparison.\n nlevels : scalar\n The number of levels to measure quality.\n sigma : scalar\n The size of the quality filter at the smallest scale.\n\n Returns\n -------\n metrics : dict\n A dictionary with image quality information organized by scale.\n ``metric[scale] = (mean_quality, quality_map)``\n The valid range for VIFp is (0, 1].\n\n .. centered:: COPYRIGHT NOTICE\n\n Copyright (c) 2005 The University of Texas at Austin. All rights reserved.\n\n Permission is hereby granted, without written agreement and without license\n or royalty fees, to use, copy, modify, and distribute this code (the source\n files) and its documentation for any purpose, provided that the copyright\n notice in its entirety appear in all copies of this code, and the original\n source of this code, Laboratory for Image and Video Engineering (LIVE,\n http://live.ece.utexas.edu) at the University of Texas at Austin (UT\n Austin, http://www.utexas.edu), is acknowledged in any publication that\n reports research using this code. The research is to be cited in the\n bibliography as: H. R. Sheikh and A. C. Bovik, \"Image Information and\n Visual Quality\", IEEE Transactions on Image Processing, (to appear). IN NO\n EVENT SHALL THE UNIVERSITY OF TEXAS AT AUSTIN BE LIABLE TO ANY PARTY FOR\n DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT\n OF THE USE OF THIS DATABASE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY\n OF TEXAS AT AUSTIN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE\n UNIVERSITY OF TEXAS AT AUSTIN SPECIFICALLY DISCLAIMS ANY WARRANTIES,\n INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY\n AND FITNESS FOR A PARTICULAR PURPOSE. THE DATABASE PROVIDED HEREUNDER IS ON\n AN \"AS IS\" BASIS, AND THE UNIVERSITY OF TEXAS AT AUSTIN HAS NO OBLIGATION\n TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n .. centered:: END COPYRIGHT NOTICE\n \"\"\"\n _full_reference_input_check(img0, img1, sigma, nlevels, L)\n\n sigmaN_sq = 2 # used to tune response\n eps = 1e-10\n\n scales = np.zeros(nlevels)\n mets = np.zeros(nlevels)\n maps = [None] * nlevels\n\n for level in range(0, nlevels):\n # Downsample (using ndimage.zoom to prevent sampling bias)\n if (level > 0):\n img0 = ndimage.zoom(img0, 0.5)\n img1 = ndimage.zoom(img1, 0.5)\n\n mu0 = ndimage.gaussian_filter(img0, sigma)\n mu1 = ndimage.gaussian_filter(img1, sigma)\n\n sigma0_sq = ndimage.gaussian_filter((img0 - mu0)**2, sigma)\n sigma1_sq = ndimage.gaussian_filter((img1 - mu1)**2, sigma)\n sigma01 = ndimage.gaussian_filter((img0 - mu0) * (img1 - mu1), sigma)\n\n g = sigma01 / (sigma0_sq + eps)\n sigmav_sq = sigma1_sq - g * sigma01\n\n # Calculate VIF\n numator = np.log2(1 + g**2 * sigma0_sq / (sigmav_sq + sigmaN_sq))\n denator = np.sum(np.log2(1 + sigma0_sq / sigmaN_sq))\n\n vifmap = numator / denator\n vifp = np.sum(vifmap)\n # Normalize the map because we want values between 1 and 0\n vifmap *= vifmap.size\n\n scale = sigma * 2**level\n\n scales[level] = scale\n mets[level] = vifp\n maps[level] = vifmap\n\n return scales, mets, maps\n\n\n# def fsim(img0, img1, nlevels=5, nwavelets=16, L=None):\n# \"\"\"FSIM Index with automatic downsampling, Version 1.0\n#\n# An implementation of the algorithm for calculating the Feature SIMilarity\n# (FSIM) index was ported to Python. This implementation only considers the\n# luminance component of images. For multichannel images, convert to\n# grayscale first. Dynamic range should be 0-255.\n#\n# Parameters\n# ----------\n# img0 : array\n# img1 : array\n# Two images for comparison.\n# nlevels : scalar\n# The number of levels to measure quality.\n# nwavelets : scalar\n# The number of wavelets to use in the phase congruency calculation.\n#\n# Returns\n# -------\n# metrics : dict\n# A dictionary with image quality information organized by scale.\n# ``metric[scale] = (mean_quality, quality_map)``\n# The valid range for FSIM is (0, 1].\n#\n#\n# References\n# ----------\n# Lin Zhang, Lei Zhang, Xuanqin Mou, and David Zhang,\"FSIM: a feature\n# similarity index for image qualtiy assessment\", IEEE Transactions on Image\n# Processing, vol. 20, no. 8, pp. 2378-2386, 2011.\n#\n# .. centered:: COPYRIGHT NOTICE\n#\n# Copyright (c) 2010 Lin ZHANG, Lei Zhang, Xuanqin Mou and David Zhang.\n# All Rights Reserved.\n#\n# Permission to use, copy, or modify this software and its documentation\n# for educational and research purposes only and without fee is here\n# granted, provided that this copyright notice and the original authors'\n# names appear on all copies and supporting documentation. This program\n# shall not be used, rewritten, or adapted as the basis of a commercial\n# software or hardware product without first obtaining permission of the\n# authors. The authors make no representations about the suitability of\n# this software for any purpose. It is provided \"as is\" without express\n# or implied warranty.\n#\n# .. centered:: END COPYRIGHT NOTICE\n# \"\"\"\n# _full_reference_input_check(img0, img1, 1.2, nlevels, L)\n# if nwavelets < 1:\n# raise ValueError('There must be at least one wavelet level.')\n#\n# Y1 = img0\n# Y2 = img1\n#\n# scales = np.zeros(nlevels)\n# mets = np.zeros(nlevels)\n# maps = [None] * nlevels\n#\n# for level in range(0, nlevels):\n# # sigma = 1.2 is approximately correct because the width of the scharr\n# # and min wavelet filter (phase congruency filter) is 3.\n# sigma = 1.2 * 2**level\n#\n# F = 2 # Downsample (using ndimage.zoom to prevent sampling bias)\n# Y1 = ndimage.zoom(Y1, 1/F)\n# Y2 = ndimage.zoom(Y2, 1/F)\n#\n# # Calculate the phase congruency maps\n# [PC1, Orient1, ft1, T1] = phase.phasecongmono(Y1, nscale=nwavelets)\n# [PC2, Orient2, ft2, T2] = phase.phasecongmono(Y2, nscale=nwavelets)\n#\n# # Calculate the gradient magnitude map using Scharr filters\n# dx = np.array([[3., 0., -3.],\n# [10., 0., -10.],\n# [3., 0., -3.]]) / 16\n# dy = np.array([[3., 10., 3.],\n# [0., 0., 0.],\n# [-3., -10., -3.]]) / 16\n#\n# IxY1 = ndimage.filters.convolve(Y1, dx)\n# IyY1 = ndimage.filters.convolve(Y1, dy)\n# gradientMap1 = np.sqrt(IxY1**2 + IyY1**2)\n#\n# IxY2 = ndimage.filters.convolve(Y2, dx)\n# IyY2 = ndimage.filters.convolve(Y2, dy)\n# gradientMap2 = np.sqrt(IxY2**2 + IyY2**2)\n#\n# # Calculate the FSIM\n# T1 = 0.85 # fixed and depends on dynamic range of PC values\n# T2 = 160 # fixed and depends on dynamic range of GM values\n# PCSimMatrix = (2 * PC1 * PC2 + T1) / (PC1**2 + PC2**2 + T1)\n# gradientSimMatrix = ((2 * gradientMap1 * gradientMap2 + T2) /\n# (gradientMap1**2 + gradientMap2**2 + T2))\n# PCm = np.maximum(PC1, PC2)\n# FSIMmap = gradientSimMatrix * PCSimMatrix\n# FSIM = np.sum(FSIMmap * PCm) / np.sum(PCm)\n#\n# scales[level] = sigma\n# mets[level] = FSIM\n# maps[level] = FSIMmap\n#\n# return scales, mets, maps\n\n\ndef msssim(\n img0,\n img1,\n nlevels=5,\n sigma=1.2,\n L=1.0,\n K=(0.01, 0.03),\n alpha=4,\n beta_gamma=None\n):\n \"\"\"Multi-Scale Structural SIMilarity index (MS-SSIM).\n\n Parameters\n ----------\n img0 : array\n img1 : array\n Two images for comparison.\n nlevels : int\n The max number of levels to analyze\n sigma : float\n Sets the standard deviation of the gaussian filter. This setting\n determines the minimum scale at which quality is assessed.\n L : scalar\n The dynamic range of the data. This value is 1 for float\n representations and 2^bitdepth for integer representations.\n K : 2-tuple\n A list of two constants which help prevent division by zero.\n alpha : float\n The exponent which weights the contribution of the luminance term.\n beta_gamma : list\n The exponent which weights the contribution of the contrast and\n structure terms at each level.\n\n Returns\n -------\n metrics : dict\n A dictionary with image quality information organized by scale.\n ``metric[scale] = (mean_quality, quality_map)``\n The valid range for SSIM is [-1, 1].\n\n\n References\n ----------\n Multi-scale Structural Similarity Index (MS-SSIM)\n Z. Wang, E. P. Simoncelli and A. C. Bovik, \"Multi-scale structural\n similarity for image quality assessment,\" Invited Paper, IEEE Asilomar\n Conference on Signals, Systems and Computers, Nov. 2003\n \"\"\"\n _full_reference_input_check(img0, img1, sigma, nlevels, L)\n # The relative imporance of each level as determined by human experiment\n if beta_gamma is None:\n beta_gamma = np.array([0.0448, 0.2856, 0.3001, 0.2363, 0.1333]) * 4\n assert nlevels < 6, \"Not enough beta_gamma weights for more than 5 levels\"\n scales = np.zeros(nlevels)\n maps = [None] * nlevels\n original_shape = np.array(img0.shape)\n for level in range(0, nlevels):\n scale, ssim_mean, ssim_map = ssim(\n img0,\n img1,\n sigma=sigma,\n L=L,\n K=K,\n scale=sigma,\n alpha=0 if level < (nlevels - 1) else alpha,\n beta_gamma=beta_gamma[level]\n )\n # Always take the direct ratio between original and downsampled maps\n # to prevent resizing mismatch for odd sizes\n ratio = original_shape / np.array(ssim_map.shape)\n scales[level] = scale * ratio[0]\n maps[level] = ndimage.zoom(ssim_map, ratio, prefilter=False, order=0)\n\n if level == nlevels - 1:\n break\n # Downsample (using ndimage.zoom to prevent sampling bias)\n # Images become half the size\n img0 = ndimage.zoom(img0, 0.5)\n img1 = ndimage.zoom(img1, 0.5)\n\n ms_ssim_map = np.nanprod(maps, axis=0)\n ms_ssim_mean = np.nanmean(ms_ssim_map)\n return scales, ms_ssim_mean, ms_ssim_map\n\n\ndef ssim(\n img1,\n img2,\n sigma=1.2,\n L=1,\n K=(0.01, 0.03),\n scale=None,\n alpha=4,\n beta_gamma=4\n):\n \"\"\"Return the Structural SIMilarity index (SSIM) of two images.\n\n A modified version of the Structural SIMilarity index (SSIM) based on an\n implementation by Helder C. R. de Oliveira, based on the implementation by\n Antoine Vacavant, ISIT lab, [email protected]\n http://isit.u-clermont1.fr/~anvacava\n\n Attributes\n ----------\n img1 : array\n img2 : array\n Two images for comparison.\n sigma : float\n Sets the standard deviation of the gaussian filter. This setting\n determines the minimum scale at which quality is assessed.\n L : scalar\n The dynamic range of the data. The difference between the\n minimum and maximum of the data: 2^bitdepth for integer\n representations.\n K : 2-tuple\n A list of two constants which help prevent division by zero.\n alpha : float\n The exponent which weights the contribution of the luminance term.\n beta_gamma : list\n The exponent which weights the contribution of the contrast and\n structure terms at each level.\n\n Returns\n -------\n metrics : dict\n A dictionary with image quality information organized by scale.\n ``metric[scale] = (mean_quality, quality_map)``\n The valid range for SSIM is [-1, 1].\n\n\n References\n ----------\n Z. Wang, A. C. Bovik, H. R. Sheikh and E. P. Simoncelli. Image quality\n assessment: From error visibility to structural similarity. IEEE\n Transactions on Image Processing, 13(4):600--612, 2004.\n\n Z. Wang and A. C. Bovik. Mean squared error: Love it or leave it? - A new\n look at signal fidelity measures. IEEE Signal Processing Magazine,\n 26(1):98--117, 2009.\n\n Silvestre-Blanes, J., & Pรฉrez-Llorรฉns, R. (2011, September). SSIM and their\n dynamic range for image quality assessment. In ELMAR, 2011 Proceedings\n (pp. 93-96). IEEE.\n \"\"\"\n _full_reference_input_check(img1, img2, sigma, 1, L)\n if scale is not None and scale <= 0:\n raise ValueError(\"Scale cannot be negative or zero.\")\n assert L > 0, \"L, the dynamic range must be larger than 0.\"\n c_1 = (K[0] * L)**2\n c_2 = (K[1] * L)**2\n c_3 = c_2 * 0.5\n # Means obtained by Gaussian filtering of inputs\n mu_1 = ndimage.filters.gaussian_filter(img1, sigma)\n mu_2 = ndimage.filters.gaussian_filter(img2, sigma)\n # Squares of means\n mu_1_sq = mu_1**2\n mu_2_sq = mu_2**2\n mu_1_mu_2 = mu_1 * mu_2\n # Variances obtained by Gaussian filtering of inputs' squares\n sigma_1_sq = ndimage.filters.gaussian_filter(img1**2, sigma) - mu_1_sq\n sigma_2_sq = ndimage.filters.gaussian_filter(img2**2, sigma) - mu_2_sq\n # Covariance\n sigma_12 = ndimage.filters.gaussian_filter(img1 * img2, sigma) - mu_1_mu_2\n # Standard deviations multiplied\n sigma_1_sigma_2 = np.sqrt(sigma_1_sq * sigma_2_sq)\n # Division by zero is prevented by adding c_1 and c_2\n numerator1 = 2 * mu_1_mu_2 + c_1 # luminance\n denominator1 = mu_1_sq + mu_2_sq + c_1 # luminace\n numerator2 = 2 * sigma_1_sigma_2 + c_2 # contrast\n denominator2 = sigma_1_sq + sigma_2_sq + c_2 # constrast\n numerator3 = sigma_12 + c_3 # structure\n denominator3 = sigma_1_sigma_2 + c_3 # structure\n\n if (c_1 > 0) and (c_2 > 0):\n with np.errstate(invalid='ignore'):\n ssim_map = (\n (numerator1 / denominator1)**alpha *\n ((numerator2 * numerator3) /\n (denominator2 * denominator3))**beta_gamma\n )\n else:\n ssim_map = np.ones(numerator1.shape)\n index = (denominator1 * denominator2 > 0)\n ssim_map[index] = (\n (numerator1[index] / denominator1[index])**alpha *\n ((numerator2[index] * numerator3[index]) /\n (denominator2[index] * denominator3[index]))**beta_gamma\n )\n # Sometimes c_1 and c_2 don't do their job of stabilizing the result\n with np.errstate(invalid='ignore'):\n ssim_map[ssim_map > 1] = 1\n ssim_map[ssim_map < -1] = -1\n ssim_mean = np.nanmean(ssim_map)\n if scale is None:\n scale = sigma\n return scale, ssim_mean, ssim_map\n\n\ndef _full_reference_input_check(img0, img1, sigma, nlevels, L):\n \"\"\"Checks full reference quality measures for valid inputs.\"\"\"\n if nlevels <= 0:\n raise ValueError('nlevels must be >= 1.')\n if sigma < 1.2:\n raise ValueError('sigma < 1.2 is effective meaningless.')\n if np.min(img0.shape) / (2**(nlevels - 1)) < sigma * 2:\n raise ValueError(\n \"{nlevels} levels makes {shape} smaller than a filter\"\n \" size of 2 * {sigma}\".format(\n nlevels=nlevels, shape=img0.shape, sigma=sigma\n )\n )\n if L is not None and L < 1:\n raise ValueError(\"Dynamic range must be >= 1.\")\n if img0.shape != img1.shape:\n raise ValueError(\n \"original and reconstruction should be the \" + \"same shape\"\n )\n"
] | [
[
"numpy.sum",
"numpy.ones",
"scipy.ndimage.zoom",
"numpy.stack",
"scipy.ndimage.filters.gaussian_filter",
"numpy.vstack",
"numpy.nanmean",
"numpy.atleast_3d",
"numpy.corrcoef",
"numpy.zeros",
"numpy.min",
"numpy.array",
"numpy.log2",
"numpy.nanprod",
"numpy.errstate",
"numpy.ravel",
"scipy.ndimage.gaussian_filter",
"numpy.sqrt",
"numpy.concatenate"
]
] |
WorldEditors/PaddleHelix | [
"7dbe947417538d7478fbab4438905b30c1d709c3"
] | [
"apps/pretrained_compound/pretrain_gnns/pretrain_contextpred.py"
] | [
"#!/usr/bin/python \n#-*-coding:utf-8-*- \n# Copyright (c) 2020 PaddlePaddle 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\"\"\"\npretrain context pred\n\"\"\"\n\nimport os\nfrom os.path import join, exists\nimport sys\nimport json\nimport argparse\nimport numpy as np\n\nimport paddle\nimport paddle.fluid as fluid\nfrom paddle.fluid.incubate.fleet.collective import fleet\n\n\"\"\"\nEnable static graph mode.\n\"\"\"\npaddle.enable_static()\n\nfrom pahelix.model_zoo import PreGNNContextpredModel\nfrom pahelix.datasets import load_zinc_dataset\nfrom pahelix.featurizers import PreGNNContextPredFeaturizer\nfrom pahelix.utils.paddle_utils import load_partial_params, get_distributed_optimizer\nfrom pahelix.utils.splitters import RandomSplitter\nfrom pahelix.utils.compound_tools import CompoundConstants\n\n\ndef train(args, exe, train_prog, model, train_dataset, featurizer):\n \"\"\"\n Define the training function according to the given settings, calculate the training loss.\n\n Args:\n args,exe,train_prog,model,train_dataset,featurizer;\n Returns:\n the average of the list loss\n \n \"\"\"\n data_gen = train_dataset.iter_batch(\n batch_size=args.batch_size, \n num_workers=args.num_workers, \n shuffle=True,\n collate_fn=featurizer.collate_fn)\n list_loss = []\n for batch_id, feed_dict in enumerate(data_gen):\n train_loss, = exe.run(train_prog, \n feed=feed_dict, fetch_list=[model.loss], return_numpy=False)\n list_loss.append(np.array(train_loss).mean())\n return np.mean(list_loss)\n\n\ndef evaluate(args, exe, test_prog, model, test_dataset, featurizer):\n \"\"\"\n Define the evaluate function\n\n In the dataset, a proportion of labels are blank. So we use a `valid` tensor \n to help eliminate these blank labels in both training and evaluation phase.\n\n \"\"\"\n data_gen = test_dataset.iter_batch(\n batch_size=args.batch_size, \n num_workers=args.num_workers, \n shuffle=True,\n collate_fn=featurizer.collate_fn)\n list_loss = []\n for batch_id, feed_dict in enumerate(data_gen):\n test_loss, = exe.run(test_prog, \n feed=feed_dict, fetch_list=[model.loss], return_numpy=False)\n list_loss.append(np.array(test_loss).mean())\n return np.mean(list_loss)\n\n\ndef main(args):\n \"\"\"\n Call the configuration function of the model, build the model and load data, then start training.\n\n model_config:\n a json file with the model configurations,such as dropout rate ,learning rate,num tasks and so on;\n\n context_pooling:\n it means the pooling type of context prediction;\n \n PreGNNContextpredModel:\n It is an unsupervised pretraining model which use subgraphs to predict their surrounding graph structures. Our goal is to pre-train a GNN so that it maps nodes appearing in similar structural contexts to nearby embeddings.\n\n \"\"\"\n model_config = json.load(open(args.model_config, 'r'))\n if not args.dropout_rate is None:\n model_config['dropout_rate'] = args.dropout_rate\n model_config['context_pooling'] = args.context_pooling\n\n ### build model\n train_prog = fluid.Program()\n test_prog = fluid.Program()\n startup_prog = fluid.Program()\n with fluid.program_guard(train_prog, startup_prog):\n with fluid.unique_name.guard():\n model = PreGNNContextpredModel(model_config)\n model.forward()\n opt = fluid.optimizer.Adam(learning_rate=args.lr)\n if args.distributed:\n opt = get_distributed_optimizer(opt)\n opt.minimize(model.loss)\n with fluid.program_guard(test_prog, fluid.Program()):\n with fluid.unique_name.guard():\n model = PreGNNContextpredModel(model_config)\n model.forward(is_test=True)\n\n \"\"\"\n Use CUDAPlace for GPU training, or use CPUPlace for CPU training.\n\n \"\"\"\n\n place = fluid.CUDAPlace(int(os.environ.get('FLAGS_selected_gpus', 0))) \\\n if args.use_cuda else fluid.CPUPlace()\n exe = fluid.Executor(place)\n exe.run(startup_prog)\n\n if not args.init_model is None and not args.init_model == \"\":\n load_partial_params(exe, args.init_model, train_prog)\n\n ### load data\n \"\"\"\n PreGNNContextPredFeaturizer:\n It is used along with `PreGNNContextPredModel`. It inherits from the super class `Featurizer` which is used for feature extractions. The `Featurizer` has two functions: `gen_features` for converting from a single raw smiles to a single graph data, `collate_fn` for aggregating a sublist of graph data into a big batch.\n\n k is the number of layer,l1 and l2 are the different size of context,usually l1 < l2.\n\n splitter:\n split type of the dataset:random,scaffold,random with scaffold. Here is randomsplit.\n `ScaffoldSplitter` will firstly order the compounds according to Bemis-Murcko scaffold, \n then take the first `frac_train` proportion as the train set, the next `frac_valid` proportion as the valid set \n and the rest as the test set. `ScaffoldSplitter` can better evaluate the generalization ability of the model on \n out-of-distribution samples. Note that other splitters like `RandomSplitter`, `RandomScaffoldSplitter` \n and `IndexSplitter` is also available.\"\n \n \"\"\"\n k = model_config['layer_num']\n l1 = k - 1\n l2 = l1 + args.context_size\n featurizer = PreGNNContextPredFeaturizer(\n model.substruct_graph_wrapper, \n model.context_graph_wrapper, \n k, l1, l2)\n dataset = load_zinc_dataset(args.data_path, featurizer=featurizer)\n\n splitter = RandomSplitter()\n train_dataset, _, test_dataset = splitter.split(\n dataset, frac_train=0.9, frac_valid=0, frac_test=0.1)\n if args.distributed:\n indices = list(range(fleet.worker_index(), len(train_dataset), fleet.worker_num()))\n train_dataset = train_dataset[indices]\n print(\"Train/Test num: %s/%s\" % (len(train_dataset), len(test_dataset)))\n\n ### start train\n\n \"\"\"\n Load the train function and calculate the train loss and test loss in each epoch.\n Here we set the epoch is in range of max epoch,you can change it if you want. \n\n Then we will calculate the train loss ,test loss and print them.\n Finally we save the best epoch to the model according to the dataset.\n\n \"\"\"\n\n list_test_loss = []\n for epoch_id in range(args.max_epoch):\n train_loss = train(args, exe, train_prog, model, train_dataset, featurizer)\n test_loss = evaluate(args, exe, test_prog, model, test_dataset, featurizer)\n if not args.distributed or fleet.worker_index() == 0:\n fluid.io.save_params(exe, '%s/epoch%s' % (args.model_dir, epoch_id), train_prog)\n list_test_loss.append(test_loss)\n print(\"epoch:%d train/loss:%s\" % (epoch_id, train_loss))\n print(\"epoch:%d test/loss:%s\" % (epoch_id, test_loss))\n\n if not args.distributed or fleet.worker_index() == 0:\n best_epoch_id = np.argmax(list_test_loss)\n fluid.io.load_params(exe, '%s/epoch%d' % (args.model_dir, best_epoch_id), train_prog)\n fluid.io.save_params(exe, '%s/epoch_best' % (args.model_dir), train_prog)\n return list_test_loss[best_epoch_id]\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--use_cuda\", action='store_true', default=False)\n parser.add_argument(\"--distributed\", action='store_true', default=False)\n\n parser.add_argument(\"--batch_size\", type=int, default=256)\n parser.add_argument(\"--num_workers\", type=int, default=4)\n parser.add_argument(\"--max_epoch\", type=int, default=100)\n parser.add_argument(\"--lr\", type=float, default=0.001)\n parser.add_argument(\"--data_path\", type=str)\n\n parser.add_argument(\"--model_config\", type=str)\n parser.add_argument(\"--dropout_rate\", type=float)\n parser.add_argument(\"--init_model\", type=str)\n parser.add_argument(\"--model_dir\", type=str)\n\n parser.add_argument(\"--context_size\", type=int, default=3)\n parser.add_argument(\"--context_pooling\", type=str, default='average')\n args = parser.parse_args()\n \n main(args)\n\n"
] | [
[
"numpy.array",
"numpy.argmax",
"numpy.mean"
]
] |
janpipek/physt | [
"bf6b05952b7d09bbbdae2b077f0989c392eac13e"
] | [
"tests/test_special.py"
] | [
"import numpy as np\nimport pytest\n\nfrom physt import special_histograms\nfrom physt.special_histograms import AzimuthalHistogram, azimuthal\n\n\[email protected]\ndef empty_azimuthal() -> AzimuthalHistogram:\n return azimuthal(\n np.zeros(\n 0,\n ),\n np.zeros(\n 0,\n ),\n )\n\n\nclass TestAzimuthal:\n def test_simple_create(self):\n data = np.array([[0.01, 0.01], [0.01, 0.99], [-1, 0.01], [-1, -0.01]])\n x = data[:, 0]\n y = data[:, 1]\n h = special_histograms.azimuthal(x, y, bins=4)\n assert h.axis_name == \"phi\"\n assert h.bin_count == 4\n assert np.array_equal([2, 1, 1, 0], h.frequencies)\n\n def test_transform(self):\n t = AzimuthalHistogram.transform([1, 0])\n assert np.array_equal(t, 0)\n\n t = AzimuthalHistogram.transform([0, 2])\n assert np.allclose(t, np.pi / 2)\n\n data = np.asarray([[1, 0], [0, 2]])\n t = AzimuthalHistogram.transform(data)\n assert np.allclose(t, [0, np.pi / 2])\n\n def test_correct_find_bin(self, empty_azimuthal):\n assert empty_azimuthal.find_bin(1, transformed=True) == 2\n assert empty_azimuthal.find_bin((0.5, 0.877)) == 2\n\n def test_incorrect_find_bin(self, empty_azimuthal):\n with pytest.raises(ValueError) as exc:\n empty_azimuthal.find_bin(1)\n assert exc.match(\"AzimuthalHistogram can transform only\")\n with pytest.raises(ValueError) as exc:\n empty_azimuthal.find_bin((1, 2), transformed=True)\n assert exc.match(\"Non-scalar value for 1D histogram\")\n\n\nclass TestPolar:\n def test_simple_create(self):\n data = np.array([[0.01, 0.01], [0.01, 0.99], [-1, 0.01], [-1, -0.01]])\n x = data[:, 0]\n y = data[:, 1]\n h = special_histograms.polar(x, y, radial_bins=2, phi_bins=4)\n assert h.axis_names == (\"r\", \"phi\")\n assert h.bin_count == 8\n assert np.array_equal([[1, 0, 0, 0], [1, 1, 1, 0]], h.frequencies)\n\n def test_transform(self):\n t = special_histograms.PolarHistogram.transform([1, 0])\n assert np.array_equal(t, [1, 0])\n\n t = special_histograms.PolarHistogram.transform([0, 2])\n assert np.allclose(t, [2, np.pi / 2])\n\n data = np.asarray([[1, 0], [0, 2]])\n t = special_histograms.PolarHistogram.transform(data)\n assert np.allclose(t, [[1, 0], [2, np.pi / 2]])\n\n def test_densities(self):\n h = special_histograms.PolarHistogram(\n binnings=[[0, 1, 2], [0, 1, 2]], frequencies=[[1, 2], [3, 4]]\n )\n assert np.array_equal(h.densities, [[2, 4], [2, 4 / 1.5]])\n\n def test_projection_types(self):\n data = np.array([[0.01, 0.01], [0.01, 0.99], [-1, 0.01], [-1, -0.01]])\n x = data[:, 0]\n y = data[:, 1]\n h = special_histograms.polar(x, y, radial_bins=2, phi_bins=4)\n assert special_histograms.RadialHistogram == type(h.projection(\"r\"))\n assert special_histograms.AzimuthalHistogram == type(h.projection(\"phi\"))\n\n\nclass TestRadial:\n def test_simple_create(self):\n data = np.array([[0.01, 0.01, 1], [0.01, 0.99, 1], [-1, 0.01, 1], [-1, -0.01, 1]])\n x = data[:, 0]\n y = data[:, 1]\n z = data[:, 2]\n h = special_histograms.radial(x, y)\n assert h.axis_name == \"r\"\n\n h_xyz = special_histograms.radial(x, y, z)\n h_3d = special_histograms.radial(data)\n\n assert h_xyz == h_3d\n\n def test_transform(self):\n t = special_histograms.RadialHistogram.transform([1, 0])\n assert t == 1\n\n t = special_histograms.RadialHistogram.transform([1, 1, 1])\n assert np.allclose(t, np.sqrt(3))\n\n with pytest.raises(ValueError) as exc:\n special_histograms.RadialHistogram.transform([1, 1, 1, 1])\n\n\nclass TestSpherical:\n def test_simple_create(self):\n pass\n\n def test_transform(self):\n t = special_histograms.SphericalHistogram.transform([0, 0, 1])\n assert np.array_equal(t, [1, 0, 0])\n\n t = special_histograms.SphericalHistogram.transform([2, 2, 0])\n assert np.array_equal(t, [np.sqrt(8), np.pi / 2, np.pi / 4])\n\n data = np.asarray([[3, 0, 0], [0, 0, 0], [0, 0.5, -0.5]])\n expected = np.asarray(\n [[3, np.pi / 2, 0], [0, 0, 0], [np.sqrt(0.5), 0.75 * np.pi, np.pi / 2]]\n )\n assert np.allclose(expected, special_histograms.SphericalHistogram.transform(data))\n\n def test_projection_types(self):\n h = special_histograms.spherical([[1, 2, 3], [2, 3, 4]])\n assert special_histograms.SphericalSurfaceHistogram == type(h.projection(\"phi\", \"theta\"))\n assert special_histograms.SphericalSurfaceHistogram == type(h.projection(\"theta\", \"phi\"))\n\n def test_equal_radius(self):\n \"\"\"Issue #62\"\"\"\n n = 1000\n data = np.empty((n, 3))\n np.random.seed(42)\n data[:, 0] = np.random.normal(0, 1, n)\n data[:, 1] = np.random.normal(0, 1, n)\n data[:, 2] = np.random.normal(0, 1, n)\n for i in range(n):\n scale = np.sqrt(data[i, 0] ** 2 + data[i, 1] ** 2 + data[i, 2] ** 2)\n data[i, 0] = data[i, 0] / scale\n data[i, 1] = data[i, 1] / scale\n data[i, 2] = data[i, 2] / scale\n\n with pytest.raises(ValueError) as exc:\n special_histograms.spherical(data, theta_bins=20, phi_bins=20)\n assert exc.match(\"All radii seem to be the same\")\n\n\nclass TestSphericalSurface:\n def test_simple_sphere_data(self):\n n = 100\n data = np.empty((n, 3))\n np.random.seed(42)\n data[:, 0] = np.random.normal(0, 1, n)\n data[:, 1] = np.random.normal(0, 1, n)\n data[:, 2] = np.random.normal(0, 1, n)\n\n h = special_histograms.spherical_surface(data, theta_bins=10, phi_bins=20)\n\n\nclass TestCylindricalSurface:\n def test_radius(self):\n h = special_histograms.cylindrical([[1, 2, 3], [2, 3, 4]])\n proj = h.projection(\"phi\", \"z\")\n assert proj.radius > 1\n\n def test_projection_types(self):\n h = special_histograms.cylindrical([[1, 2, 3], [2, 3, 4]])\n proj = h.projection(\"phi\", \"z\")\n assert special_histograms.AzimuthalHistogram == type(proj.projection(\"phi\"))\n\n\nclass TestCylindrical:\n def test_transform(self):\n t = special_histograms.CylindricalHistogram.transform([0, 0, 1])\n assert np.array_equal(t, [0, 0, 1])\n\n t = special_histograms.CylindricalHistogram.transform([2, 2, 2])\n assert np.array_equal(t, [np.sqrt(8), np.pi / 4, 2])\n\n data = np.asarray([[3, 0, 0], [0, 0, 0], [0, 0.5, -0.5]])\n expected = np.asarray([[3, 0, 0], [0, 0, 0], [0.5, np.pi / 2, -0.5]])\n assert np.allclose(expected, special_histograms.CylindricalHistogram.transform(data))\n\n def test_projection_types(self):\n h = special_histograms.cylindrical([[1, 2, 3], [2, 3, 4]])\n assert special_histograms.CylindricalSurfaceHistogram == type(h.projection(\"phi\", \"z\"))\n assert special_histograms.CylindricalSurfaceHistogram == type(h.projection(\"z\", \"phi\"))\n assert special_histograms.PolarHistogram == type(h.projection(\"rho\", \"phi\"))\n assert special_histograms.PolarHistogram == type(h.projection(\"phi\", \"rho\"))\n"
] | [
[
"numpy.sqrt",
"numpy.allclose",
"numpy.empty",
"numpy.zeros",
"numpy.random.seed",
"numpy.asarray",
"numpy.random.normal",
"numpy.array_equal",
"numpy.array"
]
] |
kbrezinski/complexity | [
"2077825c8ec64df03dfb9f791b7578d64cb35567"
] | [
"tools/plot.py"
] | [
"\nfrom scipy import stats\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef loglog(sums2,interval=None,type=None,plot=False,smoothing=None):\n\n if type is None:\n\n y = [np.log(item) for item in sums2]\n x = [1/(vel+1) for vel in interval]\n slope, yInt, _,_,_ = stats.linregress(x,y)\n\n elif type is 'Density':\n from sklearn.linear_model import HuberRegressor\n\n y = -np.ravel(sums2[1:,None])\n x = np.log2(np.arange(1,len(y)+1))\n\n huber = HuberRegressor().fit(x[:,None], y)\n slope, yInt = huber.coef_, huber.intercept_\n\n if plot == True:\n plt.scatter(x,y,s=5,color='red')\n plt.plot([min(x),max(x)],\\\n [min(x)*slope+yInt,max(x)*slope+yInt],color='black')\n\n print('The slope is: {0}'.format(slope))\n\n return slope, yInt\n"
] | [
[
"numpy.ravel",
"numpy.log",
"scipy.stats.linregress",
"sklearn.linear_model.HuberRegressor",
"matplotlib.pyplot.scatter"
]
] |
yuiiiiiiii/trashbin | [
"f8af682a4aaf84ec2e35e03364d6a5248b2aeb52"
] | [
"sampling_methods/represent_cluster_centers.py"
] | [
"# Copyright 2017 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Another informative and diverse sampler that mirrors the algorithm described\nin Xu, et. al., Representative Sampling for Text Classification Using \nSupport Vector Machines, 2003\n\nBatch is created by clustering points within the margin of the classifier and \nchoosing points closest to the k centroids.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom sklearn.cluster import MiniBatchKMeans\nimport numpy as np\nfrom sampling_methods.sampling_def import SamplingMethod\n\n\nclass RepresentativeClusterMeanSampling(SamplingMethod):\n \"\"\"Selects batch based on informative and diverse criteria.\n\n Returns points within the margin of the classifier that are closest to the\n k-means centers of those points. \n \"\"\"\n\n def __init__(self, X, y, seed):\n self.name = 'cluster_mean'\n self.X = X\n self.flat_X = self.flatten_X()\n self.y = y\n self.seed = seed\n\n def select_batch_(self, model, N, already_selected, **kwargs):\n # Probably okay to always use MiniBatchKMeans\n # Should standardize data before clustering\n # Can cluster on standardized data but train on raw features if desired\n try:\n distances = model.decision_function(self.X)\n except:\n distances = model.predict_proba(self.X)\n if len(distances.shape) < 2:\n min_margin = abs(distances)\n else:\n sort_distances = np.sort(distances, 1)[:, -2:]\n min_margin = sort_distances[:, 1] - sort_distances[:, 0]\n rank_ind = np.argsort(min_margin)\n rank_ind = [i for i in rank_ind if i not in already_selected]\n\n distances = abs(model.decision_function(self.X))\n min_margin_by_class = np.min(abs(distances[already_selected]),axis=0)\n unlabeled_in_margin = np.array([i for i in range(len(self.y))\n if i not in already_selected and\n any(distances[i]<min_margin_by_class)])\n if len(unlabeled_in_margin) < N:\n print(\"Not enough points within margin of classifier, using simple uncertainty sampling\")\n return rank_ind[0:N]\n clustering_model = MiniBatchKMeans(n_clusters=N)\n dist_to_centroid = clustering_model.fit_transform(self.flat_X[unlabeled_in_margin])\n medoids = np.argmin(dist_to_centroid,axis=0)\n medoids = list(set(medoids))\n selected_indices = unlabeled_in_margin[medoids]\n selected_indices = sorted(selected_indices,key=lambda x: min_margin[x])\n remaining = [i for i in rank_ind if i not in selected_indices]\n selected_indices.extend(remaining[0:N-len(selected_indices)])\n return selected_indices\n"
] | [
[
"numpy.sort",
"numpy.argmin",
"numpy.argsort",
"sklearn.cluster.MiniBatchKMeans"
]
] |
awlange/brainsparks | [
"05baff28da347172083672c940406f5696893201"
] | [
"src/calrissian/layers/max_pool_1d.py"
] | [
"from .layer import Layer\nfrom ..activation import Activation\nfrom .convolution_1d import Convolution1D\n\nimport numpy as np\n\n\nclass MaxPool1D(Layer):\n \"\"\"\n Convolve input but only feed forward the maximum activation\n \"\"\"\n\n def __init__(self, input_size=0, n_filters=0, pool_size=1, stride_length=1, flatten_output=False):\n super().__init__(\"MaxPool1D\", False)\n self.input_size = input_size # TODO: make shape\n self.n_filters = n_filters\n self.pool_size = pool_size\n self.stride_length = stride_length\n\n # Number of fields in convolution\n self.n_fields = 1 + (self.input_size - self.pool_size) // self.stride_length\n\n self.flatten_output = flatten_output\n\n # Not sure if needed\n self.activation = Activation.get(\"linear\")\n self.d_activation = Activation.get_d(\"linear\")\n\n def feed_forward(self, a_in):\n return self.compute_a(self.compute_z(a_in))\n\n def compute_z(self, a_in):\n return a_in\n\n def compute_a(self, z):\n a = self.apply_max_pool(z)\n if self.flatten_output:\n return Convolution1D.flatten(a)\n return a\n\n def compute_da(self, z, a=None):\n\n return np.ones_like(self.apply_max_pool(z))\n\n # # Pluck out only the argmax gradients\n # result = np.zeros_like(z)\n # for i_data in range(len(z)):\n # zi = z[i_data]\n # for filter in range(self.n_filters):\n # zf = zi[filter]\n # i = 0\n # for field in range(self.n_fields):\n # field_list = zf[i:(i+self.pool_size)]\n # max_index = np.argmax(field_list)\n # result[i_data][filter][i + max_index] = 1.0\n # i += self.stride_length\n #\n # return result\n\n def compute_gradient(self, prev_delta, A, sigma_Z=None):\n # return np.zeros_like(self.b), np.zeros_like(self.w)\n # # Pluck out only the argmax gradients\n\n result = np.zeros_like(A)\n for i_data in range(len(A)):\n zi = A[i_data]\n for filter in range(self.n_filters):\n zf = zi[filter]\n i = 0\n for field in range(self.n_fields):\n field_list = zf[i:(i+self.pool_size)]\n max_index = np.argmax(field_list)\n result[i_data][filter][i + max_index] = 1.0\n i += self.stride_length\n\n return result\n\n def compute_gradient_update(self, dc_db, dc_dw, A=None, convolve=True):\n return dc_db, dc_dw\n\n def apply_max_pool(self, a, argmax=False):\n max_func = np.argmax if argmax else np.max\n a_pool = []\n for i_data in range(len(a)):\n a_pool.append(self.convolve_max_pool(a[i_data], max_func))\n return np.asarray(a_pool)\n\n def convolve_max_pool(self, a, max_func=np.max):\n # Choose if we want the values or the indexes\n a_filter = []\n for filter in range(self.n_filters):\n convolution = []\n i = 0\n for field in range(self.n_fields):\n convolution.append(max_func(a[filter][i:(i+self.pool_size)]))\n i += self.stride_length\n a_filter.append(convolution)\n return a_filter\n\n\n"
] | [
[
"numpy.zeros_like",
"numpy.asarray",
"numpy.argmax"
]
] |
cxiang26/mygluon_cv | [
"1dfebd27afc7d788424b21dfd69007c7576dcbbe"
] | [
"gluoncv/model_zoo/fcos/fcos_target.py"
] | [
"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\n\nimport os\nimport sys\n\nimport numpy as np\nimport mxnet as mx\nfrom mxnet import nd\nfrom mxnet import autograd\nfrom mxnet.gluon import nn\n# from IPython import embed\n\nclass FCOSTargetGenerator(nn.Block):\n \"\"\"Generate FCOS targets\"\"\"\n def __init__(self, retina_stages=5, base_stride=128,\n valid_range=[(384, np.inf), (192, 384), (96, 192), (48, 96), (0, 48)], **kwargs):\n\n super(FCOSTargetGenerator, self).__init__(**kwargs)\n self._stages = retina_stages\n self._stride = base_stride\n self._valid_range = valid_range\n\n def generate_targets(self, img, boxes):\n \"\"\"\n img : [H, W, 3]\n boxes : [N, 5]\n \"\"\"\n rh, rw, _ = img.shape\n rx = nd.arange(0, rw).reshape((1, -1))\n ry = nd.arange(0, rh).reshape((-1, 1))\n sx = nd.tile(rx, reps=(rh, 1))\n sy = nd.tile(ry, reps=(1, rw))\n\n areas = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])\n boxes = boxes[nd.argsort(areas)]\n boxes = nd.concat(nd.zeros((1, 5)), boxes, dim=0) # for gt assign confusion\n x0, y0, x1, y1, cls = nd.split(boxes, num_outputs=5, axis=-1, squeeze_axis=True)\n n = boxes.shape[0]\n\n # [H, W, N]\n of_l = sx.reshape(-2, 1) - nd.expand_dims(nd.expand_dims(x0, axis=0), axis=0)\n of_t = sy.reshape(-2, 1) - nd.expand_dims(nd.expand_dims(y0, axis=0), axis=0)\n of_r = -(sx.reshape(-2, 1) - nd.expand_dims(nd.expand_dims(x1, axis=0), axis=0))\n of_b = -(sy.reshape(-2, 1) - nd.expand_dims(nd.expand_dims(y1, axis=0), axis=0))\n\n # [H, W, N]\n eps = 1e-5\n ctr =(nd.minimum(of_l, of_r) / nd.maximum(of_l, of_r)) * \\\n (nd.minimum(of_t, of_b) / nd.maximum(of_t, of_b) + eps)\n ctr = nd.sqrt(nd.abs(ctr))\n ctr[:, :, 0] = 0\n\n # [H, W, N, 4]\n offsets = nd.concat(of_l.reshape(-2, 1), of_t.reshape(-2, 1),\n of_r.reshape(-2, 1), of_b.reshape(-2, 1), dim=-1)\n\n # fh = int(np.ceil(((rh + 1) / 2) // 2 / 2))\n # fw = int(np.ceil(((rw + 1) / 2) // 2 / 2))\n fh = int(np.ceil(np.ceil(np.ceil(rh / 2) / 2) / 2))\n fw = int(np.ceil(np.ceil(np.ceil(rw / 2) / 2) / 2))\n\n fm_list = []\n for i in range(self._stages):\n fm_list.append((fh, fw))\n fh = int(np.ceil(fh / 2))\n fw = int(np.ceil(fw / 2))\n fm_list = fm_list[::-1]\n cls_targets = []\n ctr_targets = []\n box_targets = []\n cor_targets = []\n stride = self._stride\n for i in range(self._stages):\n fh, fw = fm_list[i]\n cls_target = nd.zeros((fh, fw))\n box_target = nd.zeros((fh, fw, 4))\n ctr_target = nd.zeros((fh, fw))\n\n cx = nd.arange(0, fw).reshape((1, -1))\n cy = nd.arange(0, fh).reshape((-1, 1))\n sx = nd.tile(cx, reps=(fh, 1))\n sy = nd.tile(cy, reps=(1, fw))\n syx = nd.stack(sy.reshape(-1), sx.reshape(-1)).transpose().astype('int32')\n # bugs in this type\n # bx = sxy[:, 0] * stride + nd.floor(sxy[:, 0] / 2).astype(np.int32)\n # by = sxy[:, 1] * stride + nd.floor(sxy[:, 1] / 2).astype(np.int32)\n by = syx[:, 0] * stride\n bx = syx[:, 1] * stride\n cor_targets.append(nd.stack(bx, by, axis=1))\n\n # [FH*FW, N, 4]\n of_byx = offsets[by, bx]\n # of_byx = nd.gather_nd(offsets, indices=byx.transpose())\n min_vr, max_vr = self._valid_range[i]\n # [FH*FW, N]\n is_in_box = nd.prod(of_byx > 0, axis=-1)\n is_valid_area = (of_byx.max(axis=-1) >= min_vr) * (of_byx.max(axis=-1) <= max_vr)\n # [FH*FW, N]\n valid_pos = nd.elemwise_mul(is_in_box, is_valid_area)\n of_valid = nd.zeros((fh, fw, n))\n of_valid[syx[:, 0], syx[:, 1], :] = valid_pos # 1, 0\n of_valid[:, :, 0] = 0\n # [FH, FW]\n gt_inds = nd.argmax(of_valid, axis=-1)\n # box targets\n box_target[syx[:, 0], syx[:, 1]] = boxes[gt_inds[syx[:, 0], syx[:, 1]], :4]\n box_target = box_target.reshape(-1, 4)\n # cls targets\n cls_target[syx[:, 0], syx[:, 1]] = cls[gt_inds[syx[:, 0], syx[:, 1]]]\n cls_target = cls_target.reshape(-1)\n # ctr targets\n ctr_target[syx[:, 0], syx[:, 1]] = ctr[by, bx, gt_inds[syx[:, 0], syx[:, 1]]]\n ctr_target = ctr_target.reshape(-1)\n box_targets.append(box_target)\n cls_targets.append(cls_target)\n ctr_targets.append(ctr_target)\n stride = int(stride / 2)\n box_targets = nd.concat(*box_targets, dim=0)\n cls_targets = nd.concat(*cls_targets, dim=0)\n ctr_targets = nd.concat(*ctr_targets, dim=0)\n cor_targets = nd.concat(*cor_targets, dim=0)\n cor_targets = cor_targets.astype('float32')\n\n return cls_targets, ctr_targets, box_targets, cor_targets\n\n\n def forward(self, img, boxes):\n pass\n\n\nclass FCOSBoxConverter(nn.HybridBlock):\n \"\"\"This function is used to convert box_preds(l,t,r,b)\n to corner(x1, y1, x2, y2) format, which then used\n to compute IoULoss.\n \"\"\"\n def __init__(self, **kwargs):\n super(FCOSBoxConverter, self).__init__(**kwargs)\n pass\n\n def hybrid_forward(self, F, box_preds, box_cords):\n \"\"\"\n box_preds : [B, N, 4]\n box_cords : [B, N, 2]\n coordinates for the feature map corresponding to original image.\n \"\"\"\n cx, cy = F.split(box_cords, num_outputs=2, axis=-1)\n pl, pt, pr, pb = F.split(box_preds, num_outputs=4, axis=-1)\n x1 = cx - pl\n y1 = cy - pt\n x2 = cx + pr\n y2 = cy + pb\n boxes = F.concat(x1, y1, x2, y2, dim=2)\n return boxes\n\n\n# if __name__ == '__main__':\n# img = nd.zeros(shape=(1000, 1000, 3))\n#\n# boxes = nd.array([[291, 114, 901, 778, 60],\n# [504, 263, 780, 490, 15],\n# [461, 222, 829, 579, 20],\n# [24, 205, 389, 800, 15]], ctx=mx.cpu())\n#\n# target_generator = FCOSTargetGenerator()\n# cls_targets, ctr_targets, box_targets, cor_targets = \\\n# target_generator.generate_targets(img, boxes)\n# from IPython import embed; embed()\n"
] | [
[
"numpy.ceil"
]
] |
ryanofarrell/ncaa-basketball | [
"628bda58cb1320431edf38ab407ba70ca5f80008"
] | [
"code/Vegas Analysis.py"
] | [
"\n# %% Imports\nimport pandas as pd\nimport numpy as np\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nfrom sklearn.ensemble import RandomForestRegressor, RandomForestClassifier, GradientBoostingClassifier\nfrom sklearn.metrics import r2_score, roc_curve, roc_auc_score\nfrom itertools import product\n\n# Import to add project folder to sys path\nimport sys\nutils_path = '/Users/Ryan/Documents/projects/ncaa-basketball/code/utils'\nif utils_path not in sys.path:\n sys.path.append(utils_path)\n\nfrom api import opponentAdjust\nfrom db import get_db\nfrom misc import getRelativeFp\n\n\n# %% Declare parameters\nmetrics = [\n 'PF', 'Margin',\n 'FGM', 'FGA',\n 'FG3M', 'FG3A',\n 'FG2M', 'FG2A',\n 'FTA', 'FTM',\n 'Ast', 'ORB',\n 'DRB', 'TRB',\n 'TO', 'Stl',\n 'Blk', 'Foul'\n]\nprefixes = ['Tm', 'Opp']\nattrCols = [\n 'Season',\n 'TmName',\n 'dataPriorTo',\n 'isRegularSeason',\n ''\n]\n\n\n# %% Read in raw data\ndef getTd():\n \"\"\"Reads in local csv of team-date data as of specified dates\n\n Returns:\n DataFrame: team-date data\n \"\"\"\n firstYr = True\n for yr in range(2003, 2021):\n print(f\"Reading in {yr}'s data\")\n fp = getRelativeFp(__file__, f'../data/predate_games/{yr}.csv')\n if firstYr:\n raw = pd.read_csv(fp)\n firstYr = False\n else:\n raw = raw.append(pd.read_csv(fp))\n return raw\n\n\n# %% Add additional columns to team-date data\ndef addColsToTd(_td, _metrics=metrics, _prefixes=prefixes):\n \"\"\"Add additional columns to the team-date DataFrame\n\n Args:\n _td (DataFrame): Team-date DataFrame\n _metrics (list, optional): list of metrics to pass to opponent-\n adjusting function. Defaults to metrics.\n _prefixes (list, optional): list of prefixes to pass to opponent-\n adjusting function. Defaults to prefixes.\n\n Returns:\n DataFrame: Team-date data with additional columns\n \"\"\"\n _td = opponentAdjust(\n _td,\n _prefixes,\n _metrics,\n includeOARankFields=False,\n includeNormRankFields=False,\n includeNormFields=True\n )\n _td['TmWinPct'] = _td['TmWin'] / _td['TmGame']\n _td['TmPossPerGame'] = _td['TmPoss'] / _td['TmGame']\n\n return _td\n\n\n# %% Clean team-date data\ndef cleanTd(_td, minGames=10, _metrics=metrics, _prefixes=prefixes):\n \"\"\"Removes extra columns, removes data prior to specified number of games,\n changes datetime data type\n\n Args:\n _td (DataFrame): team-date data\n minGames (int, optional): Minimum games played to keep data.\n Defaults to 10.\n _metrics (list, optional): Metrics to drop raw data of.\n Defaults to metrics.\n _prefixes (list, optional): Prefixes to drop raw data of.\n Defaults to prefixes.\n\n\n Returns:\n DataFrame: Cleaned data\n \"\"\"\n # Make list of columns to ignore\n colsToDrop = [\n 'OppGame',\n 'GameOT'\n ]\n for metr in _metrics + ['Mins', 'Win', 'Poss']:\n for pref in _prefixes:\n colsToDrop.append(f'{pref}{metr}')\n colsToDrop.append(f'OppSum_{pref}{metr}')\n\n keptCols = [\n col for col in _td.columns\n if (col not in colsToDrop) & (col[:7] != 'OppSum_')\n ]\n\n _td = _td[keptCols]\n\n # Limit team-dates to only those with >= minGames\n _td = _td.loc[_td['TmGame'] >= minGames]\n\n # Change field to datetime\n _td['dataPriorTo'] = pd.to_datetime(_td['dataPriorTo'])\n\n return _td\n\n\n# %% Get game data for analysis\ndef getGames():\n \"\"\"Get 2003+ game data from database\n\n Returns:\n DataFrame: Game data\n \"\"\"\n db = get_db()\n q = {'Season': {'$gte': 2003}}\n fields = {\n '_id': 0,\n 'TmName': 1,\n 'OppName': 1,\n 'Season': 1,\n 'GameDate': 1,\n 'TmMargin': 1,\n 'GameVegasLine': 1,\n 'TmLoc': 1\n }\n raw = pd.DataFrame(\n list(\n db.games.find(\n q,\n fields\n )\n )\n )\n return raw\n\n\n# %% De-dupe, remove outliers\ndef cleanGames(_games):\n \"\"\"De-dupes game records, keeping only home teams and lower-name neutral games,\n rename a few columns, remove outlier lines, and change datatypes.\n\n Args:\n _games (DataFrame): game data\n\n Returns:\n DataFrame: Cleaned game data\n \"\"\"\n # _games = _games.loc[(\n # (_games['TmLoc'] == 'H') |\n # ((_games['TmLoc'] == 'N') & (_games['TmName'] < _games['OppName']))\n # )]\n _games = _games.loc[np.abs(_games['GameVegasLine']) <= 50]\n _games.rename(inplace=True, columns={\n 'GameDate': 'dataPriorTo'\n })\n _games['dataPriorTo'] = pd.to_datetime(_games['dataPriorTo'])\n _games['Tm_isHome'] = np.where(_games['TmLoc'] == 'H', 1, 0)\n\n return _games\n\n\n# %% Add add'l columns to games\ndef addColsToGames(_games):\n # GameVegasLine is the expected Tm margin. Positive means vegas favored Tm.\n # If TmVegasMargin > 0: TmMargin > GameVegasLine: Team outperformed vegas - bet on team.\n # If TmVegasMargin < 0: TmMargin < GameVegasLine, team did worse than vegas expected - bet on Opp\n _games['tmVegasMargin'] = _games['TmMargin'] - _games['GameVegasLine']\n _games['tmAtsWinner'] = (_games['tmVegasMargin'] > 0) * 1\n\n return _games\n\n\n# %% Merge in team-date data to game records\ndef addTdToGames(_td, _games):\n tdCols = ['TmName', 'Season', 'dataPriorTo']\n dfTm = _td.copy()\n dfTm.columns = [\n f'Tm_{x}' if x not in tdCols else x for x in dfTm.columns\n ]\n dfOpp = _td.copy()\n dfOpp.columns = [\n f'Opp_{x}' if x not in tdCols else x for x in dfOpp.columns\n ]\n dfOpp.rename(inplace=True, columns={'TmName': 'OppName'})\n\n _games = pd.merge(\n left=_games,\n right=dfTm,\n on=['TmName', 'Season', 'dataPriorTo'],\n how='inner'\n )\n _games = pd.merge(\n left=_games,\n right=dfOpp,\n on=['OppName', 'Season', 'dataPriorTo'],\n how='inner'\n )\n\n return _games\n\n\n# %% Eval margin predictions\ndef evalModel(predMargin, actualMargin, methodName, verbose=False):\n print(f\"{methodName}:\")\n # Accuracy of margin\n R2 = r2_score(\n y_true=actualMargin,\n y_pred=predMargin\n )\n\n MAE = np.mean(np.abs(actualMargin - predMargin))\n\n # Correctly picking winner\n sumWins = np.sum(\n (predMargin * actualMargin > 0)*1\n )\n sumLosses = np.sum(\n (predMargin * actualMargin < 0)*1\n )\n sumTies = np.sum(\n (predMargin * actualMargin == 0)*1\n )\n if verbose:\n print(f\"MAE: {MAE:.2f}\")\n print(f\"R^2: {R2:.4f}\")\n print(f\"Correct Winner Record: {sumWins:,.0f} - {sumLosses:,.0f} - {sumTies:,.0f}\")\n print(f\"Win Pct: {sumWins/len(predMargin):.3%}\")\n print(f\"Win Pct excluding pushes: {sumWins/(sumWins + sumLosses):.3%}\")\n print('\\n')\n\n return R2, MAE\n\n\n# %% Create function for classification model \ndef evalClassificationModel(predClass, actualClass, isPush, methodName, predProb, showCurve=False, verbose=False):\n print(f\"{methodName}:\")\n\n predWin = ((predClass == actualClass) & (isPush == 0))*1\n predLoss = ((predClass != actualClass) & (isPush == 0))*1\n predPush = (isPush == 1)*1\n\n w = np.sum(predWin)/(np.sum(predWin)+np.sum(predLoss))\n b_auc = roc_auc_score(actualClass, predClass)\n p_auc = roc_auc_score(actualClass, predProb)\n\n if verbose:\n print(f\"Record: {np.sum(predWin)} - {np.sum(predLoss)} - {np.sum(predPush)}\")\n print(f\"Net wins: {np.sum(predWin) - np.sum(predLoss)}\")\n print(f\"Win Percent: {w:.2%}\")\n print(f\"Binary AUC: {b_auc:.2%}\")\n print(f\"Probability AUC: {p_auc:.2%}\")\n\n if showCurve:\n fpr, tpr, thresholds = roc_curve(actualClass, predProb)\n fig = go.Figure(go.Scatter(x=fpr, y=tpr))\n fig.show()\n\n return w, b_auc, p_auc\n\n\n# %% Main function\nif __name__ == '__main__':\n # Get team-date data\n td = addColsToTd(getTd())\n td = cleanTd(td)\n\n # Get games data, add team details\n games = cleanGames(getGames())\n games = addColsToGames(games)\n gamesCols = games.columns\n games = addTdToGames(td, games)\n\n gamesX = games[[col for col in games.columns if col not in gamesCols]]\n gamesy = games[gamesCols]\n\n ####################################\n ## Predicting Game Margin\n ####################################\n # Set baseline: Vegas lines to predict margin\n evalModel(\n predMargin=gamesy['GameVegasLine'],\n actualMargin=gamesy['TmMargin'],\n methodName='Vegas',\n verbose=True\n )\n\n # Now, using Marginper40 diffs\n evalModel(\n predMargin=gamesX['Tm_TmMarginper40'] - gamesX['Opp_TmMarginper40'],\n actualMargin=gamesy['TmMargin'],\n methodName='Margin per 40 Difference',\n verbose=True\n )\n\n # OA Margin per 40\n evalModel(\n predMargin=gamesX['Tm_OA_TmMarginper40'] - gamesX['Opp_OA_TmMarginper40'],\n actualMargin=gamesy['TmMargin'],\n methodName='OA Margin per 40 Difference',\n verbose=True\n )\n\n # Now, adding a few different home court advantages to margin and OAM\n buffs = [a/2 for a in range(-5,16)]\n mov_r= []\n mov_m = []\n oa_r = []\n oa_m = []\n for b in buffs:\n # print(a/2)\n r, m = evalModel(\n predMargin=gamesX['Tm_TmMarginper40'] - gamesX['Opp_TmMarginper40'] + b* gamesy['Tm_isHome'],\n actualMargin=gamesy['TmMargin'],\n methodName=f'Margin per 40 Difference + {b}'\n )\n mov_r.append(r)\n mov_m.append(m)\n\n r, m = evalModel(\n predMargin=gamesX['Tm_OA_TmMarginper40'] - gamesX['Opp_OA_TmMarginper40'] + b* gamesy['Tm_isHome'],\n actualMargin=gamesy['TmMargin'],\n methodName=f'OA Margin per 40 Difference + {b}'\n )\n oa_r.append(r)\n oa_m.append(m)\n \n fig = make_subplots(rows=2, cols=1, shared_xaxes=True, subplot_titles=('R2 by Home Court Advantage', 'MAE by Home Court Advantage'))\n fig.add_trace(\n go.Scatter(x=buffs,y=mov_r, name='MoV - R2', legendgroup='MOV', line_color='steelblue'),\n row=1, col=1\n )\n fig.add_trace(\n go.Scatter(x=buffs,y=oa_r, name='OA MoV - R2', legendgroup='OA', line_color='crimson'),\n row=1, col=1\n )\n fig.add_trace(\n go.Scatter(x=buffs,y=mov_m, name='MoV - MAE', legendgroup='MOV', line_color='steelblue'),\n row=2, col=1\n )\n fig.add_trace(\n go.Scatter(x=buffs,y=oa_m, name='OA MoV - MAE', legendgroup='OA', line_color='crimson'),\n row=2, col=1\n )\n fig.add_trace(\n go.Scatter(x=buffs, y=[0.3504]*len(buffs), name='Vegas - R2', legendgroup='v', line_color='black'),\n row=1, col=1\n )\n fig.add_trace(\n go.Scatter(x=buffs, y=[8.31]*len(buffs), name='Vegas - MAE', legendgroup='v', line_color='black'),\n row=2, col=1\n )\n fig.update_xaxes(\n title_text='Home Court Advantage Value',\n row=2\n )\n fig.update_yaxes(title_text='R2', row=1)\n fig.update_yaxes(title_text='MAE', row=2)\n\n fig.show()\n\n # Machine learning section\n rf = RandomForestRegressor(\n n_estimators=500,\n n_jobs=-1,\n max_depth=10,\n random_state=114492,\n min_samples_split=6,\n max_features='sqrt',\n bootstrap=True,\n oob_score=False,\n max_samples=0.8,\n # verbose=True\n )\n temp = pd.DataFrame()\n for s in sorted(gamesy['Season'].unique()):\n print(f\"Season {s}\")\n rf.fit(gamesX.loc[gamesy['Season'] != s], gamesy.loc[gamesy['Season'] != s, 'TmMargin'])\n # gb.predict(gamesX.loc[gamesy['Season'] == s)\n t = pd.DataFrame(data={\n 'predMargin': rf.predict(gamesX.loc[gamesy['Season'] == s]),\n 'actlMargin': gamesy.loc[gamesy['Season'] == s, 'TmMargin'],\n 'season': s\n })\n temp = temp.append(t)\n evalModel(\n predMargin=t['predMargin'],\n actualMargin=t['actlMargin'],\n methodName=f'Season {s} RF Results',\n verbose=True\n )\n\n evalModel(\n predMargin=temp['predMargin'],\n actualMargin=temp['actlMargin'],\n methodName=f'Total RF Results',\n verbose=True\n )\n\n df = temp.groupby(['Season'])\n\n\n ##############\n ## ATS\n ##############\n # Now, adding a few different home court advantages to margin and OAM\n buffs = [a/2 for a in range(-50,50)]\n mov_w = []\n mov_bauc = []\n mov_pauc = []\n oa_w = []\n oa_bauc = []\n oa_pauc = []\n for b in buffs:\n # print(a/2)\n # Check versus vegas\n # vegasMinusModel (+) when vegas likes Tm better than model (model bet on Opp)\n # vegasMinusModel (-) when vegas likes Tm worse than model (model bet on Tm)\n predMargin = gamesX['Tm_TmMarginper40'] - gamesX['Opp_TmMarginper40'] + b* gamesy['Tm_isHome']\n vegasMinusModel = gamesy['GameVegasLine'] - predMargin\n \n w, bauc, pauc = evalClassificationModel(\n predClass=(vegasMinusModel <= 0) * 1,\n actualClass=gamesy['tmAtsWinner'],\n isPush=(gamesy['tmVegasMargin'] == 0)*1,\n predProb=vegasMinusModel,\n methodName=f'Margin per 40 Difference + {b}'\n # showCurve=True\n )\n mov_w.append(w)\n mov_bauc.append(bauc)\n mov_pauc.append(pauc)\n\n\n predMargin = gamesX['Tm_OA_TmMarginper40'] - gamesX['Opp_OA_TmMarginper40'] + b* gamesy['Tm_isHome']\n vegasMinusModel = gamesy['GameVegasLine'] - predMargin\n \n w, bauc, pauc = evalClassificationModel(\n predClass=(vegasMinusModel <= 0) * 1,\n actualClass=gamesy['tmAtsWinner'],\n isPush=(gamesy['tmVegasMargin'] == 0)*1,\n predProb=vegasMinusModel,\n methodName=f'Margin per 40 Difference + {b}'\n # showCurve=True\n )\n oa_w.append(w)\n oa_bauc.append(bauc)\n oa_pauc.append(pauc)\n fig = make_subplots(rows=3, cols=1, shared_xaxes=True, subplot_titles=('Win Pct by Home Court Advantage', 'Binary AUC by HCA', 'Probability AUC by HCA'))\n fig.add_trace(\n go.Scatter(x=buffs,y=mov_w, name='MoV - Win Pct', legendgroup='MOV', line_color='steelblue'),\n row=1, col=1\n )\n fig.add_trace(\n go.Scatter(x=buffs,y=oa_w, name='OA MoV - Win Pct', legendgroup='OA', line_color='crimson'),\n row=1, col=1\n )\n fig.add_trace(\n go.Scatter(x=buffs,y=mov_bauc, name='MoV - Binary AUC', legendgroup='MOV', line_color='steelblue'),\n row=2, col=1\n )\n fig.add_trace(\n go.Scatter(x=buffs,y=oa_bauc, name='OA MoV - Binary AUC', legendgroup='OA', line_color='crimson'),\n row=2, col=1\n )\n fig.add_trace(\n go.Scatter(x=buffs,y=mov_pauc, name='MoV - Probability AUC', legendgroup='MOV', line_color='steelblue'),\n row=3, col=1\n )\n fig.add_trace(\n go.Scatter(x=buffs,y=oa_pauc, name='OA MoV - Probability AUC', legendgroup='OA', line_color='crimson'),\n row=3, col=1\n )\n\n\n\n fig.update_xaxes(\n title_text='Home Court Advantage Value',\n row=3\n )\n fig.update_yaxes(title_text='Win Pct', row=1)\n fig.update_yaxes(title_text='AUC', row=2)\n fig.update_yaxes(title_text='AUC', row=3)\n\n fig.show()\n\n\n\n # Try Classification based on if Tm wins ATS\n gamesX['GameVegasLine'] = gamesy['GameVegasLine']\n # Train the winning parameters: 10 depth, 6 min samples\n rfc = RandomForestClassifier(\n n_estimators=500,\n criterion='gini',\n max_depth=5,\n min_samples_split=2,\n max_features='sqrt',\n bootstrap=True,\n # oob_score=True,\n n_jobs=-1,\n random_state=114492,\n # verbose=True,\n max_samples=.8\n )\n temp = pd.DataFrame()\n for s in sorted(gamesy['Season'].unique()):\n print(f\"Season {s}\")\n rfc.fit(gamesX.loc[gamesy['Season'] != s], gamesy.loc[gamesy['Season'] != s, 'tmAtsWinner'])\n # gb.predict(gamesX.loc[gamesy['Season'] == s)\n t = pd.DataFrame(data={\n 'predClass': rfc.predict(gamesX.loc[gamesy['Season'] == s]),\n 'predProb': rfc.predict_proba(gamesX.loc[gamesy['Season'] == s])[:,1],\n 'actlClass': gamesy.loc[gamesy['Season'] == s, 'tmAtsWinner'],\n 'isPush': ((gamesy.loc[gamesy['Season'] == s, 'tmVegasMargin'])==0)*1\n })\n temp = temp.append(t)\n evalClassificationModel(\n predClass=t['predClass'],\n actualClass=t['actlClass'],\n isPush=t['isPush'],\n predProb=t['predProb'],\n methodName=f'{s} Season Results', \n # showCurve=True\n )\n evalClassificationModel(\n predClass=temp['predClass'],\n actualClass=temp['actlClass'],\n isPush=temp['isPush'],\n predProb=temp['predProb'],\n methodName=f'rfc All Season Results', \n showCurve=True\n )\n\n\n # Gradient Boosting\n gb = GradientBoostingClassifier(\n n_estimators=20,\n max_depth=3,\n random_state=114492,\n verbose=True\n )\n temp = pd.DataFrame()\n for s in sorted(gamesy['Season'].unique()):\n print(f\"Season {s}\")\n gb.fit(gamesX.loc[gamesy['Season'] != s], gamesy.loc[gamesy['Season'] != s, 'tmAtsWinner'])\n # gb.predict(gamesX.loc[gamesy['Season'] == s)\n t = pd.DataFrame(data={\n 'predClass': gb.predict(gamesX.loc[gamesy['Season'] == s]),\n 'predProb': gb.predict_proba(gamesX.loc[gamesy['Season'] == s])[:,1],\n 'actlClass': gamesy.loc[gamesy['Season'] == s, 'tmAtsWinner'],\n 'isPush': ((gamesy.loc[gamesy['Season'] == s, 'tmVegasMargin'])==0)*1\n })\n temp = temp.append(t)\n evalClassificationModel(\n predClass=t['predClass'],\n actualClass=t['actlClass'],\n isPush=t['isPush'],\n predProb=t['predProb'],\n methodName=f'{s} Season Results', \n # showCurve=True\n )\n evalClassificationModel(\n predClass=temp['predClass'],\n actualClass=temp['actlClass'],\n isPush=temp['isPush'],\n predProb=temp['predProb'],\n methodName=f'GB All Season Results', \n showCurve=True,\n verbose=True\n )\n\n\n\n # print(f\"RF Classifier Correct: {np.mean(gamesy['rfc_Correct']):.2%}\")\n # games['rfc_correctCumSum'] = np.where(\n # games['rfc_betOnTm'] == games['tmAtsWinner'],\n # 1,\n # -1\n # )\n # games.sort_values(inplace=True, by=['dataPriorTo'])\n # games['modelDateCumSum'] = games['rfc_correctCumSum'].cumsum()\n # fig = px.line(games, x='dataPriorTo', y='modelDateCumSum')\n # fig.show()\n\n # gamesy['probRounded'] = np.round(rfc.oob_decision_function_[:,1],3)\n # temp2 = gamesy.groupby(['probRounded'])['rfc_correctCumSum'].agg({'rfc_correctCumSum': ['sum', 'count']}).reset_index()\n # temp2.columns = ['probRounded', 'rfc_correctCumSum', 'recordCnt']\n # fig = px.bar(temp2, x='probRounded', y='rfc_correctCumSum')\n # fig.update_layout(\n # title_text=f\"Performance of {predictionCol} by {col}\"\n # )\n\n # gamesy['placeBet'] = (gamesy['probRounded']<= 0.5)*1\n # games['smartWinner'] = games['placeBet']*games['rfc_correctCumSum']\n # print(f\"Smart logic correct: {np.sum(games['smartWinner']):.0f}, win pct = {np.sum(games['smartWinner']==1)/np.sum(games['placeBet']):.2%}\")\n\n # temp = games[['tmAtsWinner', 'rfc_tmAtsWinner_1','rfc_betOnTm']]\n\n\n\n\n# %%\ngb = GradientBoostingClassifier(\n n_estimators=150,\n max_depth=3,\n random_state=114492,\n verbose=True\n)\ngb.fit(gamesX, games['tmAtsWinner'])\n\ngamesy['rfc_betOnTm'] = gb.predict(gamesX)\ngamesy['rfc_Win'] = ((gamesy['rfc_betOnTm'] == gamesy['tmAtsWinner']) & (gamesy['tmVegasMargin'] != 0))*1\ngamesy['rfc_Loss'] = ((gamesy['rfc_betOnTm'] != gamesy['tmAtsWinner']) & (gamesy['tmVegasMargin'] != 0))*1\ngamesy['rfc_Push'] = (gamesy['tmVegasMargin'] == 0)*1\nprint(f\"Record: {np.sum(gamesy['rfc_Win'])} - {np.sum(gamesy['rfc_Loss'])} - {np.sum(gamesy['rfc_Push'])}\")\nprint(f\"Net wins: {np.sum(gamesy['rfc_Win']) - np.sum(gamesy['rfc_Loss'])}\")\nprint(f\"Win Percent: {np.sum(gamesy['rfc_Win'])/(np.sum(gamesy['rfc_Win'])+np.sum(gamesy['rfc_Loss'])):.2%}\")\n\n\n# %%\n"
] | [
[
"numpy.sum",
"sklearn.metrics.roc_curve",
"pandas.read_csv",
"pandas.DataFrame",
"numpy.abs",
"sklearn.metrics.roc_auc_score",
"pandas.to_datetime",
"sklearn.ensemble.RandomForestRegressor",
"pandas.merge",
"sklearn.metrics.r2_score",
"sklearn.ensemble.RandomForestClassifier",
"numpy.where",
"sklearn.ensemble.GradientBoostingClassifier"
]
] |
signofthefour/tacotron | [
"660d3448a0a0dcf6efd4f7629f203f121c271fff"
] | [
"audio.py"
] | [
"from __future__ import print_function, division\n\nimport numpy as np\nimport librosa\nfrom tqdm import tqdm\nimport math\nimport tensorflow as tf\nimport soundfile as sf\n\nn_fft = 2048\nwin_length = 1200\nhop_length = int(win_length/4)\nmax_audio_length = 108000\n\n# decoder output width r\nr = 2\n\ndef reshape_frames(signal, forward=True):\n if forward:\n split_points = np.arange(4*r, signal.shape[1] + 1, step=4*r)\n splits = np.split(signal, split_points, axis=1)\n new_signal = np.concatenate([np.concatenate(np.split(s, r, axis=1), axis=0) for s in splits[:-1]], axis=1)\n return new_signal.T\n else:\n signal = np.reshape(signal, (-1, int(signal.shape[1]/r)))\n split_points = np.arange(4*r, signal.shape[0]+1, step=4*r)\n splits = np.split(signal, split_points, axis=0)\n new_signal = np.concatenate([np.concatenate(np.split(s, s.shape[0]/r, axis=0), axis=1) for s in splits[:-1]], axis=0)\n new_signal = np.reshape(new_signal, (-1, signal.shape[1]))\n return new_signal\n\ndef process_audio(fname, n_fft=2048, win_length=1200, hop_length=300, sr=16000):\n wave, sr = librosa.load(fname, mono=True, sr=sr)\n \n # trim initial silence\n wave, _ = librosa.effects.trim(wave)\n\n # ensure the sample length is multiple of 4 * r\n assert math.ceil(max_audio_length / hop_length) % (4*r) == 0\n\n if wave.shape[0] < max_audio_length:\n wave = np.pad(wave, (0, max_audio_length - wave.shape[0]), 'constant', constant_values=0)\n else:\n return None, None\n \n pre_emphasis = 0.97\n wave = np.append(wave[0], wave[1:] - pre_emphasis*wave[:-1])\n\n stft = librosa.stft(wave, n_fft=n_fft, win_length=win_length, hop_length=hop_length)\n mel = librosa.feature.melspectrogram(S=stft, n_mels=80)\n\n stft = np.log(abs(stft) + 1e-8)\n mel = np.log(abs(mel) + 1e-8)\n\n stft = reshape_frames(stft)\n mel = reshape_frames(mel)\n\n return stft, mel\n\ndef invert_spectrogram(spec, out_fn=None, sr=16000):\n spec = reshape_frames(spec, forward=False)\n inv = griffinlim(np.exp(spec.T), n_fft=n_fft, win_length=win_length, hop_length=hop_length, verbose=False)\n\n if out_fn is not None:\n sf.write(out_fn, inv, sr, subtype='PCM_24')\n return inv\n\n\ndef griffinlim(spectrogram, n_iter=50, window='hann', n_fft=2048, win_length=2048, hop_length=-1, verbose=False):\n if hop_length == -1:\n hop_length = n_fft // 4\n\n angles = np.exp(2j * np.pi * np.random.rand(*spectrogram.shape))\n\n t = tqdm(range(n_iter), ncols=100, mininterval=2.0, disable=not verbose)\n for i in t:\n full = np.abs(spectrogram).astype(np.complex) * angles\n inverse = librosa.istft(full, win_length=win_length, hop_length=hop_length, window=window)\n rebuilt = librosa.stft(inverse, n_fft=n_fft, win_length=win_length, hop_length=hop_length, window=window)\n angles = np.exp(1j * np.angle(rebuilt))\n\n if verbose:\n diff = np.abs(spectrogram) - np.abs(rebuilt)\n t.set_postfix(loss=np.linalg.norm(diff, 'fro'))\n\n full = np.abs(spectrogram).astype(np.complex) * angles\n inverse = librosa.istft(full, hop_length=hop_length, win_length=win_length, window=window)\n return inverse\n\nif __name__ == '__main__':\n # simple tests\n fname = 'data/arctic/wav/arctic_a0001.wav'\n stft, mel = process_audio(fname)\n\n invert_spectrogram(stft, out_fn='test_inv32.wav')\n\n test = np.repeat(np.arange(40)[:, None] + 1, 7, axis=1)\n out = reshape_frames(test.T)\n\n inv = reshape_frames(out, forward=False)\n\n print(test.shape)\n print(out.shape)\n print(inv.shape)\n\n assert np.array_equal(test, inv)"
] | [
[
"numpy.append",
"numpy.reshape",
"numpy.abs",
"numpy.exp",
"numpy.arange",
"numpy.random.rand",
"numpy.angle",
"numpy.array_equal",
"numpy.pad",
"numpy.linalg.norm",
"numpy.split"
]
] |
RachitKeertiDas/LitSocBot | [
"863c629eb53e8783ebaea50fedabce3971c8a33b"
] | [
"main.py"
] | [
"from typing import Optional\nimport discord as dc\nimport os\nfrom discord.ext.commands.core import command\nimport requests\nimport json\nfrom CowsAndBulls import CowsAndBulls\nimport Anagram as ana\nimport feedparser\nimport random\nimport discord\nfrom discord.ext import commands\nfrom dotenv import load_dotenv\nfrom Crossword import Crossword\nfrom CrosswordGen import GenCwd\n# from private import *\nimport urllib.request\nimport numpy as np\nimport cv2 as cv\nfrom keep_alive import keep_alive\n\n\nTOKEN = os.environ['token']\n\nload_dotenv()\n\n# Change only the no_category default string\nhelp_command = commands.DefaultHelpCommand(\n no_category = 'Read it and weep'\n)\n\nbot = commands.Bot(\n command_prefix = commands.when_mentioned_or('>>'),\n help_command = help_command\n)\[email protected]\nasync def on_ready():\n print(\"Logged in as {0.user}\".format(bot))\n\n\n# @bot.command(name='readme', help='Gets the link to the readme for the bot')\n# async def ReadMe(ctx):\n# await ctx.reply('<https://github.com/LitSocBot/LitSocBot/blob/main/README.md>')\n\[email protected](name='anagram', help='Gets possible anagram for the word')\nasync def Anagram(ctx, choice : str):\n await ctx.reply(ctx.author.mention +\" Here are the possible anagrams\\n\" + ana.getAnagrams(choice))\n\[email protected](name='wordswith', help='Gets possible words with the letters')\nasync def Anagram(ctx, choice : str):\n await ctx.reply(ctx.author.mention +\" Here are the possible words with those letters\\n\" + ana.getWordswith(choice))\n\[email protected](name='isthere', help='Tells if a word is there or not')\nasync def Anagram(ctx, choice : str):\n value = ana.isThere(choice)\n if(value):\n await ctx.reply(ctx.author.mention + \"Yes\")\n else:\n await ctx.reply(ctx.author.mention + \"Nope :(\\nTry looking for something else\")\n\n\n#Debate Bot Commands \n#Using discord bot subcommand feature\n#primary command :will generate random debate topics \[email protected](pass_context = True,help = 'Use addtop command (>>debate addtop) to add a custom topic.')\nasync def debate(ctx): \n NewsFeed = feedparser.parse(\"https://www.createdebate.com/browse/debaterss/all/rss\")\n \n number = random.randint(0,11) #there are only 12 debate topics in this api\n entry = NewsFeed.entries[number] \n show = entry.title\n \n if ctx.invoked_subcommand is None:\n await ctx.reply(\"Here:\\n\"+show) \n else:\n print(\"what\") \n\n#secondary command: will add topics given by the user to the category 'mods'\[email protected](pass_context =True) \nasync def addtop(ctx,*,choice): \n with open('topics_updated.txt','r') as f:\n contents = f.readlines()\n choice = choice + \"\\n\"\n contents.insert(146,choice)\n\n with open('topics_updated.txt','w') as f:\n contents = \"\".join(contents)\n f.write(contents)\n \n await ctx.reply(\"The topic has been added.\")\n\n\n#searching through a text file to generate debate topics under specific categories\nloc='' #loc = list of contents\n\nlot= ['*','all','general', 'education', 'society', 'environment', 'politics', 'parenting', 'tech', 'healthcare', 'leisure', 'finance and politics', 'history', 'fun','mods']\n\nfor term in lot: #goes through list of topics and adds these topics to the string loc\n if term =='*':\n continue\n loc=loc+'\\n'+''.join(term)\n\ndef generate_topic(category): \n f=open('topics_updated.txt','r')\n topics=f.read() \n f.close()\n\n #moving the topics from the text file to a list\n lis=topics.split('\\n') \n if category == 'all':\n topic=lis[random.randint(0,len(lis))]\n if((topic not in lot)):\n return topic\n \n #returns topics from specific categories\n li=lis[lis.index(category):lis.index('*',lis.index(category))]\n i=random.randint(0,len(li))\n topic=li[i]\n return topic\n\[email protected](name='debatopic', help='Generate a debate topic based on some category\\nList of Categories:'+loc)\nasync def deb(ctx, choice:str):\n response = generate_topic(choice)\n await ctx.reply(response)\n \n\[email protected](name='startcwd', help='Generates a random crossword')\nasync def cwd(ctx):\n global c\n c = Crossword()\n await ctx.reply(file=discord.File('crossword.jpg'))\n acrossclues = \"\\n\".join(c.across_clues)\n downclues = \"\\n\".join(c.down_clues)\n acrossClues = acrossclues.replace(\"_\", \"\\_\")\n downClues = downclues.replace(\"_\", \"\\_\")\n await ctx.reply(\"**Clues**:\\n**Across**:\\n\" + acrossClues)\n await ctx.reply(\"**Down**:\\n\" + downClues)\n for ind in c.dic_across.keys():\n print(ind, \" : \", c.dic_across[ind])\n for ind in c.dic_down.keys():\n print(ind, \" : \", c.dic_down[ind])\n\n \[email protected](name='answercwd', help='To answer a crossword')\nasync def ans(ctx, val : int, choice : str, answer : str):\n # across = (choice == 'a')\n answer = answer.upper()\n if(c.checkAnswer(answer, val, choice)):\n await ctx.reply(\"Correct Answer\")\n c.enterAnswer(answer, val, choice)\n await ctx.reply(file=discord.File('crossword.jpg'))\n else:\n await ctx.reply(\"Wrong Answer\")\n\[email protected](name='revealcwd', help='Reveals answers of the crossword')\nasync def reveal(ctx):\n c.revealAnswer()\n await ctx.reply(file=discord.File('answer.jpg'))\n\[email protected](name='clues', help='Gives clues for specified grid number and direction')\nasync def clues(ctx, *args):\n if len(args) == 1:\n choice = args[0].lower()\n acrossclues = \"\\n\".join(c.across_clues)\n downclues = \"\\n\".join(c.down_clues)\n acrossClues = acrossclues.replace(\"_\", \"\\_\")\n downClues = downclues.replace(\"_\", \"\\_\")\n if choice == 'all':\n await ctx.reply(\"**Across**:\\n\" + acrossClues)\n await ctx.reply(\"**Down**:\\n\" + downClues)\n if choice == 'down':\n await ctx.reply(\"**Down**:\\n\" + downClues)\n if choice == 'across':\n await ctx.reply(\"**Across**:\\n\" + acrossClues)\n else:\n response = \"\"\n for i in range(len(args) // 2):\n clue = c.giveClues(args[2*i], args[2*i+1])\n response = response + args[2*i] + args[2*i+1] + \". \" + clue + \"\\n\"\n await ctx.reply(response)\n\n\[email protected](name='createcwd', help='Resets the word list to generate a new crossword')\nasync def gencwd(ctx):\n global crwd\n crwd = GenCwd()\n await ctx.reply(\"Word list succesfully reset\")\n\[email protected](name='addword', help='To add a word to the word list which generates the crossword')\nasync def addword(ctx, *args):\n for word in args:\n crwd.addWord(word)\n if len(args) > 1:\n await ctx.reply(\", \".join(args) + \" have been added to the list\")\n else:\n await ctx.reply(\", \".join(args) + \" has been added to the list\")\n\[email protected](name='delword', help='To remove a word from the word list')\nasync def delword(ctx, word):\n deleted = crwd.delWord(word)\n if deleted:\n await ctx.reply(word + \" has been deleted from the word list\")\n else:\n await ctx.reply(\"No such word in the list\")\n \[email protected](name='showcwd', help='Generates a crossword using the word in the word list')\nasync def showcwd(ctx):\n # crwd.computeCwd()\n await ctx.reply(file=discord.File('Test_grid.png'))\n file = open('Clues.txt', 'r')\n content = file.read()\n file.close()\n await ctx.reply(content)\n\[email protected](name='showkey', help='Displays the grid with key to the crossword')\nasync def showkey(ctx):\n await ctx.reply(file=discord.File('Test_key.png'))\n\[email protected](name='xkcd', help='Displays the XKCD corresponding to number(if provided).\\n Otherwise, outputs a random xkcd comic strip.')\nasync def xkcdcomic(ctx, number: int=None):\n if isinstance(number,int) == False:\n number = random.randint(1, 2487)\n url = \"https://xkcd.com/\" + str(number) + \"/info.0.json\"\n pg = requests.get(url)\n if pg.status_code == 404:\n return await ctx.reply(\"The requested comic does not exist.\")\n json_data = json.loads(pg.text)\n img = json_data[\"img\"]\n title = json_data[\"title\"]\n urllib.request.urlretrieve(img, \"xkcd.png\")\n await ctx.reply(title, file=discord.File('xkcd.png'))\n\[email protected](name='startcb', help='Starts a new Cow Bulls game')\nasync def startcowbull(ctx, dig : int):\n global cb \n cb = CowsAndBulls()\n cb.active=True\n cb.digits=dig\n cb.number=cb.makeRandom(cb.digits)\n print(cb.number)\n await ctx.reply('Game started\\nPlease guess a {}-digit number'.format(cb.digits))\n\[email protected](name='guesscb', help='To make a guess')\nasync def guesscowbull(ctx, num : str):\n if(cb.active):\n bulls, cows = CowsAndBulls.compareNumbers(cb.number, num)\n if bulls == cb.digits:\n await ctx.reply('Cows : {}\\nBulls : {}\\nYou win!!'.format(cows, bulls))\n cb.active=False\n elif bulls == -1:\n await ctx.reply('Please enter a {}-digit number'.format(cb.digits))\n else:\n await ctx.reply('Cows : {}\\nBulls : {}'.format(cows, bulls))\n\[email protected](name='stopcb', help='To make a guess')\nasync def stopCowBull(ctx):\n cb.active=False\n await ctx.reply('Game stopped successfully.\\n{} was the answer'.format(cb.number))\n\n\n#this command gives info on movies by searching through their titles\[email protected](help = 'Get movie details')\nasync def movies(ctx,*,choice):\n\n final = choice.replace(\" \",\"+\")\n url = \"http://www.omdbapi.com/?t=\" + final + \"&apikey=5a70a732\"\n\n response = requests.get(url)\n json_data = json.loads(response.text) \n \n if json_data[\"Response\"] == \"True\":\n \n movie_name = json_data[\"Title\"]\n runtime = json_data[\"Runtime\"]\n rating = json_data[\"imdbRating\"]\n genre = json_data[\"Genre\"]\n director = json_data[\"Director\"]\n poster = json_data[\"Poster\"]\n \n if poster != \"N/A\": \n urllib.request.urlretrieve(poster, \"poster.jpg\")\n file = discord.File('poster.jpg')\n\n message = discord.Embed(title = movie_name, color = 0xFFFFFF )\n message.add_field(name = \"Genre\", value = genre, inline= False)\n message.add_field(name= \"Director\", value= director, inline= False)\n message.add_field(name= \"Runtime\", value= runtime, inline= False)\n message.add_field(name= \"IMDb Rating\", value= rating,inline= False)\n message.set_image(url = \"attachment://poster.jpg\")\n \n await ctx.reply(file = file,embed = message)\n\n elif poster == \"N/A\":\n\n message = discord.Embed(title = movie_name, color = 16777215 )\n message.add_field(name = \"Genre\", value = genre, inline= False)\n message.add_field(name= \"Director\", value= director,inline= False)\n message.add_field(name= \"Runtime\", value= runtime,inline= False)\n message.add_field(name= \"IMDb Rating\", value= rating,inline= False)\n\n await ctx.reply(embed = message)\n\n else :\n message = discord.Embed(title = \"Error\", description = \"Either the info isn't available or the spelling is wrong.\", color = 15158332 )\n\n await ctx.reply(embed = message)\n\n\n#a wordsearch that creates grids on random words\[email protected](name='ws', help= 'Generate a 10x10 wordsearch')\nasync def wordsearch_(ctx):\n response=requests.get('https://random-word-api.herokuapp.com/word?number=20')\n l=response.json()\n\n with open ('w.txt', 'w') as w:\n c=0\n for wor in l:\n if c==10:\n break\n if(len(wor)<11):\n w.write(wor+'\\n') \n c+=1\n\n os.system('python word_search.py')\n\n s=''\n #extracting solution from a file\n with open('sol.txt', 'r') as sol: \n for line in sol:\n s=s+''.join(line)\n\n await ctx.reply(s)\n \n #creating a blank 10x10 grid\n rows=10\n blank = np.zeros((rows*30 + (rows +1)*3, rows*30 + (rows +1)*3, 3), dtype='uint8')\n blank[:,:] = 255, 255, 255\n\n for i in range(0, rows+1):\n cv.rectangle(blank, (33*i, 0), (33*i + 3, rows*30 + (rows +1)*3), (128, 128, 128), thickness=-1)\n cv.rectangle(blank, (0, 33*i), (rows*30 + (rows +1)*3, 33*i + 3), (128, 128, 128), thickness=-1)\n\n cv.imwrite('wordsearch.jpg', blank)\n s=''\n with open('ws.txt', 'r') as f:\n st=f.read()\n \n ls=list(st)\n\n count=0\n \n #putting letters in the grid\n for i in range(len(ls)):\n row=count%10\n col=count//10\n cv.putText(blank, str(ls[i]), (row*33 +13, col*33 + 26), cv.FONT_HERSHEY_PLAIN, 1, (0, 0, 0), thickness = 2)\n count+=1\n cv.imwrite('wordsearch.jpg', blank)\n \n await ctx.reply(file=discord.File('wordsearch.jpg'))\n\n\n#this command gives info on books related to IT/CSE by searching through their titles\[email protected](help = 'Get IT books info')\nasync def itbooks(ctx,*,choice):\n\n final = choice.replace(\" \",\"+\")\n url = \"https://api.itbook.store/1.0/search/\"+ final\n\n response = requests.get(url)\n json_data = json.loads(response.text)\n\n bookdesc = \" \"\n\n for bookname in json_data[\"books\"]: \n booktitle = bookname[\"title\"]\n description = bookname[\"subtitle\"] \n link = bookname[\"url\"]\n\n bookdesc += \"**\"+booktitle+\"**\" + \" : \" + description + \"\\n\" + \"<\" + link + \">\" + \"\\n\" \n\n if len(json_data[\"books\"]) != 0 :\n await ctx.reply(bookdesc)\n\n else :\n message = discord.Embed(title = \"Error\", description = \"Either the info isn't available or the spelling is wrong.\", color = 15158332 )\n\n await ctx.reply(embed = message) \n \nkeep_alive()\nbot.run(TOKEN)\n"
] | [
[
"numpy.zeros"
]
] |
Pandinosaurus/closed-form-matting | [
"5fb39478fb9fc938c583a6786adc17cea6dd9c4c"
] | [
"test_matting.py"
] | [
"\"\"\"Tests for Closed-Form matting and foreground/background solver.\"\"\"\nimport unittest\n\nimport cv2\nimport numpy as np\n\nimport closed_form_matting\n\nclass TestMatting(unittest.TestCase):\n def test_solution_close_to_original_implementation(self):\n image = cv2.imread('testdata/source.png', cv2.IMREAD_COLOR) / 255.0\n scribles = cv2.imread('testdata/scribbles.png', cv2.IMREAD_COLOR) / 255.0\n\n alpha = closed_form_matting.closed_form_matting_with_scribbles(image, scribles)\n foreground, background = closed_form_matting.solve_foreground_background(image, alpha)\n\n matlab_alpha = cv2.imread('testdata/matlab_alpha.png', cv2.IMREAD_GRAYSCALE) / 255.0\n matlab_foreground = cv2.imread('testdata/matlab_foreground.png', cv2.IMREAD_COLOR) / 255.0\n matlab_background = cv2.imread('testdata/matlab_background.png', cv2.IMREAD_COLOR) / 255.0\n\n sad_alpha = np.mean(np.abs(alpha - matlab_alpha))\n sad_foreground = np.mean(np.abs(foreground - matlab_foreground))\n sad_background = np.mean(np.abs(background - matlab_background))\n\n self.assertLess(sad_alpha, 1e-2)\n self.assertLess(sad_foreground, 1e-2)\n self.assertLess(sad_background, 1e-2)\n\n def test_matting_with_trimap(self):\n image = cv2.imread('testdata/source.png', cv2.IMREAD_COLOR) / 255.0\n trimap = cv2.imread('testdata/trimap.png', cv2.IMREAD_GRAYSCALE) / 255.0\n\n alpha = closed_form_matting.closed_form_matting_with_trimap(image, trimap)\n\n reference_alpha = cv2.imread('testdata/output_alpha.png', cv2.IMREAD_GRAYSCALE) / 255.0\n\n sad_alpha = np.mean(np.abs(alpha - reference_alpha))\n self.assertLess(sad_alpha, 1e-3)\n"
] | [
[
"numpy.abs"
]
] |
luphord/monte-carlo-contracts | [
"e7723e6304bb5df6f5f2b18225be8feeb09f60e6"
] | [
"tests/test_mcc.py"
] | [
"import unittest\n\nimport numpy as np\nfrom pandas.testing import assert_frame_equal\nfrom dataclasses import dataclass\nfrom typing import Callable\nfrom mcc import (\n parser,\n IndexedCashflows,\n DateIndex,\n Model,\n TermStructuresModel,\n ObservableBool,\n KonstFloat,\n LinearRate,\n FixedAfter,\n Stock,\n FX,\n At,\n Zero,\n One,\n Give,\n Scale,\n And,\n Or,\n When,\n Cond,\n Until,\n Anytime,\n Contract,\n ResolvableContract,\n ZeroCouponBond,\n EuropeanOption,\n BrownianMotion,\n GeometricBrownianMotion,\n simulate_equity_black_scholes_model,\n HoLeeModel,\n)\n\n\n@dataclass\nclass DummyTermStructureModel(TermStructuresModel):\n rate: np.ndarray\n\n def linear_rate(self, frequency: str) -> np.ndarray:\n return self.rate\n\n\ndef _make_model(nsim: int = 100) -> Model:\n dategrid = np.arange(\n np.datetime64(\"2020-01-01\"),\n np.datetime64(\"2020-01-10\"),\n dtype=\"datetime64[D]\",\n )\n numeraire = np.ones((nsim, dategrid.size), dtype=np.float)\n rnd = np.random.RandomState(123)\n rate = rnd.normal(size=(nsim, dategrid.size))\n eurusd = rnd.lognormal(size=(nsim, dategrid.size))\n abc = rnd.lognormal(size=(nsim, dategrid.size))\n return Model(\n dategrid,\n {\"EUR\": DummyTermStructureModel(rate)},\n {(\"EUR\", \"USD\"): eurusd},\n {\"ABC\": abc},\n numeraire,\n \"EUR\",\n )\n\n\n@dataclass\nclass MyContract(ResolvableContract):\n maturity: np.datetime64\n notional: float\n\n def resolve(self) -> Contract:\n return When(At(self.maturity), Scale(KonstFloat(self.notional), One(\"EUR\")))\n\n\nclass AlternatingBool(ObservableBool):\n def __init__(self, start_with_false: bool = True):\n self.offset = 0 if start_with_false else 1\n\n def simulate(self, model: Model) -> np.ndarray:\n mask = np.array(\n (np.arange(model.nsim) + self.offset) % 2, dtype=np.bool_\n ).reshape((model.nsim, 1))\n return np.repeat(mask, model.ndates, axis=1)\n\n\nclass TestMonteCarloContracts(unittest.TestCase):\n def test_argument_parsing(self) -> None:\n args = parser.parse_args([])\n self.assertEqual(args.version, False)\n args = parser.parse_args([\"--version\"])\n self.assertEqual(args.version, True)\n\n def test_simple_cashflows(self) -> None:\n model = _make_model()\n c = Cond(AlternatingBool(), One(\"EUR\"), One(\"USD\"))\n cf = model.generate_cashflows(c)\n simplecf = cf.to_simple_cashflows()\n self.assertEqual(simplecf.shape[1], model.nsim)\n self.assertEqual(simplecf.shape[0], 2)\n assert_frame_equal(simplecf, model.generate_simple_cashflows(c))\n simplecf2 = model.generate_simple_cashflows_in_currency(c, \"USD\")\n self.assertEqual(simplecf2.shape[1], model.nsim)\n self.assertEqual(simplecf2.shape[0], 1)\n self.assertEqual(simplecf2.index[0][1], \"USD\")\n simplecf3 = model.generate_simple_cashflows_in_numeraire_currency(c)\n self.assertEqual(simplecf3.shape[1], model.nsim)\n self.assertEqual(simplecf3.shape[0], 1)\n self.assertEqual(simplecf3.index[0][1], model.numeraire_currency)\n\n def test_cashflows(self) -> None:\n n = 10\n k = 2\n dategrid = np.array([np.datetime64(\"2030-07-14\"), np.datetime64(\"2031-07-14\")])\n cf1 = IndexedCashflows(\n np.zeros((n, k), dtype=IndexedCashflows.dtype),\n np.array([\"USD\"] * k, dtype=(np.unicode_, 3)),\n dategrid,\n )\n self.assertEqual(cf1.nsim, n)\n self.assertEqual(cf1.ncashflows, k)\n self.assertEqual(cf1.currencies.size, k)\n cf2 = IndexedCashflows(\n np.array(\n [\n [(0, 123.45)],\n [(1, 123.45)],\n ],\n IndexedCashflows.dtype,\n ),\n np.array([\"USD\"], dtype=(np.unicode_, 3)),\n dategrid,\n )\n self.assertEqual(cf2.nsim, 2)\n self.assertEqual(cf2.ncashflows, 1)\n self.assertEqual(cf2.currencies.size, 1)\n cf3 = cf1 + cf1\n self.assertTrue((cf3.cashflows[:, :k] == cf1.cashflows).all())\n self.assertTrue((cf3.cashflows[:, k:] == cf1.cashflows).all())\n cf3.apply_index()\n\n def test_negative_date_index(self) -> None:\n dategrid = np.array([np.datetime64(\"2030-07-14\"), np.datetime64(\"2031-07-14\")])\n cf = IndexedCashflows(\n np.array(\n [\n [(0, 123.45)],\n [(-1, 123.45)],\n ],\n IndexedCashflows.dtype,\n ),\n np.array([\"USD\"], dtype=(np.unicode_, 3)),\n dategrid,\n ).apply_index()\n self.assertEqual(cf.cashflows[\"date\"][0], dategrid[0])\n self.assertTrue(np.isnat(cf.cashflows[\"date\"][1]))\n\n def test_model_without_fx(self) -> None:\n model = _make_model()\n model2 = Model(\n model.dategrid,\n {},\n {},\n model.simulated_stocks,\n model.numeraire,\n model.numeraire_currency,\n )\n indexedcf = One(model2.numeraire_currency).generate_cashflows(\n model2.eval_date_index, model\n )\n cf = model2.in_numeraire_currency(indexedcf)\n self.assertTrue((cf.cashflows[\"value\"][:, 0] == 1).all())\n self.assertEqual(model2.currencies, {model2.numeraire_currency})\n\n def test_contract_creation(self) -> None:\n And(\n Or(\n Cond(AlternatingBool(), Zero(), One(\"USD\")),\n When(At(np.datetime64(\"2030-07-14\")), One(\"EUR\")),\n ),\n Give(Scale(KonstFloat(1.23), One(\"USD\"))),\n )\n KonstFloat(1.23)\n KonstFloat(123)\n KonstFloat(np.float_(1.23))\n KonstFloat(np.int_(123))\n KonstFloat(np.float64(123))\n KonstFloat(np.float32(123))\n KonstFloat(np.int64(123))\n KonstFloat(np.int32(123))\n KonstFloat(np.int16(123))\n KonstFloat(np.int8(123))\n\n def test_resolvable_contract_creation(self) -> None:\n model = _make_model()\n c = MyContract(model.dategrid[-1], 1234)\n model.generate_cashflows(c)\n self.assertRaises(TypeError, lambda: ResolvableContract()) # type: ignore\n\n def test_contract_str(self) -> None:\n c = And(\n Or(\n Cond((Stock(\"ABC\") > 28) & ~(Stock(\"DEF\") > 28), Zero(), One(\"USD\")),\n When(At(np.datetime64(\"2030-07-14\")), One(\"EUR\")),\n ),\n And(\n Until(\n FX(\"EUR\", \"USD\") < 1.0, Give(Scale(KonstFloat(1.23), One(\"USD\")))\n ),\n Anytime(\n (Stock(\"DEF\") >= 50) | (Stock(\"DEF\") < 20),\n Scale(Stock(\"ABC\"), One(\"EUR\")),\n ),\n ),\n )\n expected = (\n \"And(Or(Cond((Stock(ABC) > 28) & (~(Stock(DEF) > 28)), Zero, One(USD)), \"\n \"When(2030-07-14, One(EUR))), And(Until(~(FX(EUR/USD) >= 1.0), \"\n \"Give(Scale(1.23, One(USD)))), Anytime((Stock(DEF) >= 50) \"\n \"| (~(Stock(DEF) >= 20)), Scale(Stock(ABC), One(EUR)))))\"\n )\n self.assertEqual(str(c), expected)\n c2 = Scale(Stock(\"ABC\") ** 2 / (Stock(\"DEF\") - 1.7) + 42, One(\"EUR\"))\n self.assertEqual(\n str(c2),\n \"Scale((((Stock(ABC)) ** (2)) / ((Stock(DEF)) + (-1.7))) + (42), One(EUR))\",\n )\n\n def test_model_creation(self) -> None:\n nsim = 100\n model = _make_model(nsim=nsim)\n self.assertEqual(model.shape, (nsim, model.dategrid.size))\n\n def test_date_index(self) -> None:\n model = _make_model()\n at0 = At(model.dategrid[0])\n idx0 = model.eval_date_index.next_after(at0.simulate(model))\n self.assertTrue((idx0.index == 0).all())\n at1 = At(model.dategrid[1])\n idx1 = model.eval_date_index.next_after(at1.simulate(model))\n self.assertTrue((idx1.index == 1).all())\n\n def test_observable_float_calculations(self) -> None:\n model = _make_model()\n stock_twice = Stock(\"ABC\") + Stock(\"ABC\")\n once = Stock(\"ABC\").simulate(model)\n twice = stock_twice.simulate(model)\n self.assertTrue(np.allclose(2 * once, twice))\n addconst = (Stock(\"ABC\") + 123).simulate(model)\n self.assertTrue(np.allclose(once + 123, addconst))\n constadd = (123 + Stock(\"ABC\")).simulate(model)\n self.assertTrue(np.allclose(123 + once, constadd))\n minus = (-Stock(\"ABC\")).simulate(model)\n self.assertTrue(np.allclose(minus, -once))\n constsub = (Stock(\"ABC\") - 123).simulate(model)\n self.assertTrue(np.allclose(constsub, once - 123))\n subconst = (123 - Stock(\"ABC\")).simulate(model)\n self.assertTrue(np.allclose(subconst, 123 - once))\n zero = (Stock(\"ABC\") - Stock(\"ABC\")).simulate(model)\n self.assertTrue(np.allclose(zero, np.zeros(shape=zero.shape)))\n stockmulti = (Stock(\"ABC\") * 123).simulate(model)\n self.assertTrue(np.allclose(stockmulti, 123 * once))\n multistock = (123 * Stock(\"ABC\")).simulate(model)\n self.assertTrue(np.allclose(multistock, once * 123))\n stocksquared = (Stock(\"ABC\") * Stock(\"ABC\")).simulate(model)\n self.assertTrue(np.allclose(stocksquared, once ** 2))\n stockdiv = (Stock(\"ABC\") / 123).simulate(model)\n self.assertTrue(np.allclose(stockdiv, once / 123))\n divstock = (123 / Stock(\"ABC\")).simulate(model)\n self.assertTrue(np.allclose(divstock, 123 / once))\n one = (Stock(\"ABC\") / Stock(\"ABC\")).simulate(model)\n self.assertTrue(np.allclose(one, np.ones(shape=zero.shape)))\n org = (1 / (1 / Stock(\"ABC\"))).simulate(model)\n self.assertTrue(np.allclose(org, once))\n stockpower = (Stock(\"ABC\") ** 123).simulate(model)\n self.assertTrue(np.allclose(stockpower, once ** 123))\n powerstock = (123 ** Stock(\"ABC\")).simulate(model)\n self.assertTrue(np.allclose(powerstock, 123 ** once))\n stockstock = (Stock(\"ABC\") ** Stock(\"ABC\")).simulate(model)\n self.assertTrue(np.allclose(stockstock, once ** once))\n org2 = ((Stock(\"ABC\") ** 3) ** (1 / 3)).simulate(model)\n self.assertTrue(np.allclose(org2, once))\n\n def test_observable_float_comparisons(self) -> None:\n model = _make_model()\n # greater or equal\n barrier_breach = Stock(\"ABC\") >= 1\n bbsim = barrier_breach.simulate(model)\n self.assertTrue((bbsim == (model.simulated_stocks[\"ABC\"] >= 1)).all())\n shouldbeall = Stock(\"ABC\") >= Stock(\"ABC\")\n self.assertTrue(shouldbeall.simulate(model).all())\n # strictly greater\n barrier_breach = Stock(\"ABC\") > 1\n bbsim = barrier_breach.simulate(model)\n self.assertTrue((bbsim == (model.simulated_stocks[\"ABC\"] > 1)).all())\n shouldbenone = Stock(\"ABC\") > Stock(\"ABC\")\n self.assertFalse(shouldbenone.simulate(model).any())\n # less or equal\n barrier_breach = Stock(\"ABC\") <= 1\n bbsim = barrier_breach.simulate(model)\n self.assertTrue((bbsim == (model.simulated_stocks[\"ABC\"] <= 1)).all())\n shouldbeall = Stock(\"ABC\") <= Stock(\"ABC\")\n self.assertTrue(shouldbeall.simulate(model).all())\n # strictly less\n barrier_breach = Stock(\"ABC\") < 1\n bbsim = barrier_breach.simulate(model)\n self.assertTrue((bbsim == (model.simulated_stocks[\"ABC\"] < 1)).all())\n shouldbenone = Stock(\"ABC\") < Stock(\"ABC\")\n self.assertFalse(shouldbenone.simulate(model).any())\n # test right comparison operator application\n self.assertIsInstance(1 <= Stock(\"ABC\"), ObservableBool)\n self.assertIsInstance(1 < Stock(\"ABC\"), ObservableBool)\n self.assertIsInstance(1 >= Stock(\"ABC\"), ObservableBool)\n self.assertIsInstance(1 > Stock(\"ABC\"), ObservableBool)\n\n def test_fixed_after(self) -> None:\n model = _make_model()\n fixed1 = FixedAfter(AlternatingBool(), Stock(\"ABC\"))\n fixed1sim = fixed1.simulate(model)\n altsim = AlternatingBool().simulate(model)\n self.assertTrue(\n np.allclose(fixed1sim[altsim[:, 0], 0], fixed1sim[altsim[:, 0], -1])\n )\n self.assertFalse(\n np.isclose(fixed1sim[~altsim[:, 0], 0], fixed1sim[~altsim[:, 0], -1]).any()\n )\n fixed2 = FixedAfter(At(model.dategrid[-2, 0]), Stock(\"ABC\"))\n fixed2sim = fixed2.simulate(model)\n self.assertTrue(np.allclose(fixed2sim[:, -2], fixed2sim[:, -1]))\n self.assertFalse(np.isclose(fixed2sim[:, -3], fixed2sim[:, -1]).any())\n\n def test_boolean_operators(self) -> None:\n model = _make_model()\n alt = AlternatingBool()\n altsim = alt.simulate(model)\n altinvertsim = (~alt).simulate(model)\n self.assertTrue((altsim == ~altinvertsim).all())\n alt2 = AlternatingBool(False)\n self.assertFalse((alt & alt2).simulate(model).any())\n self.assertTrue((alt | alt2).simulate(model).all())\n\n def test_rates(self) -> None:\n model = _make_model()\n dategrid = model.dategrid.flatten()\n yearfraction = (dategrid[-1] - dategrid[-3]).astype(np.float64) / 365\n c = When(\n At(model.dategrid[-1]),\n Scale(\n FixedAfter(At(dategrid[-3]), LinearRate(\"EUR\", \"3M\")) * yearfraction,\n One(\"EUR\"),\n ),\n )\n cf = model.generate_cashflows(c)\n self.assertEqual(cf.currencies.shape, (1,))\n self.assertEqual(cf.cashflows.shape, (model.nsim, 1))\n self.assertTrue((cf.cashflows[\"date\"] == model.dategrid[-1]).all())\n self.assertEqual(cf.currencies[0], \"EUR\")\n\n def test_stock(self) -> None:\n model = _make_model()\n c = When(At(model.dategrid[-1]), Scale(Stock(\"ABC\"), One(\"EUR\")))\n cf = model.generate_cashflows(c)\n self.assertEqual(cf.currencies.shape, (1,))\n self.assertEqual(cf.cashflows.shape, (model.nsim, 1))\n self.assertTrue(\n (cf.cashflows[\"value\"][:, 0] == model.simulated_stocks[\"ABC\"][:, -1]).all()\n )\n self.assertTrue((cf.cashflows[\"date\"] == model.dategrid[-1]).all())\n self.assertEqual(cf.currencies[0], \"EUR\")\n\n def test_fx(self) -> None:\n model = _make_model()\n c = When(At(model.dategrid[-1]), Scale(FX(\"EUR\", \"USD\"), One(\"EUR\")))\n cf = model.generate_cashflows(c)\n self.assertEqual(cf.currencies.shape, (1,))\n self.assertEqual(cf.cashflows.shape, (model.nsim, 1))\n self.assertTrue(\n (\n cf.cashflows[\"value\"][:, 0] == model.simulated_fx[(\"EUR\", \"USD\")][:, -1]\n ).all()\n )\n self.assertTrue((cf.cashflows[\"date\"] == model.dategrid[-1]).all())\n self.assertEqual(cf.currencies[0], \"EUR\")\n c = When(At(model.dategrid[-1]), Scale(FX(\"USD\", \"EUR\"), One(\"EUR\")))\n cf = model.generate_cashflows(c)\n self.assertTrue(\n (\n cf.cashflows[\"value\"][:, 0]\n == 1 / model.simulated_fx[(\"EUR\", \"USD\")][:, -1]\n ).all()\n )\n\n def test_cashflow_currency_conversion(self) -> None:\n model = _make_model()\n self.assertEqual(model.currencies, {\"EUR\", \"USD\"})\n c = When(At(model.dategrid[-1]), Scale(Stock(\"ABC\"), One(\"EUR\")))\n cf_eur = c.generate_cashflows(model.eval_date_index, model)\n self.assertRaises(AssertionError, lambda: model.in_currency(cf_eur, \"GBP\"))\n cf_usd = model.in_currency(cf_eur, \"USD\")\n self.assertEqual(cf_eur.cashflows.shape, cf_usd.cashflows.shape)\n self.assertEqual(cf_usd.currencies[0], \"USD\")\n cf_eur_conv = model.in_numeraire_currency(cf_usd)\n self.assertEqual(cf_eur_conv.currencies[0], \"EUR\")\n self.assertTrue(\n np.allclose(cf_eur.cashflows[\"value\"], cf_eur_conv.cashflows[\"value\"])\n )\n # test with deterministic spots\n numeraire = np.ones((1, model.dategrid.size), dtype=np.float_)\n ccyspot = np.arange(1, model.dategrid.size + 1, dtype=np.float_).reshape(\n numeraire.shape\n )\n model2 = Model(\n model.dategrid, {}, {(\"UND\", \"ACC\"): ccyspot}, {}, numeraire, \"UND\"\n )\n self.assertEqual(model2.currencies, {\"UND\", \"ACC\"})\n for i, dt in enumerate(model2.dategrid):\n c = When(At(dt), One(\"UND\"))\n cf_und = c.generate_cashflows(model2.eval_date_index, model2)\n cf_acc = model2.in_currency(cf_und, \"ACC\")\n self.assertEqual(cf_acc.cashflows[\"value\"][0, 0], i + 1)\n for i, dt in enumerate(model2.dategrid):\n c = When(At(dt), One(\"ACC\"))\n cf_acc = c.generate_cashflows(model2.eval_date_index, model2)\n cf_und = model2.in_numeraire_currency(cf_acc)\n self.assertEqual(cf_und.cashflows[\"value\"][0, 0], 1 / (i + 1))\n\n def test_cashflow_currency_conversion_nnn(self) -> None:\n model = _make_model()\n self.assertEqual(model.currencies, {\"EUR\", \"USD\"})\n c = Zero()\n cf = c.generate_cashflows(model.eval_date_index, model)\n converted = model.in_currency(cf, \"EUR\")\n self.assertEqual(converted.currencies[0], \"NNN\")\n c2 = One(\"EUR\")\n cf2 = c2.generate_cashflows(model.eval_date_index, model)\n self.assertRaises(AssertionError, lambda: model.in_currency(cf2, \"NNN\"))\n self.assertRaises(AssertionError, lambda: model.get_simulated_fx(\"NNN\", \"EUR\"))\n self.assertRaises(AssertionError, lambda: model.get_simulated_fx(\"EUR\", \"NNN\"))\n\n def test_boolean_obs_at(self) -> None:\n model = _make_model()\n at0 = At(model.dategrid[0])\n at0sim = at0.simulate(model)\n self.assertEqual(at0sim.dtype, np.bool_)\n self.assertEqual(at0sim.shape, model.shape)\n self.assertTrue(at0sim[:, 0].all())\n self.assertFalse(at0sim[:, 1].any())\n at1 = At(model.dategrid[1])\n at1sim = at1.simulate(model)\n self.assertEqual(at1sim.dtype, np.bool_)\n self.assertEqual(at1sim.shape, model.shape)\n self.assertFalse(at1sim[:, 0].any())\n self.assertTrue(at1sim[:, 1].all())\n alt = AlternatingBool()\n altsim = alt.simulate(model)\n self.assertFalse(altsim[np.arange(0, model.nsim, 2), :].any())\n self.assertTrue(altsim[np.arange(1, model.nsim, 2), :].all())\n\n def test_zero_cashflow_generation(self) -> None:\n model = _make_model()\n cf = model.generate_cashflows(Zero())\n self.assertEqual(cf.currencies.shape, (1,))\n self.assertEqual(cf.currencies[0], \"NNN\")\n self.assertEqual(cf.cashflows.shape, (model.nsim, 1))\n self.assertTrue((cf.cashflows[\"value\"] == 0).all())\n self.assertTrue((cf.cashflows[\"date\"] == model.eval_date).all())\n\n def test_one_cashflow_generation(self) -> None:\n ccy = \"EUR\"\n c = One(ccy)\n model = _make_model()\n cf = c.generate_cashflows(model.eval_date_index, model)\n self.assertEqual(cf.currencies.shape, (1,))\n self.assertEqual(cf.cashflows.shape, (model.nsim, 1))\n self.assertTrue((cf.cashflows[\"value\"] == 1).all())\n self.assertTrue((cf.cashflows[\"index\"] == 0).all())\n self.assertEqual(cf.currencies[0], ccy)\n bad_eval_idx = DateIndex(np.zeros((model.nsim + 1,), dtype=np.int))\n self.assertRaises(\n AssertionError, lambda: c.generate_cashflows(bad_eval_idx, model)\n )\n\n def test_give_cashflow_generation(self) -> None:\n model = _make_model()\n cf = model.generate_cashflows(Give(One(\"EUR\")))\n self.assertEqual(cf.currencies.shape, (1,))\n self.assertEqual(cf.currencies[0], \"EUR\")\n self.assertEqual(cf.cashflows.shape, (model.nsim, 1))\n self.assertTrue((cf.cashflows[\"value\"] == -1).all())\n self.assertTrue((cf.cashflows[\"date\"] == model.eval_date).all())\n\n def test_scale_cashflow_generation(self) -> None:\n model = _make_model()\n cf = model.generate_cashflows(Scale(KonstFloat(1.23), One(\"EUR\")))\n self.assertEqual(cf.currencies.shape, (1,))\n self.assertEqual(cf.currencies[0], \"EUR\")\n self.assertEqual(cf.cashflows.shape, (model.nsim, 1))\n self.assertTrue((cf.cashflows[\"value\"] == 1.23).all())\n self.assertTrue((cf.cashflows[\"date\"] == model.eval_date).all())\n\n def test_and_cashflow_generation(self) -> None:\n c = And(One(\"EUR\"), One(\"USD\"))\n model = _make_model()\n cf = c.generate_cashflows(model.eval_date_index, model)\n self.assertEqual(cf.currencies.shape, (2,))\n self.assertEqual(cf.currencies[0], \"EUR\")\n self.assertEqual(cf.currencies[1], \"USD\")\n self.assertEqual(cf.cashflows.shape, (model.nsim, 2))\n self.assertTrue((cf.cashflows[\"value\"] == 1).all())\n self.assertTrue((cf.cashflows[\"index\"] == 0).all())\n cf_alt = model.generate_cashflows(c)\n self.assertTrue(cf_alt, cf.apply_index())\n\n def test_or_cashflow_generation(self) -> None:\n model = _make_model()\n c2 = Or(One(\"EUR\"), When(At(model.dategrid[-1]), One(\"EUR\")))\n self.assertRaises(NotImplementedError, lambda: model.generate_cashflows(c2))\n c3 = Or(One(\"EUR\"), Scale(KonstFloat(2), One(\"EUR\")))\n cf = model.generate_cashflows(c3)\n self.assertEqual(cf.currencies.shape, (2,))\n self.assertEqual(cf.currencies[0], \"EUR\")\n self.assertEqual(cf.currencies[1], \"EUR\")\n self.assertEqual(cf.cashflows.shape, (model.nsim, 2))\n self.assertTrue((cf.cashflows[\"value\"][:, 0] == 0).all())\n self.assertTrue((np.isnat(cf.cashflows[\"date\"][:, 0])).all())\n self.assertTrue((cf.cashflows[\"value\"][:, 1] == 2).all())\n self.assertTrue((cf.cashflows[\"date\"][:, 1] == model.eval_date).all())\n c4 = Or(One(\"EUR\"), One(\"USD\"))\n cf4 = model.generate_cashflows(c4)\n self.assertEqual(cf4.currencies.shape, (2,))\n self.assertEqual(cf4.currencies[0], \"EUR\")\n self.assertEqual(cf4.currencies[1], \"USD\")\n\n def test_when_cashflow_generation(self) -> None:\n model = _make_model()\n cf = model.generate_cashflows(When(At(model.dategrid[0]), One(\"EUR\")))\n self.assertEqual(cf.currencies.shape, (1,))\n self.assertEqual(cf.currencies[0], \"EUR\")\n self.assertEqual(cf.cashflows.shape, (model.nsim, 1))\n self.assertTrue((cf.cashflows[\"value\"] == 1).all())\n self.assertTrue((cf.cashflows[\"date\"] == model.dategrid[0]).all())\n cf1 = model.generate_cashflows(When(At(model.dategrid[1]), One(\"EUR\")))\n self.assertEqual(cf1.currencies.shape, (1,))\n self.assertTrue(cf1.currencies[0], \"EUR\")\n self.assertEqual(cf1.cashflows.shape, (model.nsim, 1))\n self.assertTrue((cf1.cashflows[\"value\"] == 1).all())\n self.assertTrue((cf1.cashflows[\"date\"] == model.dategrid[1]).all())\n cf2 = model.generate_cashflows(When(AlternatingBool(), One(\"EUR\")))\n self.assertEqual(cf2.currencies.shape, (1,))\n self.assertTrue(cf2.currencies[0], \"EUR\")\n self.assertEqual(cf2.cashflows.shape, (model.nsim, 1))\n self.assertTrue(\n (cf2.cashflows[\"value\"][np.arange(0, model.nsim, 2), :] == 0).all()\n )\n self.assertTrue(\n (cf2.cashflows[\"value\"][np.arange(1, model.nsim, 2), :] == 1).all()\n )\n\n def test_cond_cashflow_generation(self) -> None:\n model = _make_model()\n cf = model.generate_cashflows(Cond(AlternatingBool(), One(\"EUR\"), One(\"USD\")))\n self.assertEqual(cf.currencies.shape, (2,))\n self.assertEqual(cf.currencies[0], \"EUR\")\n self.assertEqual(cf.currencies[1], \"USD\")\n self.assertEqual(cf.cashflows.shape, (model.nsim, 2))\n self.assertTrue(\n (cf.cashflows[\"value\"][np.arange(0, model.nsim, 2), 0] == 0).all()\n )\n self.assertTrue(\n (cf.cashflows[\"value\"][np.arange(0, model.nsim, 2), 1] == 1).all()\n )\n self.assertTrue(\n (cf.cashflows[\"value\"][np.arange(1, model.nsim, 2), 0] == 1).all()\n )\n self.assertTrue(\n (cf.cashflows[\"value\"][np.arange(1, model.nsim, 2), 1] == 0).all()\n )\n\n def test_until_cashflow_generation(self) -> None:\n model = _make_model()\n cf = model.generate_cashflows(Until(AlternatingBool(), One(\"EUR\")))\n self.assertEqual(cf.currencies.shape, (1,))\n self.assertEqual(cf.currencies[0], \"EUR\")\n self.assertEqual(cf.cashflows.shape, (model.nsim, 1))\n self.assertTrue(\n (cf.cashflows[\"value\"][np.arange(0, model.nsim, 2), 0] == 1).all()\n )\n self.assertTrue(\n (cf.cashflows[\"value\"][np.arange(1, model.nsim, 2), 0] == 0).all()\n )\n\n def test_discounting(self) -> None:\n dategrid = np.arange(\n np.datetime64(\"2020-01-01\"),\n np.datetime64(\"2020-06-01\"),\n 30,\n dtype=\"datetime64[D]\",\n )\n rnd = np.random.RandomState(seed=123)\n n = 100\n rate = 0.03\n model = simulate_equity_black_scholes_model(\n \"ABC\", \"USD\", 123, dategrid, 0.2, rate, n, rnd, use_moment_matching=True\n )\n for t in dategrid:\n c = When(At(t), One(\"USD\"))\n cf = c.generate_cashflows(model.eval_date_index, model)\n npv = model.discount(cf)[:, 0].mean()\n self.assertEqual(model.evaluate(c), npv)\n self.assertEqual(model.evaluate(cf), npv)\n dt = (t - dategrid[0]).astype(np.float64) / 365\n self.assertTrue(np.isclose(npv, np.exp(-rate * dt)))\n model.evaluate(When(Stock(\"ABC\") > 130, One(\"USD\")))\n\n def test_evaluation(self) -> None:\n model = _make_model()\n c = When(At(model.dategrid[-1]), One(\"EUR\"))\n npv = model.evaluate(c)\n self.assertEqual(npv, 1)\n\n def test_zero_coupon_bond(self) -> None:\n model = _make_model()\n notional = 1234\n currency = \"USD\"\n zcb = ZeroCouponBond(model.dategrid[-2], notional, currency)\n cf = model.generate_cashflows(zcb)\n self.assertEqual(cf.currencies.shape, (1,))\n self.assertEqual(cf.currencies[0], currency)\n self.assertEqual(cf.cashflows.shape, (model.nsim, 1))\n self.assertTrue((cf.cashflows[\"value\"] == notional).all())\n self.assertTrue((cf.cashflows[\"date\"] == model.dategrid[-2]).all())\n\n def test_european_option_on_zcb(self) -> None:\n model = _make_model()\n notional = 1234\n currency = \"USD\"\n strike = 1000\n zcb = ZeroCouponBond(model.dategrid[-2], notional, currency)\n opt = EuropeanOption(\n model.dategrid[-2], And(zcb, Give(Scale(KonstFloat(strike), One(currency))))\n )\n cf = model.generate_cashflows(opt)\n self.assertEqual(cf.currencies.shape, (3,))\n self.assertEqual(cf.currencies[0], currency)\n self.assertEqual(cf.currencies[1], currency)\n self.assertEqual(cf.currencies[2], \"NNN\")\n self.assertEqual(cf.cashflows.shape, (model.nsim, 3))\n self.assertTrue((cf.cashflows[\"date\"][:, 0] == model.dategrid[-2]).all())\n self.assertTrue((cf.cashflows[\"value\"][:, 0] == notional).all())\n self.assertTrue((cf.cashflows[\"date\"][:, 1] == model.dategrid[-2]).all())\n self.assertTrue((cf.cashflows[\"value\"][:, 1] == -strike).all())\n self.assertTrue((np.isnat(cf.cashflows[\"date\"][:, 2])).all())\n self.assertTrue((cf.cashflows[\"value\"][:, 2] == 0).all())\n\n def test_brownian_motions(self) -> None:\n mu = 0.123\n sigma = 0.456\n bm = BrownianMotion(mu_t=lambda t: mu * t, sigma=sigma)\n gbm = GeometricBrownianMotion(mu_t=lambda t: mu * t, sigma=sigma)\n rnd = np.random.RandomState(1234)\n t = np.linspace(0, 20, 20)\n n = 200\n x = bm.simulate(t, n, rnd)\n bm.expected(t), bm.stddev(t)\n bm.moment_match(t, x)\n self.assertEqual((n, t.size), x.shape)\n self.assertEqual(n, x[:, -1].size)\n x = gbm.simulate(t, n, rnd)\n self.assertEqual((n, t.size), x.shape)\n self.assertEqual(n, x[:, -1].size)\n gbm.expected(t), gbm.stddev(t)\n gbm.moment_match(t, x)\n\n def test_moment_matched_brownian_motions(self) -> None:\n bm = BrownianMotion(lambda t: t)\n rnd = np.random.RandomState(1234)\n t = np.linspace(0, 20, 20)\n n = 200\n x = bm.simulate_with_moment_matching(t, n, rnd)\n self.assertTrue(np.allclose(x.mean(axis=0), t))\n self.assertTrue(np.allclose(x.std(axis=0), np.sqrt(t)))\n gbm = GeometricBrownianMotion()\n x = gbm.simulate_with_moment_matching(t, n, rnd)\n self.assertTrue(np.allclose(x.mean(axis=0), np.ones(t.shape)))\n self.assertTrue(np.allclose(x.var(axis=0), np.exp(t) - 1))\n\n def test_equity_black_scholes(self) -> None:\n dategrid = np.arange(\n np.datetime64(\"2020-01-01\"),\n np.datetime64(\"2020-01-10\"),\n dtype=\"datetime64[D]\",\n )\n rnd = np.random.RandomState(seed=123)\n ndates = dategrid.size\n n = 100\n m = simulate_equity_black_scholes_model(\n \"ABC\", \"EUR\", 123, dategrid, 0.2, 0.2, n, rnd, use_moment_matching=True\n )\n self.assertIn(\"ABC\", m.simulated_stocks)\n self.assertEqual(m.simulated_stocks[\"ABC\"].shape, (n, ndates))\n self.assertEqual(m.numeraire.shape, (n, ndates))\n for t in dategrid:\n c = When(At(t), Scale(Stock(\"ABC\"), One(\"EUR\")))\n self.assertTrue(np.isclose(m.evaluate(c), 123))\n\n def test_ho_lee_model(self) -> None:\n dategrid = np.arange(\n np.datetime64(\"2020-01-01\"),\n np.datetime64(\"2020-12-01\"),\n 30,\n dtype=\"datetime64[D]\",\n )\n rnd = np.random.RandomState(seed=123)\n n = 100\n sigma = 0.2\n rate = 0.08\n discount_curve: Callable[[float], float] = lambda t: np.exp(-rate * t)\n hl = HoLeeModel(dategrid, discount_curve, sigma, n, rnd, True)\n self.assertEqual(hl.shortrates.shape, (n, dategrid.size))\n self.assertTrue(np.allclose(hl.mu_t(hl.yearfractions), hl._mu_t))\n self.assertTrue(\n (\n np.abs(\n discount_curve(hl.yearfractions)\n - hl.discount_factors().mean(axis=0)\n )\n < 0.001\n ).all()\n )\n bp = hl.bond_prices(hl.yearfractions[-1])\n self.assertTrue(np.allclose(bp[:, -1], 1))\n"
] | [
[
"numpy.ones",
"numpy.isclose",
"numpy.int_",
"numpy.int64",
"numpy.random.RandomState",
"numpy.datetime64",
"numpy.isnat",
"numpy.float64",
"numpy.allclose",
"numpy.linspace",
"numpy.int8",
"numpy.sqrt",
"numpy.float_",
"numpy.zeros",
"numpy.float32",
"numpy.repeat",
"numpy.int32",
"numpy.arange",
"numpy.int16",
"numpy.exp",
"numpy.array"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.