repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
nesl/Black-box-ECG-attack
[ "726c9009ce192708f5173433dff2bc7ca9393b1b" ]
[ "ECG_v1/attacklib/boundary_attack.py" ]
[ "import numpy as np \nfrom numpy.linalg import norm\nimport collections\nimport os, sys\nimport matplotlib.pyplot as plt\nimport pdb\nimport scipy \nimport sys\nsys.path.append(\"..\") \nfrom utils import smooth\n\n# Smooth function\ndef sm(data):\n data = data.squeeze()\n length = data.size\n temp1 = data[1:]\n temp0 = data[:length-1]\n diff = temp1 - temp0\n var = np.std(diff)\n return var\n\nclass BoundaryAttack(object):\n\tdef __init__(self, model, shape, args, source_step=0.01, spherical_step=0.01,\n\t\t\t\tstep_adaptation=1.5):\n\t\tsuper(BoundaryAttack, self).__init__()\n\t\tself.model = model \n\t\tself.source_step = source_step\n\t\tself.spherical_step = spherical_step\n\t\tself.stats_spherical_adversarial = collections.deque(maxlen=100)\n\t\tself.stats_step_adversarial = collections.deque(maxlen=30)\n\n\t\tself.min = np.zeros(shape, dtype=np.float32)\n\t\tself.max = np.ones(shape, dtype=np.float32)\n\n\t\tself.type = np.float32\n\n\t\tself.step_adaptation = step_adaptation\n\t\tself.log_every_n_steps = 1\n\t\tself.args = args\n\n\tdef prepare_generate_candidates(self, original, perturbed):\n\t\tunnormalized_source_direction = original - perturbed\n\t\tsource_norm = norm(unnormalized_source_direction)\n\t\tsource_direction = unnormalized_source_direction / source_norm\n\t\treturn unnormalized_source_direction, source_direction, source_norm\n\t\n\tdef generate_candidate_default(self, original,\n\t\t\tunnormalized_source_direction, source_direction, source_norm):\n\t\tspherical_step = self.spherical_step\n\t\tsource_step = self.source_step\n\n\t\tperturbation = np.random.randn(*original.shape)\n\t\tperturbation = perturbation.astype(np.float32)\n\t\tshape = perturbation.shape \n\t\t# apply hanning filter\n\t\tif self.args.smooth:\n\t\t\tif self.args.win%2==1: \n\t\t\t\t# Verifying Odd Window Size\n\t\t\t\tperturbation = smooth(perturbation.squeeze(), window_len=self.args.win)\n\t\t\t\tperturbation = perturbation.reshape(shape)\n\n\t\t# ===========================================================\n\t\t# calculate candidate on sphere\n\t\t# ===========================================================\n\t\tdot = np.vdot(perturbation, source_direction)\n\t\tperturbation -= dot * source_direction\n\t\tperturbation *= spherical_step * source_norm / norm(perturbation)\n\n\t\tD = 1 / np.sqrt(spherical_step ** 2 + 1)\n\t\tdirection = perturbation - unnormalized_source_direction\n\t\tspherical_candidate = original + D * direction\n\n\t\t# ===========================================================\n\t\t# add perturbation in direction of source\n\t\t# ===========================================================\n\n\t\tnew_source_direction = original - spherical_candidate\n\t\tnew_source_direction_norm = norm(new_source_direction)\n\n\t\t# length if spherical_candidate would be exactly on the sphere\n\t\tlength = source_step * source_norm\n\n\t\t# length including correction for deviation from sphere\n\t\tdeviation = new_source_direction_norm - source_norm\n\t\tlength += deviation\n\n\t\t# make sure the step size is positive\n\t\tlength = max(0, length)\n\n\t\t# normalize the length\n\t\tlength = length / new_source_direction_norm\n\n\t\tcandidate = spherical_candidate + length * new_source_direction\n\t\t\n\t\t\n\t\treturn (candidate, spherical_candidate)\n\n\tdef update_step_sizes(self):\n\t\tdef is_full(deque):\n\t\t\treturn len(deque) == deque.maxlen\n\n\t\tif not (\n\t\t\tis_full(self.stats_spherical_adversarial)\n\t\t\tor is_full(self.stats_step_adversarial)\n\t\t):\n\t\t\t# updated step size recently, not doing anything now\n\t\t\treturn\n\n\t\tdef estimate_probability(deque):\n\t\t\tif len(deque) == 0:\n\t\t\t\treturn None\n\t\t\treturn np.mean(deque)\n\n\t\tp_spherical = estimate_probability(self.stats_spherical_adversarial)\n\t\tp_step = estimate_probability(self.stats_step_adversarial)\n\n\t\tn_spherical = len(self.stats_spherical_adversarial)\n\t\tn_step = len(self.stats_step_adversarial)\n\n\t\tdef log(message):\n\t\t\t_p_spherical = p_spherical\n\t\t\tif _p_spherical is None: # pragma: no cover\n\t\t\t\t_p_spherical = -1.0\n\n\t\t\t_p_step = p_step\n\t\t\tif _p_step is None:\n\t\t\t\t_p_step = -1.0\n\n\t\t\tprint(\n\t\t\t\t\" {} spherical {:.2f} ({:3d}), source {:.2f} ({:2d})\".format(\n\t\t\t\t\tmessage, _p_spherical, n_spherical, _p_step, n_step\n\t\t\t\t)\n\t\t\t)\n\n\t\tif is_full(self.stats_spherical_adversarial):\n\t\t\t# Constrains orthogonal steps based on previous probabilities\n\t\t\t# where the spherical candidate is in the correct target class\n\t\t\t# so it's between .2 and .5 \n\t\t\tif p_spherical > 0.5:\n\t\t\t\tmessage = \"Boundary too linear, increasing steps:\t\"\n\t\t\t\tself.spherical_step *= self.step_adaptation\n\t\t\t\tself.source_step *= self.step_adaptation\n\t\t\telif p_spherical < 0.2:\n\t\t\t\tmessage = \"Boundary too non-linear, decreasing steps:\"\n\t\t\t\tself.spherical_step /= self.step_adaptation\n\t\t\t\tself.source_step /= self.step_adaptation\n\t\t\telse:\n\t\t\t\tmessage = None\n\n\t\t\tif message is not None:\n\t\t\t\tself.stats_spherical_adversarial.clear()\n\t\t\t\tlog(message)\n\n\t\tif is_full(self.stats_step_adversarial):\n\t\t\t# Constrains step towards the source after orthogonal step\n\t\t\t# If it's too small, remaining in the targeted class,\n\t\t\t# then we want to be right along the boundary as to lower\n\t\t\t# the rate of sucess of attacks, since they will be more\n\t\t\t# responsive to smaller steps\n\t\t\tif p_step > 0.5:\n\t\t\t\tmessage = \"Success rate too high, increasing source step:\"\n\t\t\t\tself.source_step *= self.step_adaptation\n\t\t\telif p_step < 0.2:\n\t\t\t\tmessage = \"Success rate too low, decreasing source step: \"\n\t\t\t\tself.source_step /= self.step_adaptation\n\t\t\telse:\n\t\t\t\tmessage = None\n\n\t\t\tif message is not None:\n\t\t\t\tself.stats_step_adversarial.clear()\n\t\t\t\tlog(message)\n\n\tdef attack(self, target_ecg, orig_ecg, orig, target, max_iterations, max_queries):\n\t\t# Added parameter queries to limit query amount, default is infinite\n\t\tprint(\"Initial spherical_step = {:.2f}, source_step = {:.2f}\".format(\n\t\t\t\tself.spherical_step, self.source_step\n\t\t\t))\n\t\tprint(\"Window size: {}\".format(self.args.win))\n\t\tm = np.size(orig_ecg)\n\t\tn_batches = 25\n\t\tperturbed = target_ecg\n\t\toriginal = orig_ecg\n\t\tquery = 0\n\t\titeration = 1\n\t\tquery_dist_smooth = np.empty((3,1))\n\t\t# Iteration value for row 0\n\t\tquery_dist_smooth[1][0] = norm(original - perturbed)/m\n\t\t# Distance value for row 1\n\t\tquery_dist_smooth[2][0] = sm(perturbed - original, perturbed.shape[1])\n\t\tbool = True\n\t\t# Set to false to terminate attack function\n\t\trel_improvement_temp = 1\n\t\t# History of adversarial attacks\n\t\thist_adv = np.array(target_ecg).reshape((1,perturbed.shape[1]))\n\t\t# Add an iterations variable instead so we can use a while loop\n\t\t# Update each time like it normally would at the end of each loop\n\t\t# while max_iterations >= iterations && max_queries >= iterations\n\n\t\twhile (iteration <= max_iterations) :\n\t\t\t\t\t\t# Only appending every 10th step, not wasting memory\n\t\t\t\t\t\t# on every single step taken, rep. sample\n\t\t\tdo_spherical = (iteration % 10 == 0)\n\t\t\t\n\t\t\tunnormalized_source_direction, source_direction, source_norm = self.prepare_generate_candidates(\n\t\t\t\toriginal, perturbed)\n\n\t\t\tdistance = source_norm\n\t\t\tfor i in range(n_batches):\n\n\t\t\t\t# generate candidates\n\t\t\t\tcandidate, spherical_candidate = self.generate_candidate_default(original,\n\t\t\t\t\tunnormalized_source_direction, source_direction, source_norm)\n\t\t\t\t# candidate is the final result after both orthogonal and\n\t\t\t\t# source steps, while spherical step is just the\n\t\t\t\t# orthotogonal step wrt to the surface of the sphere\n\t\t\t\tif do_spherical:\n\t\t\t\t\tspherical_is_adversarial = (np.argmax(self.model.predict(spherical_candidate)) == target)\n\t\t\t\t\tquery += 1\n\t\t\t\t\tif (query % 200 == 0):\n\t\t\t\t\t\ttemp = np.empty((3,1))\n\t\t\t\t\t\ttemp[0][0] = query / 100\n\t\t\t\t\t\ttemp[1][0] = norm(original - perturbed)/m\n\t\t\t\t\t\ttemp[2][0] = sm(perturbed - original,perturbed.shape[1])\n\t\t\t\t\t\tquery_dist_smooth = np.append(query_dist_smooth, temp, axis = 1)\n\t\t\t\t\tself.stats_spherical_adversarial.appendleft(\n\t\t\t\t\t\t\tspherical_is_adversarial)\n\t\t\t\t\tis_adversarial = (np.argmax(self.model.predict(candidate)) == target)\n\t\t\t\t\tquery += 1\n\t\t\t\t\tif (query % 200 == 0):\n\t\t\t\t\t\ttemp = np.empty((3,1))\n\t\t\t\t\t\ttemp[0][0] = query / 100\n\t\t\t\t\t\ttemp[1][0] = norm(original - perturbed)/m\n\t\t\t\t\t\ttemp[2][0] = sm(perturbed - original,perturbed.shape[1])\n\t\t\t\t\t\tquery_dist_smooth = np.append(query_dist_smooth, temp, axis = 1)\n\t\t\t\t\tself.stats_step_adversarial.appendleft(is_adversarial)\n\t\t\t\t\t# is_adversarial is wrt to the final position\n\t\t\t\t\t# and final perturbed image after both steps\n\t\t\t\t\tif is_adversarial:\n\t\t\t\t\t\tnew_perturbed = candidate\n\t\t\t\t\t\tnew_distance = norm(new_perturbed - original)\n\t\t\t\t\t\tbreak\n\t\t\t\t\t# If final step is adversarial, then the for loops breaks\n\t\t\t\t\t# Sets the new_perturbed to not None, also updating the distance\n\t\t\t\telse:\n\t\t\t\t\tis_adversarial = (np.argmax(self.model.predict(candidate)) == target)\n\t\t\t\t\tquery += 1\n\t\t\t\t\tif (query % 200 == 0):\n\t\t\t\t\t\ttemp = np.empty((3,1))\n\t\t\t\t\t\ttemp[0][0] = query / 100\n\t\t\t\t\t\ttemp[1][0] = norm(original - perturbed)/186\n\t\t\t\t\t\ttemp[2][0] = sm(perturbed - original,perturbed.shape[1])\n\t\t\t\t\t\tquery_dist_smooth = np.append(query_dist_smooth, temp, axis = 1)\n\t\t\t\t\tif is_adversarial:\n\t\t\t\t\t\tnew_perturbed = candidate\n\t\t\t\t\t\tnew_distance = norm(new_perturbed - original)\n\t\t\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tnew_perturbed = None\n\t\t\t\t# Determines when to record datapoint for queries vs distance plot \n\n\t\t\tmessage = \"\"\n\t\t\t# This if statement only runs if out of the X iterations\n\t\t\t# one of them result in an adversarial position wrt to\n\t\t\t# the original image\n\t\t\t# If there is no adversarial perturbed image, then this\n\t\t\t# statement doesn't run\n\t\t\tif new_perturbed is not None:\n\t\t\t\tabs_improvement = abs(distance - new_distance)\n\t\t\t\trel_improvement = abs_improvement / distance\n\t\t\t\t# Is this relative improvement what we're looking for??\n\t\t\t\t# How do we decide which percentage is too little change?\n\t\t\t\tmessage = \"d. reduced by {:.3f}% ({:.4e})\".format(\n\t\t\t\t\t\trel_improvement * 100, abs_improvement\n\t\t\t\t\t)\n\t\t\t\tmessage += ' queries {}'.format(query)\n\t\t\t\t# update the variables\n\t\t\t\tperturbed = new_perturbed\n\t\t\t\tdistance = new_distance\n\n\t\t\t\trel_improvement_temp = rel_improvement\n\n\t\t\t\tif iteration % int(max_iterations/100) == 0:\n\t\t\t\t\tstore_dir = self.args.store_dir\n\t\t\t\t\tif not os.path.isdir(store_dir):\n\t\t\t\t\t\tos.makedirs(store_dir, exist_ok=True)\n\t\t\t\t\tsmooth = sm(perturbed - original,perturbed.shape[1])\n\t\t\t\t\tplt.figure()\n\t\t\t\t\tplt.ylabel('Normalized Amplitude')\n\t\t\t\t\tplt.xlabel('Sample Index')\n\t\t\t\t\tplt.title('average L2 distance = {:.4f}, Smoothness = {:.4f} \\n Queries {}'.format(distance/m, smooth, query))\n\t\t\t\t\tplt.plot(np.arange(len(original.squeeze())), original.squeeze(), 'C1', label='Original ECG')\n\t\t\t\t\tplt.plot(np.arange(len(perturbed.squeeze())), perturbed.squeeze(), 'C2', label='Adversarial ECG')\n\t\t\t\t\tplt.legend()\n\t\t\t\t\tplt.savefig(store_dir+str(iteration)+'.png')\n\t\t\t\t\tplt.close()\n\t\t\t\t\thist_adv = np.append(hist_adv, perturbed.reshape((1,perturbed.shape[1])), axis = 0)\n\n\t\t\t\t# store adversarial images\n\t\t\t\t# Potential for iteration to not result in successful adversarial candidate\n\t\t\t\t# To avoid issues where the final adversarial candidate isn't saved, we allowed for the iterations to be one less\n\t\t\t\t# than the maximum alloted iterations\n\t\t\t\tif (iteration == max_iterations) or (iteration == max_iterations - 1) or (query == max_queries):\n\t\t\t\t\tprint(\"stored .npy files\")\n\t\t\t\t\tstore_dir = self.args.store_dir\n\t\t\t\t\tif not os.path.isdir(store_dir):\n\t\t\t\t\t\tos.makedirs(store_dir, exist_ok=True)\n\t\t\t\t\tnoise = new_perturbed - original\n\t\t\t\t\tnp.save(store_dir+\"orig.npy\", original.astype(np.float16))\n\t\t\t\t\tnp.save(store_dir+\"adv.npy\", new_perturbed.astype(np.float16))\n\t\t\t\t\tnp.save(store_dir+\"noise.npy\", noise.astype(np.float16))\n\t\t\t\t\tnp.save(store_dir+\"query_dist_smooth.npy\", query_dist_smooth.astype(np.float16))\n\t\t\t\t\tarray = np.array([[iteration],\n\t\t\t\t\t\t\t\t\t\t[query]])\n\t\t\t\t\tnp.save(store_dir+\"iteration_queries.npy\", array.astype(int))\n\t\t\t\t\tnp.save(store_dir+\"hist_adv.npy\", hist_adv.astype(np.float16))\n\t\t\t\t\tbreak \n\n\t\t\t\t# Create 1 x 2 array with distance and query number\n\t\t\t\t# Store each array as vals.npy in store directory\n\n\t\t\titeration += 1\n\n\t\t\t\t# Add formatting for the different names, also add a different type of save file\n\t\t\t\t# specifically storing a graph that represents iterations vs distance\n\t\t\t\t# Do we apply a regression model on the data points, or should we do that after?\n\n\n\t\t\t# ===========================================================\n\t\t\t# Update step sizes\n\t\t\t# ===========================================================\n\t\t\tself.update_step_sizes()\n\n\t\t\t# ===========================================================\n\t\t\t# Log the step\n\t\t\t# ===========================================================\n\t\t\t# self.log_step(iteration, distance, message)\n\n\t\treturn perturbed, query \n\n\t# Can be uncommented to print values of step size and source step for each iteration,\n\t# we removed it as to print less lines while the boundary attack was running\n\n\t# def log_step(self, iteration, distance, message=\"\", always=False):\n\t# \tif not always and iteration % self.log_every_n_steps != 0:\n\t# \t\treturn\n\t# \tprint(\n\t# \t\t\"Step {}: {:.5e}, stepsizes = {:.1e}/{:.1e}: {}\".format(\n\t# \t\t\titeration, distance, self.spherical_step, self.source_step, message\n\t# \t\t)\n\t# \t)\n" ]
[ [ "matplotlib.pyplot.legend", "numpy.sqrt", "matplotlib.pyplot.figure", "numpy.linalg.norm", "numpy.ones", "numpy.std", "numpy.size", "numpy.random.randn", "numpy.mean", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.close", "numpy.append", "matplotlib.pyplot.xlabel", "numpy.array", "numpy.zeros", "numpy.empty", "numpy.vdot" ] ]
himanshur-dev/ribopy
[ "78846e4140a7aa7b4dc995f39606577efaaf0831" ]
[ "tests/other/aggregate_by_length_test.py" ]
[ "# -*- coding: utf-8 -*-\nimport unittest\nfrom unittest import mock\nfrom unittest.mock import patch\nimport os\nfrom io import StringIO, BytesIO\n\nimport numpy as np\nimport h5py\n\nfrom ribopy import create\nfrom ribopy.core.coverage import find_coverage\nfrom ribopy.core.get_gadgets import get_reference_names,\\\n get_reference_lengths,\\\n get_region_boundaries\nfrom ribopy.settings import *\nfrom ribopy.core.aggregate_by_length import *\n\nimport sys\ntest_dir = os.path.dirname(os.path.realpath(__file__))\nsys.path.append(test_dir)\n\nfrom multilength_test_data import *\nfrom ribopy.core import create_experiment\n\n###########################################\n\nNPROCESS = 4\n\nclass TestCreate(unittest.TestCase):\n def setUp(self):\n\n self.len_file = StringIO(TRANSCRIPT_LENGTHS)\n self.annotation_file = StringIO(TRANSCRIPT_ANNOTATION)\n self.alignment_file = StringIO(READ_SET_1)\n\n self.handle = h5py.File(BytesIO(), \"w\")\n\n create.create_ribo(self.handle,\n experiment_name = \"merzifon\",\n alignment_file = self.alignment_file,\n reference_name = \"hg38\",\n lengths_file = self.len_file,\n annotation_file = self.annotation_file,\n metagene_radius = METAGENE_RADIUS,\n left_span = LEFT_SPAN, right_span = RIGHT_SPAN,\n length_min = 2, length_max = 5,\n tmp_file_prefix = \"\")\n\n def tearDown(self):\n self.handle.close()\n\n\n ### T E S T S U M S ################################\n\n def test_aggregate_region_sum(self):\n aggregate_2_3_region = aggregate_region_counts(\n self.handle, range_lower = 2, range_upper =3,\n sum_values = True )\n expected_reg_count_len_2_3 = expected_counts_length_2 + \\\n expected_counts_length_3\n\n # print(aggregate_2_3_region, \"\\n-----\\n\" , expected_reg_count_len_2_3 )\n self.assertTrue( np.all(aggregate_2_3_region ==\\\n expected_reg_count_len_2_3) )\n\n expected_reg_count_len_2_3_4_5 = expected_counts_length_2 + \\\n expected_counts_length_3 + \\\n expected_counts_length_4 + \\\n expected_counts_length_5\n\n aggregate_2_5_region = aggregate_region_counts(\n self.handle, range_lower = 2, range_upper =5,\n sum_values = True )\n\n self.assertTrue( np.all(expected_reg_count_len_2_3_4_5 ==\\\n aggregate_2_5_region) )\n\n aggregate_2_region = aggregate_region_counts(\n self.handle, range_lower = 2, range_upper =2,\n sum_values = True,\n experiment_list = [\"merzifon\", \"merzifon\"] )\n self.assertTrue( np.all(aggregate_2_region ==\\\n expected_counts_length_2) )\n\n\n def test_aggregate_start_site_sum(self):\n aggregate_2_3_start = aggregate_start_site(\n self.handle, range_lower = 2, range_upper =3,\n sum_values = True )\n expected_2_3_start = ACTUAL_START_SITE_COVERAGE_length_2 + \\\n ACTUAL_START_SITE_COVERAGE_length_3\n\n self.assertTrue( np.all(aggregate_2_3_start == expected_2_3_start) )\n\n aggregate_2_start = aggregate_start_site(\n self.handle, range_lower = 2, range_upper =2,\n sum_values = True )\n\n self.assertTrue( np.all(aggregate_2_start ==\\\n ACTUAL_START_SITE_COVERAGE_length_2) )\n\n aggregate_2_to_5_start = aggregate_start_site(\n self.handle, range_lower = 2, range_upper =5,\n sum_values = True )\n\n expected_2_to_5_start = ACTUAL_START_SITE_COVERAGE_length_2 + \\\n ACTUAL_START_SITE_COVERAGE_length_3 + \\\n ACTUAL_START_SITE_COVERAGE_length_4 + \\\n ACTUAL_START_SITE_COVERAGE_length_5\n\n self.assertTrue( np.all(aggregate_2_to_5_start == \\\n expected_2_to_5_start) )\n\n\n def test_aggregate_stop_site_sum(self):\n aggregate_2_3_stop = aggregate_stop_site(\n self.handle, range_lower = 2, range_upper =3,\n sum_values = True )\n\n expected_2_3_stop = ACTUAL_STOP_SITE_COVERAGE_length_2 + \\\n ACTUAL_STOP_SITE_COVERAGE_length_3\n\n self.assertTrue( np.all(aggregate_2_3_stop == expected_2_3_stop) )\n\n\n ### Test GROUPINGS #######################\n def test_aggregate_region_group(self):\n aggregate_2_3_region = aggregate_region_counts(\n self.handle, range_lower = 2, range_upper =3,\n sum_values = False )\n\n length_col = np.repeat( range(2,3+1), len( expected_counts_length_2 ) )\n length_col = np.array( length_col, ndmin=2 )\n\n combined_counts = np.concatenate( (expected_counts_length_2,\n expected_counts_length_3) )\n\n expected_array = np.concatenate( (length_col.T, combined_counts), axis = 1 )\n\n array_comparison = (expected_array == aggregate_2_3_region)\n self.assertTrue( np.all(array_comparison) )\n\n def test_aggregate_start_site_group(self):\n aggregate_4_5_start = aggregate_start_site(\n self.handle, range_lower = 4, range_upper =5,\n sum_values = False )\n\n length_col = np.repeat( range(4,5+1),\n len( ACTUAL_START_SITE_COVERAGE_length_4 ) )\n length_col = np.array( length_col, ndmin=2 )\n\n combined_counts = np.concatenate( (ACTUAL_START_SITE_COVERAGE_length_4,\n ACTUAL_START_SITE_COVERAGE_length_5) )\n\n expected_array = np.concatenate( (length_col.T, combined_counts), axis = 1 )\n array_comparison = (expected_array == aggregate_4_5_start)\n self.assertTrue( np.all(array_comparison) )\n\n def test_aggregate_stop_site_group(self):\n aggregate_2_5_stop = aggregate_stop_site(\n self.handle, range_lower = 2, range_upper =5,\n sum_values = False )\n\n length_col = np.repeat( range(2,5+1), len( ACTUAL_STOP_SITE_COVERAGE_length_4 ) )\n length_col = np.array( length_col, ndmin=2 )\n\n combined_counts = np.concatenate( (ACTUAL_STOP_SITE_COVERAGE_length_2,\n ACTUAL_STOP_SITE_COVERAGE_length_3,\n ACTUAL_STOP_SITE_COVERAGE_length_4,\n ACTUAL_STOP_SITE_COVERAGE_length_5) )\n\n expected_array = np.concatenate( (length_col.T, combined_counts), axis = 1 )\n array_comparison = (expected_array == aggregate_2_5_stop)\n self.assertTrue( np.all(array_comparison) )\n\n\n\nif __name__ == '__main__':\n\n unittest.main()\n" ]
[ [ "numpy.concatenate", "numpy.all", "numpy.array" ] ]
bnavigator/distributed
[ "5ea74cd7ec3cf5b90c5e6d5a31fb7dc3888ea242" ]
[ "distributed/dashboard/utils.py" ]
[ "from distutils.version import LooseVersion\nfrom numbers import Number\n\nimport bokeh\nfrom bokeh.io import curdoc\nfrom tlz import partition\nfrom tlz.curried import first\n\ntry:\n import numpy as np\nexcept ImportError:\n np = False\n\n\nBOKEH_VERSION = LooseVersion(bokeh.__version__)\n\n\nPROFILING = False\n\n\nif BOKEH_VERSION >= \"1.0.0\":\n # This decorator is only available in bokeh >= 1.0.0, and doesn't work for\n # callbacks in Python 2, since the signature introspection won't line up.\n from bokeh.core.properties import without_property_validation\nelse:\n\n def without_property_validation(f):\n return f\n\n\ndef parse_args(args):\n options = dict(partition(2, args))\n for k, v in options.items():\n if v.isdigit():\n options[k] = int(v)\n\n return options\n\n\ndef transpose(lod):\n keys = list(lod[0].keys())\n return {k: [d[k] for d in lod] for k in keys}\n\n\n@without_property_validation\ndef update(source, data):\n \"\"\"Update source with data\n\n This checks a few things first\n\n 1. If the data is the same, then don't update\n 2. If numpy is available and the data is numeric, then convert to numpy\n arrays\n 3. If profiling then perform the update in another callback\n \"\"\"\n if not np or not any(isinstance(v, np.ndarray) for v in source.data.values()):\n if source.data == data:\n return\n if np and len(data[first(data)]) > 10:\n d = {}\n for k, v in data.items():\n if type(v) is not np.ndarray and isinstance(v[0], Number):\n d[k] = np.array(v)\n else:\n d[k] = v\n else:\n d = data\n\n if PROFILING:\n curdoc().add_next_tick_callback(lambda: source.data.update(d))\n else:\n source.data.update(d)\n" ]
[ [ "numpy.array" ] ]
Louis-Mozart/Louis-Mozart.github.io
[ "ffc11437fb47fa4007b47ef0bf82388de132cca1" ]
[ "louismozart_teyou_BDA1.py" ]
[ "import pandas as pd\nfrom datetime import datetime\nfrom multiprocessing import Pool\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nfrom pathlib import Path\n\n\"\"\"\nINCORRECT CODES LINES 29,43,48,147,150,163,187,226\n\"\"\"\n\n# ==================================\n# INSTRUCTIONS\n# ==================================\n# 1. Replace all places where there is 'YOUR CODE HERE\" with your own code\n# 2. You can test and check the code in Jupyter Notebook but the submission should be a Python file\n# 3. Please name your Python script like this: FirstName_MiddleName_LastName\n\ndef get_date_range_by_chunking(large_csv):\n \"\"\"\n In this function, the idea is to use pandas chunk feature.\n :param large_csv: Full path to activity_log_raw.csv\n :return:\n \"\"\"\n # ======================================\n # EXPLORE THE DATA\n # ======================================\n # Read the first 100,000 rows in the dataset\n df_first_100k = pd.read_csv(\"activity_log_raw.csv\",nrows=100.000)\n print(df_first_100k.head())\n # Identify the time column in the dataset\n str_time_col = 'ACTIVITY_TIME'\n\n # ============================================================\n # FIND THE FIRST [EARLIEST] AND LAST DATE IN THE WHOLE DATASET\n # BY USING CHUNKING\n # =============================================================\n # set chunk size to some number. You can play around with the chunk size to see its effect\n chunksize = 500000\n\n # declare a list to hold the dates\n dates = []\n with pd.read_csv(\"activity_log_raw.csv\", nrows=100 ,chunksize=chunksize) as reader:\n for chunk in reader:\n # convert the string to Python datetime object\n # add a new column to hold this datetime object. For instance,\n # you can call it \"activ_time\"\n #time_col = data['ACTIVITY_TIME']\n chunk['str_time_col']=chunk['ACTIVITY_TIME']\n chunk['time_col'] = chunk['str_time_col'].apply(lambda x: pd.to_datetime(x[:9]))\n chunk.sort_values(by='time_col', inplace=True)\n top_date = chunk.iloc[0]['time_col']\n # Add the top_date to the list\n dates.append(top_date)\n chunk.sort_values(by='time_col', ascending=False, inplace=True)\n bottom_date = chunk.iloc[0]['time_col']\n # Add the bottom_date to the list\n dates.append(bottom_date)\n\n\n # Find the earliest and last date by sorting the dates list we created above\n sorted_dates = sorted(dates)\n first = sorted_dates[0]\n last = sorted_dates[-1]\n print(\"First date is {} and the last date is {}\".format(first, last))\n\n return first, last\n\n\ndef quadratic_func(x, a):\n \"\"\"\n Define the quadratic function like this: y = 2x^2 + a -1\n (read as y is equal to 2 x squared plus a minus 1)\n :param x:\n :return:\n \"\"\"\n y = 2*x**2+a-1\n return y\n\n\ndef run_the_quad_func_without_multiprocessing(list_x, list_y):\n \"\"\"\n Run the quadratic function on a huge list of X and Ys without using parallelism\n :param list_x: List of xs\n :param list_y: List of ys\n :return:\n \"\"\"\n results = [quadratic_func(x, y) for x, y in zip(list_x, list_y)]\n return results\n\n\ndef run_the_quad_func_with_multiprocessing(list_x, list_y, num_processors):\n \"\"\"\n Run the quadratic function with multiprocessing\n :param list_x: List of xs\n :param list_y: List of xs\n :param num_processors: Number of processors to use\n :return:\n \"\"\"\n # Use the Pool method to initiate processors with number\n # of processors set to num_processors\n processors = Pool(4)\n params = [i for i in zip(list_x, list_y)]\n\n # Use the starmap method for Pool to run the processes\n # Like this: Pool.starmap(func_name, params)\n results = processors.starmap(quadratic_func, params)\n processors.close()\n return results\n\n\ndef multiprocessing_vs_sequential_quadratic(list_len, out_plot, out_csv):\n \"\"\"\n Compare how\n :param list_len:\n :return:\n \"\"\"\n\n data = []\n for i in range(1, list_len):\n list_length = 10 ** i\n\n # Create lists using the range() function\n # and provided list length param\n x = [i for i in range(list_length)]\n y = [i for i in range(list_length)]\n\n start_time = datetime.now()\n run_the_quad_func_without_multiprocessing(x, y)\n end_time = datetime.now()\n time_taken_seq = (end_time - start_time).total_seconds()\n data.append({'ListLen': list_length, 'Type' : 'Parallel', 'TimeTaken': time_taken_seq})\n\n start_time = datetime.now()\n # Call the function run_the_quad_func_with_multiprocessing below\n run_the_quad_func_with_multiprocessing(x, y, 4)\n end_time = datetime.now()\n time_taken_mult = (end_time - start_time).total_seconds()\n data.append({'ListLen': list_length, 'Type' : 'Sequential', 'TimeTaken': time_taken_mult})\n\n # Create a data frame using the data variable defined above\n df = pd.DataFrame(data)\n plt.figure(figsize=(12, 8))\n sns.lineplot(data=df, x='ListLen', y='TimeTaken', hue='Type')\n\n # Use plt.savefig() to save the plot\n plt.savefig('Multi')\n\n # Also save the pandas dataframe defined above\n df.to_csv(\"dataframe\")\n\ndef get_num_uniq_users(csv_file, userid_col):\n \"\"\"\n A Helper function to help get the number of unique users\n :param csv_file: path to CSV file\n :param userid_col: Column for user ID\n :return:\n \"\"\"\n # Read the CSV file using pandas\n df = pd.read_csv(csv_file)\n\n # Use the nunique() method to get number of unique users\n num = len(np.unique(df[userid_col]))\n\n return num\n\n\ndef get_tot_uniq_users_parallel(path_to_csv, num_processors):\n \"\"\"\n\n :param path_to_csv:\n :return:\n \"\"\"\n # ==================================================\n # GET LIST OF ALL CSV FILES AND PUT IN A LIST\n # ===================================================\n # convert the string URL for path to a Path object for easier interaction\n start = datetime.now()\n path_to_csv = Path(path_to_csv)\n list_csv = [f for f in path_to_csv.iterdir() if f.suffix == '.csv']\n\n\n # ======================================================\n # USE MULTIPROCESSING TO GET UNIQUE USERS FROM ALL CSV'S\n # ======================================================\n # Create processors using Pool and num_processors\n processors = Pool(4)\n\n # Prepare parameters for the get_num_uniq_users() function\n user_id_col = ['user_id']*len(list_csv) # List containing parameters for the user_id column\n params = [i for i in zip(list_csv, user_id_col)] # combine the two lists\n # Run the function in parallel\n results = processors.starmap(get_num_uniq_users, params)\n processors.close()\n\n # combine results to get the total\n tot_users = sum(results)\n end = datetime.now()\n time_taken = round((end - start).total_seconds(), 2)\n print('Total unique users: {:,} in {} seconds'.format(tot_users, time_taken))\n\n return tot_users\n\ndef get_tot_uniq_users_seq(path_to_csv, userid_col):\n \"\"\"\n\n :param path_to_csv:\n :return:\n \"\"\"\n # ==================================================\n # GET LIST OF ALL CSV FILES AND PUT IN A LIST\n # ===================================================\n # convert the string URL for path to a Path object for easier interaction\n start = datetime.now()\n path_to_csv = Path(path_to_csv)\n list_csv = [f for f in path_to_csv.iterdir() if f.suffix == '.csv']\n\n tot_users = 0\n for csv in list_csv:\n # Read CSV into pandas dataframe\n df = pd.read_csv(csv)\n # Get unique number of users using nunique() and the column for user_id\n uniq = np.unique(df['userid_col'])\n\n # Increment the total number of users\n tot_users += len(uniq)\n\n end = datetime.now()\n time_taken = round((end - start).total_seconds(), 2)\n print('Total unique users: {:,} in {} seconds'.format(tot_users, time_taken))\n\n return tot_users\n\n\n\nif __name__ == '__main__':\n # Question-1: Pandas chunks\n file = \"home/mozart/Desktop/big data analytic/activity_log_raw.csv\"#->\"activity_log_raw.csv\"\n get_date_range_by_chunking(file)\n\n # Question-2: CPU bound parallelization\n out_plot = \"/home/mozart/Desktop/big data analytic\"\n out_csv = \"/home/mozart/Desktop/big data analytic\"\n multiprocessing_vs_sequential_quadratic(9, out_plot, out_csv)\n\n # =====================================================\n # QUESTION-3: CPU BOUND PARALLELIZATION WITH PANDAS\n # =====================================================\n fpath = \"/home/mozart/Desktop/big data analytic\"\n get_tot_uniq_users_parallel(fpath, 12)\n get_tot_uniq_users_seq(fpath, 'user_id')" ]
[ [ "pandas.read_csv", "pandas.to_datetime", "matplotlib.pyplot.savefig", "pandas.DataFrame", "matplotlib.pyplot.figure" ] ]
shtoneyan/basenji
[ "b220dc72069c3d8c250f36cb09799b337daac2fe" ]
[ "bin/basenji_bench_classify.py" ]
[ "#!/usr/bin/env python\nfrom optparse import OptionParser\nimport joblib\nimport os\nimport pdb\n\nimport h5py\nimport numpy as np\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import roc_auc_score, roc_curve\nfrom sklearn.model_selection import KFold\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom basenji.dna_io import dna_1hot\n\n'''\nbasenji_bench_classify.py\n'''\n\n################################################################################\n# main\n################################################################################\ndef main():\n usage = 'usage: %prog [options] <sadp_file> <sadn_file>'\n parser = OptionParser(usage)\n parser.add_option('-a', dest='abs_value',\n default=False, action='store_true')\n parser.add_option('-i', dest='iterations',\n default=1, type='int',\n help='Cross-validation iterations [Default: %default]')\n parser.add_option('-l', dest='log',\n default=False, action='store_true')\n parser.add_option('-m', dest='model_pkl',\n help='Dimension reduction model')\n parser.add_option('-o', dest='out_dir',\n default='class_out')\n parser.add_option('-p', dest='parallel_threads',\n default=1, type='int',\n help='Parallel threads passed to scikit-learn n_jobs [Default: %default]')\n parser.add_option('-r', dest='random_seed',\n default=None, type='int')\n parser.add_option('-s', dest='save_preds',\n default=False, action='store_true',\n help='Save predictions across iterations [Default: %default]')\n parser.add_option('--stat', dest='sad_stat',\n default='SAD',\n help='HDF5 key stat to consider. [Default: %default]')\n (options,args) = parser.parse_args()\n\n if len(args) != 2:\n parser.error('Must provide positive and negative variant predictions.')\n else:\n sadp_file = args[0]\n sadn_file = args[1]\n\n np.random.seed(options.random_seed)\n\n if not os.path.isdir(options.out_dir):\n os.mkdir(options.out_dir)\n\n # read dimension reduction model\n if options.model_pkl:\n model = joblib.load(options.model_pkl)\n\n # read positive/negative variants\n Xp = read_sad(sadp_file, options.sad_stat)\n Xn = read_sad(sadn_file, options.sad_stat)\n if options.log:\n Xp = np.arcsinh(Xp)\n Xn = np.arcsinh(Xn)\n if options.abs_value:\n Xp = np.abs(Xp)\n Xn = np.abs(Xn)\n if options.model_pkl:\n Xp = model.transform(Xp)\n Xn = model.transform(Xn)\n\n # combine\n X = np.concatenate([Xp, Xn], axis=0)\n y = np.array([True]*Xp.shape[0] + [False]*Xn.shape[0], dtype='bool')\n\n # train classifier\n if X.shape[1] == 1:\n aurocs, fpr_folds, tpr_folds, fpr_mean, tpr_mean = fold_roc(X, y, folds=8)\n else:\n # aurocs, fpr_folds, tpr_folds, fpr_full, tpr_full = ridge_roc(X, y, folds=8, alpha=10000)\n aurocs, fpr_folds, tpr_folds, fpr_mean, tpr_mean, preds = randfor_roc(X, y, folds=8,\n iterations=options.iterations, random_state=options.random_seed,\n n_jobs=options.parallel_threads)\n\n # save preds\n if options.save_preds:\n np.save('%s/preds.npy' % options.out_dir, preds)\n\n # save full model\n model = randfor_full(X, y)\n joblib.dump(model, '%s/model.pkl' % options.out_dir)\n\n # save\n np.save('%s/aurocs.npy' % options.out_dir, aurocs)\n np.save('%s/fpr_mean.npy' % options.out_dir, fpr_mean)\n np.save('%s/tpr_mean.npy' % options.out_dir, tpr_mean)\n\n # print stats\n stats_out = open('%s/stats.txt' % options.out_dir, 'w')\n auroc_stdev = np.std(aurocs) / np.sqrt(len(aurocs))\n print('AUROC: %.4f (%.4f)' % (np.mean(aurocs), auroc_stdev), file=stats_out)\n stats_out.close()\n\n # plot roc\n plot_roc(fpr_folds, tpr_folds, options.out_dir)\n\n\ndef fold_roc(X, y, folds=8, random_state=44):\n \"\"\"Compute ROC for a single value, sans model.\"\"\"\n aurocs = []\n fpr_folds = []\n tpr_folds = []\n\n fpr_mean = np.linspace(0, 1, 256)\n tpr_mean = []\n\n # preds_full = np.zeros(y.shape)\n\n kf = KFold(n_splits=folds, shuffle=True, random_state=random_state)\n\n for train_index, test_index in kf.split(X):\n # predict test set (as is)\n preds = X[test_index,:]\n\n # save\n # preds_full[test_index] = preds.squeeze()\n\n # compute ROC curve\n fpr, tpr, _ = roc_curve(y[test_index], preds)\n fpr_folds.append(fpr)\n tpr_folds.append(tpr)\n\n interp_tpr = np.interp(fpr_mean, fpr, tpr)\n interp_tpr[0] = 0.0\n tpr_mean.append(interp_tpr)\n\n # compute AUROC\n aurocs.append(roc_auc_score(y[test_index], preds))\n\n # fpr_full, tpr_full, _ = roc_curve(y, preds_full)\n tpr_mean = np.array(tpr_mean).mean(axis=0)\n\n return np.array(aurocs), np.array(fpr_folds), np.array(tpr_folds), fpr_mean, tpr_mean\n\n\ndef plot_roc(fprs, tprs, out_dir):\n plt.figure(figsize=(4,4))\n\n for fi in range(len(fprs)):\n plt.plot(fprs[fi], tprs[fi], alpha=0.25)\n\n ax = plt.gca()\n ax.set_xlabel('False positive rate')\n ax.set_ylabel('True positive rate')\n\n sns.despine()\n plt.tight_layout()\n\n plt.savefig('%s/roc.pdf' % out_dir)\n plt.close()\n\n\ndef randfor_full(X, y, random_state=None, n_jobs=1):\n \"\"\"Compute a single random forest on the full data.\"\"\"\n model = RandomForestClassifier(n_estimators=100, max_features='log2', max_depth=64,\n min_samples_leaf=1, min_samples_split=2,\n random_state=random_state, n_jobs=n_jobs)\n model.fit(X, y)\n return model\n\n\ndef randfor_roc(X, y, folds=8, iterations=1, random_state=None, n_jobs=1):\n \"\"\"Compute ROC using a random forest.\"\"\"\n aurocs = []\n fpr_folds = []\n tpr_folds = []\n fpr_fulls = []\n tpr_fulls = []\n preds_return = []\n\n fpr_mean = np.linspace(0, 1, 256)\n tpr_mean = []\n\n for i in range(iterations):\n rs_iter = random_state + i\n preds_full = np.zeros(y.shape)\n\n kf = KFold(n_splits=folds, shuffle=True, random_state=rs_iter)\n\n for train_index, test_index in kf.split(X):\n # fit model\n if random_state is None:\n rs_rf = None\n else:\n rs_rf = rs_iter+test_index[0]\n model = RandomForestClassifier(n_estimators=100, max_features='log2', max_depth=64,\n min_samples_leaf=1, min_samples_split=2,\n random_state=rs_rf, n_jobs=n_jobs)\n model.fit(X[train_index,:], y[train_index])\n\n # predict test set\n preds = model.predict_proba(X[test_index,:])[:,1]\n\n # save\n preds_full[test_index] = preds.squeeze()\n\n # compute ROC curve\n fpr, tpr, _ = roc_curve(y[test_index], preds)\n fpr_folds.append(fpr)\n tpr_folds.append(tpr)\n\n interp_tpr = np.interp(fpr_mean, fpr, tpr)\n interp_tpr[0] = 0.0\n tpr_mean.append(interp_tpr)\n\n # compute AUROC\n aurocs.append(roc_auc_score(y[test_index], preds))\n\n fpr_full, tpr_full, _ = roc_curve(y, preds_full)\n fpr_fulls.append(fpr_full)\n tpr_fulls.append(tpr_full)\n preds_return.append(preds_full)\n\n aurocs = np.array(aurocs)\n tpr_mean = np.array(tpr_mean).mean(axis=0)\n preds_return = np.array(preds_return).T\n\n return aurocs, fpr_folds, tpr_folds, fpr_mean, tpr_mean, preds_return\n\n\ndef read_sad(sad_file, sad_stat):\n with h5py.File(sad_file, 'r') as sad_open:\n sad = np.array(sad_open[sad_stat], dtype='float64')\n return sad\n\n\n################################################################################\n# __main__\n################################################################################\nif __name__ == '__main__':\n main()\n" ]
[ [ "sklearn.metrics.roc_auc_score", "numpy.linspace", "sklearn.model_selection.KFold", "numpy.concatenate", "matplotlib.pyplot.plot", "numpy.mean", "matplotlib.pyplot.gca", "matplotlib.pyplot.tight_layout", "sklearn.ensemble.RandomForestClassifier", "numpy.save", "numpy.std", "numpy.interp", "matplotlib.pyplot.close", "numpy.zeros", "matplotlib.pyplot.figure", "matplotlib.pyplot.savefig", "sklearn.metrics.roc_curve", "numpy.array", "numpy.arcsinh", "numpy.abs", "numpy.random.seed" ] ]
dineshchitlangia/HadoopTools
[ "bab3d1173c6dfff65f88e47209eeaea31848fb4a" ]
[ "plot-jmx/plot-jmx.py" ]
[ "#!/usr/bin/env python3\n\nimport getopt\nimport glob\nimport json\nimport sys\nfrom collections import OrderedDict\nfrom enum import Enum\nfrom os.path import basename\n\nimport matplotlib.pyplot as plt\n\n\n# ---------------------------------------------------------------------------\n# Class definitions.\n#\nclass MetricType(Enum):\n COUNTER = 1\n RATE = 2\n\n\n# A class to Store information about a counter.\nclass Metric:\n def __init__(self, name, metric_type):\n self.name = name\n self.values = []\n self.values_for_plot = []\n self.absolute_epochs_ms = []\n self.metric_type = metric_type\n # Is the metric a sum of two or more.\n self.is_sum = '+' in name\n\n\n# ----------------------------------------------------------------------------\n# Methods\n#\ndef usage_and_die():\n print('''\n Usage: plot-jmx.py -i <input-files-pattern> [-o output-file.csv]\n <metric1:counter> [<metric2:rate>] ...\n\n Plot one or more metrics over time from multiple JMX files.\n\n It is assumed that each file is a single JMX dump and each filename\n should be the corresponding UNIX epoch.\n\n Each metric must be specified as a beanName:metricName:type, where\n type is either 'rate' or 'counter'.\n\n A metric spec can also be specified as\n 'beanName1:metricName1+beanName2:metricName2:type' in which case\n the counts will be summed.\n\n Examples:\n\n 1. Plot getFileInfo_num_ops vs. elapsed time.\n plot-jmx.py -i \"/inputfiles/*\"\n Hadoop:service=NameNode,name=RpcDetailedActivityForPort8020:getFileInfo_num_ops:counter\n\n 2. Plot sum of port 8020 RPC processing time and RPC queue time vs. elapsed time.\n plot-jmx.py -i \"/inputfiles/*\"\n Hadoop:service=NameNode,name=RpcActivityForPort8020:RpcQueueTime_avg_time+\\\nHadoop:service=NameNode,name=RpcActivityForPort8020:RpcProcessingTime_avg_time:rate\n ''')\n sys.exit()\n\n\ndef parse_args(input_args):\n \"\"\"\n Parse the supplied command-line arguments and return the input file glob\n and metric spec strings.\n\n :param input_args: Command line arguments.\n :return: A triplet, the first element of which is the input file glob,\n the second element is the output file name (may be empty),\n the third element is a list of metric spec strings.\n \"\"\"\n file_glob = \"\"\n output_file_name = \"\"\n try:\n opts, args = getopt.getopt(input_args, \"hi:o:\")\n except getopt.GetoptError as err:\n print(str(err))\n usage_and_die()\n\n for o, a in opts:\n if o == \"-h\":\n usage_and_die()\n elif o == \"-i\":\n file_glob = a\n elif o == \"-o\":\n output_file_name = a\n else:\n usage_and_die()\n if not file_glob:\n usage_and_die()\n\n return file_glob, output_file_name, args\n\n\ndef parse_metric_specs(spec_strings):\n \"\"\"\n Parse the metric specs provided as a list of strings and return an\n OrderedDict of Metric objects. Each metric spec string is specified\n as \"name:MetricType\".\n \"\"\"\n parsed_metrics = OrderedDict()\n for metric_spec in spec_strings:\n if ':' not in metric_spec:\n print(\"ERROR: Metric must be specified as 'beanName:metricName:type'\")\n sys.exit()\n name, metric_type = metric_spec.rsplit(\":\", 1)\n parsed_metrics[name] = Metric(name, MetricType[metric_type.upper()])\n return parsed_metrics\n\n\ndef get_raw_metrics_from_file(filename):\n \"\"\"\n Parse the given file as JSON and return a dictionary of the\n given metric names to their values.\n\n :param filename: JSON file name.\n :return: Dictionary of {beanName.metricName->Value}.\n \"\"\"\n values = {}\n with open(filename) as mf:\n try:\n j = json.load(mf)\n except json.decoder.JSONDecodeError:\n print(\"WARNING: Failed to decode {} as valid json\".format(filename))\n return values\n\n for bean in j['beans']:\n for m in bean.keys():\n values[bean['name'] + ':' + m] = bean[m]\n return values\n\n\ndef update_metrics_map(metrics_map, raw_metrics):\n \"\"\"\n Update a dictionary of Metric objects with metric values parsed from\n a single file. Handles compound Metrics which can be a sum of two or\n more metrics.\n\n :param metrics_map: Dictionary of Metric objects to be updated.\n :param raw_metrics: Dictionary of metrics parsed from a single JSON file.\n :return: True on success, False on failure.\n \"\"\"\n try:\n for metric in metrics_map.values():\n value = 0\n if not metric.is_sum:\n value = raw_metrics[metric.name]\n else:\n for component in metric.name.split(\"+\"):\n value += raw_metrics[component]\n metric.values.append(value)\n print(\"DEBUG: Saved metric value: {}={}\".format(metric.name, value))\n return True\n except KeyError:\n # Ignore the file if any metric was missing.\n return False\n\n\ndef generate_relative_epochs(epochs):\n relative = []\n for i in range(0, len(epochs)):\n relative.append(epochs[i] - epochs[0])\n return relative\n\n\ndef plot_graph(epochs, metrics_map):\n \"\"\"\n Generate a plot of the given metrics.\n\n :param epochs: A list of relative epochs.\n :param metrics_map: Dictionary of Metric objects to be plotted.\n \"\"\"\n if len(metrics_map) > 1:\n print(\"WARN: Not generating plot. Multi-line plots not supported yet\")\n return\n\n # colors = ['b', 'g', 'r', 'c', 'm', 'k', 'y']\n for s in metrics_map.values():\n points_to_plot = min(len(epochs), len(s.values_for_plot))\n print(\"Plotting {} values\".format(points_to_plot))\n plt.plot(epochs[:points_to_plot], s.values_for_plot[:points_to_plot],\n \"b-\", label=s.name)\n break\n\n plt.xlabel(\"Seconds elapsed\")\n plt.legend()\n plt.show()\n\n\ndef parse_metric_vals_and_epochs_from_files(file_glob, metrics_map):\n \"\"\"\n Parse JSON files described by the given glob.\n :param file_glob: Glob describing the input JSON files.\n :param metrics_map: Dictionary of Metrics objects to be updated.\n :return: A list of epochs, read from the file names.\n \"\"\"\n # Parse out the metric values from each file.\n # The file name should be the UNIX epoch.\n #\n epochs = []\n for jmx_file_name in glob.glob(file_glob):\n metrics_from_file = get_raw_metrics_from_file(jmx_file_name)\n if update_metrics_map(metrics_map, metrics_from_file):\n epochs.append(int(basename(jmx_file_name)))\n return epochs\n\n\ndef process_metrics_data(epochs, metrics_map, output_file_name):\n \"\"\"\n Convert counter metrics to rates, updating the Metrics.values_for_plot\n list for each metric with the rates. For rate metrics, this just copies\n the values as-is.\n\n :param epochs: A list of all the UNIX epochs, one corresponding to each\n raw metric value.\n :param metrics_map: A dictionary of Metrics objects with raw values.\n :param output_file_name: File to which the processed data will be written in\n csv format.\n :return:\n \"\"\"\n # Open the output file and write the header.\n if output_file_name:\n f = open(output_file_name, 'w')\n f.write(\"Seconds Elapsed, {}\\n\".format(\", \".join(metrics_map.keys())))\n\n for i, current_epoch in enumerate(epochs):\n values_for_csv = []\n for m in metrics_map.values():\n print(\"Iter={}, Value of {}={}\".format(\n i + 1, m.name, m.values[i]))\n # If it's a counter, then compute its rate.\n if m.metric_type == MetricType.COUNTER:\n curr_count = m.values[i]\n if i > 0:\n delta = max(curr_count - m.values[i - 1], 0)\n epoch_delta = current_epoch - epochs[i - 1]\n m.values_for_plot.append(delta / epoch_delta)\n values_for_csv.append(delta / epoch_delta)\n else:\n # The rate at the first epoch is unknowable, just set it\n # it to zero.\n m.values_for_plot.append(0)\n values_for_csv.append(0)\n else:\n # For a rate, there is nothing to do.\n m.values_for_plot.append(m.values[i])\n values_for_csv.append(m.values[i])\n\n if output_file_name:\n f.write(\"{},{}\\n\".format(\n current_epoch - epochs[0], \",\".join(map(str, values_for_csv))))\n\n if output_file_name:\n f.close()\n\n# ----------------------------------------------------------------------------\n#\n\n\ndef main():\n input_file_glob, output_file, metric_specs = parse_args(sys.argv[1:])\n metrics = parse_metric_specs(metric_specs)\n all_epochs = parse_metric_vals_and_epochs_from_files(input_file_glob, metrics)\n process_metrics_data(all_epochs, metrics, output_file)\n plot_graph(generate_relative_epochs(all_epochs), metrics)\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "matplotlib.pyplot.plot", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "matplotlib.pyplot.legend" ] ]
goncaloperes/bayesmark
[ "8c420e935718f0d6867153b781e58943ecaf2338" ]
[ "test/experiment_test.py" ]
[ "# Copyright (c) 2019 Uber Technologies, 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.\nimport inspect\nimport os.path\n\nimport numpy as np\nfrom hypothesis import assume, given, settings\nfrom hypothesis.strategies import floats, integers, sampled_from, text\nfrom hypothesis_gufunc.extra.xr import simple_datasets\nfrom hypothesis_gufunc.gufunc import gufunc_args\n\nimport bayesmark.experiment as exp\nimport bayesmark.random_search as rs\nfrom bayesmark import data, np_util\nfrom bayesmark.abstract_optimizer import AbstractOptimizer\nfrom bayesmark.builtin_opt.config import CONFIG\nfrom bayesmark.constants import DATA_LOADER_NAMES, ITER, METRICS, MODEL_NAMES, SUGGEST\nfrom bayesmark.sklearn_funcs import SklearnModel, TestFunction\nfrom hypothesis_util import seeds\nfrom util import space_configs\n\n\nclass RandomOptimizer(AbstractOptimizer):\n # Unclear what is best package to list for primary_import here.\n primary_import = \"bayesmark\"\n\n def __init__(self, api_config, random=np_util.random, flaky=False):\n AbstractOptimizer.__init__(self, api_config)\n self.random = random\n self.flaky = flaky\n\n def suggest(self, n_suggestions=1):\n if self.flaky:\n assert self.random.rand() <= 0.5\n x_guess = rs.suggest_dict([], [], self.api_config, n_suggestions=n_suggestions, random=self.random)\n return x_guess\n\n def observe(self, X, y):\n # Random search so don't do anything for observe\n if self.flaky:\n assert self.random.rand() <= 0.5\n\n\nclass OutOfBoundsOptimizer(AbstractOptimizer):\n def __init__(self, api_config, random=np_util.random):\n AbstractOptimizer.__init__(self, api_config)\n self.random = random\n self.param_list = sorted([kk for kk in api_config.keys() if api_config[kk][\"type\"] in (\"real\", \"int\")])\n\n def suggest(self, n_suggestions=1):\n x_guess = rs.suggest_dict([], [], self.api_config, n_suggestions=n_suggestions, random=self.random)\n\n ii = self.random.randint(0, n_suggestions)\n pp = self.random.choice(self.param_list)\n\n if self.api_config[pp][\"type\"] == \"real\":\n eps = self.random.rand()\n else:\n eps = self.random.randint(1, 10)\n\n if self.random.rand() <= 0.5:\n x_guess[ii][pp] = self.api_config[pp][\"range\"][0] - eps\n else:\n x_guess[ii][pp] = self.api_config[pp][\"range\"][1] + eps\n return x_guess\n\n def observe(self, X, y):\n pass\n\n\nclass FlakyProblem(TestFunction):\n def __init__(self, api_config, random):\n TestFunction.__init__(self)\n self.api_config = api_config\n self.random = random\n\n def evaluate(self, params):\n assert self.random.rand() <= 0.5\n return [0.0]\n\n\n@given(\n sampled_from(MODEL_NAMES),\n sampled_from(DATA_LOADER_NAMES),\n sampled_from(METRICS),\n integers(0, 5),\n integers(1, 3),\n seeds(),\n)\n@settings(max_examples=10, deadline=None)\ndef test_run_study(model_name, dataset, scorer, n_calls, n_suggestions, seed):\n prob_type = data.get_problem_type(dataset)\n assume(scorer in data.METRICS_LOOKUP[prob_type])\n\n function_instance = SklearnModel(model_name, dataset, scorer)\n optimizer = RandomOptimizer(function_instance.get_api_config(), random=np.random.RandomState(seed))\n optimizer.get_version()\n exp.run_study(optimizer, function_instance, n_calls, n_suggestions, n_obj=len(function_instance.objective_names))\n\n\n@given(\n sampled_from(MODEL_NAMES),\n sampled_from(DATA_LOADER_NAMES),\n sampled_from(METRICS),\n integers(1, 5),\n integers(1, 3),\n seeds(),\n)\ndef test_run_study_bounds_fail(model_name, dataset, scorer, n_calls, n_suggestions, seed):\n prob_type = data.get_problem_type(dataset)\n assume(scorer in data.METRICS_LOOKUP[prob_type])\n\n function_instance = SklearnModel(model_name, dataset, scorer)\n optimizer = OutOfBoundsOptimizer(function_instance.get_api_config(), random=np.random.RandomState(seed))\n optimizer.get_version()\n\n # pytest have some assert failed tools we could use instead, but this is ok for now\n bounds_fails = False\n try:\n exp.run_study(\n optimizer, function_instance, n_calls, n_suggestions, n_obj=len(function_instance.objective_names)\n )\n except Exception as e:\n bounds_fails = str(e) == \"Optimizer suggestion is out of range.\"\n assert bounds_fails\n\n\n@given(\n sampled_from(MODEL_NAMES),\n sampled_from(DATA_LOADER_NAMES),\n sampled_from(METRICS),\n integers(0, 5),\n integers(1, 3),\n seeds(),\n)\n@settings(max_examples=10, deadline=None)\ndef test_run_study_callback(model_name, dataset, scorer, n_calls, n_suggestions, seed):\n prob_type = data.get_problem_type(dataset)\n assume(scorer in data.METRICS_LOOKUP[prob_type])\n\n function_instance = SklearnModel(model_name, dataset, scorer)\n optimizer = RandomOptimizer(function_instance.get_api_config(), random=np.random.RandomState(seed))\n optimizer.get_version()\n n_obj = len(function_instance.objective_names)\n\n function_evals_cmin = np.zeros((n_calls, n_obj), dtype=float)\n iters_list = []\n\n def callback(f_min, iters):\n assert f_min.shape == (n_obj,)\n\n iters_list.append(iters)\n if iters == 0:\n assert np.all(f_min == np.inf)\n return\n\n function_evals_cmin[iters - 1, :] = f_min\n\n function_evals, _, _ = exp.run_study(\n optimizer, function_instance, n_calls, n_suggestions, n_obj=n_obj, callback=callback\n )\n\n assert iters_list == list(range(n_calls + 1))\n\n for ii in range(n_obj):\n for jj in range(n_calls):\n idx0, idx1 = np_util.argmin_2d(function_evals[: jj + 1, :, 0])\n assert function_evals_cmin[jj, ii] == function_evals[idx0, idx1, ii]\n\n\n@given(space_configs(allow_missing=True), integers(0, 5), integers(1, 3), seeds(), seeds())\n@settings(deadline=None)\ndef test_run_study_flaky(api_config, n_calls, n_suggestions, seed1, seed2):\n api_config, _, _, _ = api_config\n\n function_instance = FlakyProblem(api_config=api_config, random=np.random.RandomState(seed1))\n optimizer = RandomOptimizer(api_config, random=np.random.RandomState(seed2), flaky=True)\n optimizer.get_version()\n exp.run_study(optimizer, function_instance, n_calls, n_suggestions)\n\n\n@given(\n space_configs(allow_missing=True),\n sampled_from(MODEL_NAMES),\n sampled_from(DATA_LOADER_NAMES),\n sampled_from(METRICS),\n integers(0, 5),\n integers(1, 3),\n seeds(),\n)\n@settings(max_examples=10, deadline=None)\ndef test_run_sklearn_study(api_config, model_name, dataset, scorer, n_calls, n_suggestions, seed):\n prob_type = data.get_problem_type(dataset)\n assume(scorer in data.METRICS_LOOKUP[prob_type])\n\n random = np.random.RandomState(seed)\n exp.run_sklearn_study(RandomOptimizer, {\"random\": random}, model_name, dataset, scorer, n_calls, n_suggestions)\n\n\n@given(\n space_configs(allow_missing=True),\n sampled_from(MODEL_NAMES),\n sampled_from(DATA_LOADER_NAMES),\n sampled_from(METRICS),\n integers(0, 5),\n integers(1, 3),\n)\n@settings(max_examples=10, deadline=None)\ndef test_run_sklearn_study_real(api_config, model_name, dataset, scorer, n_calls, n_suggestions):\n prob_type = data.get_problem_type(dataset)\n assume(scorer in data.METRICS_LOOKUP[prob_type])\n\n # Should really do parametric test but for loop good enough\n for opt_name in sorted(CONFIG.keys()):\n opt_class = exp._get_opt_class(opt_name)\n # opt_root=None should work with built-in opt\n opt_kwargs = exp.load_optimizer_kwargs(opt_name, opt_root=None)\n\n exp.run_sklearn_study(opt_class, opt_kwargs, model_name, dataset, scorer, n_calls, n_suggestions)\n\n\n@given(sampled_from(MODEL_NAMES), sampled_from(DATA_LOADER_NAMES), sampled_from(METRICS))\n@settings(deadline=None)\ndef test_get_objective_signature(model_name, dataset, scorer):\n prob_type = data.get_problem_type(dataset)\n assume(scorer in data.METRICS_LOOKUP[prob_type])\n\n exp.get_objective_signature(model_name, dataset, scorer)\n\n\n@given(gufunc_args(\"(n,m,k),(k)->()\", dtype=[np.float_, str], elements=[floats(), text()], unique=[False, True]))\ndef test_build_eval_ds(args):\n function_evals, objective_names = args\n exp.build_eval_ds(function_evals, objective_names)\n\n\n@given(gufunc_args(\"(n),(n,m),(n)->()\", dtype=np.float_, elements=floats(min_value=0, max_value=1e6)))\ndef test_build_timing_ds(args):\n suggest_time, eval_time, observe_time = args\n exp.build_timing_ds(suggest_time, eval_time, observe_time)\n\n\n@given(\n simple_datasets(\n {\"int\": (ITER, SUGGEST), \"real\": (ITER, SUGGEST), \"binary\": (ITER, SUGGEST), \"cat\": (ITER, SUGGEST)},\n dtype={\"int\": int, \"real\": float, \"binary\": bool, \"cat\": str},\n min_side=1,\n )\n)\ndef test_build_suggest_ds(suggest_ds):\n ds_vars = list(suggest_ds)\n\n n_call, n_suggest = suggest_ds[ds_vars[0]].values.shape\n suggest_log = np.zeros((n_call, n_suggest), dtype=object)\n for ii in range(n_call):\n for jj in range(n_suggest):\n suggest_log[ii, jj] = {}\n for kk in ds_vars:\n suggest_log[ii, jj][kk] = suggest_ds[kk].sel({ITER: ii, SUGGEST: jj}, drop=True).values.item()\n suggest_log = suggest_log.tolist()\n\n suggest_ds_2 = exp.build_suggest_ds(suggest_log)\n\n assert suggest_ds.equals(suggest_ds_2)\n\n\ndef test_get_opt_class_module():\n # Should really do parametric test but for loop good enough\n for opt_name in sorted(CONFIG.keys()):\n opt_class = exp._get_opt_class(opt_name)\n\n fname = inspect.getfile(opt_class)\n fname = os.path.basename(fname)\n\n wrapper_file, _ = CONFIG[opt_name]\n\n assert fname == wrapper_file\n" ]
[ [ "numpy.all", "numpy.random.RandomState", "numpy.zeros" ] ]
giulatona/keras-io
[ "c9814a79182c1977ba28944174ad24dbcd517842", "c441a1f7dd7310c773125242e16769aef8ff65f6" ]
[ "examples/vision/grad_cam.py", "examples/structured_data/deep_neural_decision_forests.py" ]
[ "\"\"\"\nTitle: Grad-CAM class activation visualization\nAuthor: [fchollet](https://twitter.com/fchollet)\nDate created: 2020/04/26\nLast modified: 2020/05/14\nDescription: How to obtain a class activation heatmap for an image classification model.\n\"\"\"\n\"\"\"\nAdapted from Deep Learning with Python (2017).\n\n## Setup\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\n\n# Display\nfrom IPython.display import Image, display\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\n\n\n\"\"\"\n## Configurable parameters\n\nYou can change these to another model.\n\nTo get the values for `last_conv_layer_name` and `classifier_layer_names`, use\n `model.summary()` to see the names of all layers in the model.\n\"\"\"\n\nmodel_builder = keras.applications.xception.Xception\nimg_size = (299, 299)\npreprocess_input = keras.applications.xception.preprocess_input\ndecode_predictions = keras.applications.xception.decode_predictions\n\nlast_conv_layer_name = \"block14_sepconv2_act\"\nclassifier_layer_names = [\n \"avg_pool\",\n \"predictions\",\n]\n\n# The local path to our target image\nimg_path = keras.utils.get_file(\n \"african_elephant.jpg\", \"https://i.imgur.com/Bvro0YD.png\"\n)\n\ndisplay(Image(img_path))\n\n\n\"\"\"\n## The Grad-CAM algorithm\n\"\"\"\n\n\ndef get_img_array(img_path, size):\n # `img` is a PIL image of size 299x299\n img = keras.preprocessing.image.load_img(img_path, target_size=size)\n # `array` is a float32 Numpy array of shape (299, 299, 3)\n array = keras.preprocessing.image.img_to_array(img)\n # We add a dimension to transform our array into a \"batch\"\n # of size (1, 299, 299, 3)\n array = np.expand_dims(array, axis=0)\n return array\n\n\ndef make_gradcam_heatmap(\n img_array, model, last_conv_layer_name, classifier_layer_names\n):\n # First, we create a model that maps the input image to the activations\n # of the last conv layer\n last_conv_layer = model.get_layer(last_conv_layer_name)\n last_conv_layer_model = keras.Model(model.inputs, last_conv_layer.output)\n\n # Second, we create a model that maps the activations of the last conv\n # layer to the final class predictions\n classifier_input = keras.Input(shape=last_conv_layer.output.shape[1:])\n x = classifier_input\n for layer_name in classifier_layer_names:\n x = model.get_layer(layer_name)(x)\n classifier_model = keras.Model(classifier_input, x)\n\n # Then, we compute the gradient of the top predicted class for our input image\n # with respect to the activations of the last conv layer\n with tf.GradientTape() as tape:\n # Compute activations of the last conv layer and make the tape watch it\n last_conv_layer_output = last_conv_layer_model(img_array)\n tape.watch(last_conv_layer_output)\n # Compute class predictions\n preds = classifier_model(last_conv_layer_output)\n top_pred_index = tf.argmax(preds[0])\n top_class_channel = preds[:, top_pred_index]\n\n # This is the gradient of the top predicted class with regard to\n # the output feature map of the last conv layer\n grads = tape.gradient(top_class_channel, last_conv_layer_output)\n\n # This is a vector where each entry is the mean intensity of the gradient\n # over a specific feature map channel\n pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2))\n\n # We multiply each channel in the feature map array\n # by \"how important this channel is\" with regard to the top predicted class\n last_conv_layer_output = last_conv_layer_output.numpy()[0]\n pooled_grads = pooled_grads.numpy()\n for i in range(pooled_grads.shape[-1]):\n last_conv_layer_output[:, :, i] *= pooled_grads[i]\n\n # The channel-wise mean of the resulting feature map\n # is our heatmap of class activation\n heatmap = np.mean(last_conv_layer_output, axis=-1)\n\n # For visualization purpose, we will also normalize the heatmap between 0 & 1\n heatmap = np.maximum(heatmap, 0) / np.max(heatmap)\n return heatmap\n\n\n\"\"\"\n## Let's test-drive it\n\"\"\"\n\n# Prepare image\nimg_array = preprocess_input(get_img_array(img_path, size=img_size))\n\n# Make model\nmodel = model_builder(weights=\"imagenet\")\n\n# Print what the top predicted class is\npreds = model.predict(img_array)\nprint(\"Predicted:\", decode_predictions(preds, top=1)[0])\n\n# Generate class activation heatmap\nheatmap = make_gradcam_heatmap(\n img_array, model, last_conv_layer_name, classifier_layer_names\n)\n\n# Display heatmap\nplt.matshow(heatmap)\nplt.show()\n\n\n\"\"\"\n## Create a superimposed visualization\n\"\"\"\n\n# We load the original image\nimg = keras.preprocessing.image.load_img(img_path)\nimg = keras.preprocessing.image.img_to_array(img)\n\n# We rescale heatmap to a range 0-255\nheatmap = np.uint8(255 * heatmap)\n\n# We use jet colormap to colorize heatmap\njet = cm.get_cmap(\"jet\")\n\n# We use RGB values of the colormap\njet_colors = jet(np.arange(256))[:, :3]\njet_heatmap = jet_colors[heatmap]\n\n# We create an image with RGB colorized heatmap\njet_heatmap = keras.preprocessing.image.array_to_img(jet_heatmap)\njet_heatmap = jet_heatmap.resize((img.shape[1], img.shape[0]))\njet_heatmap = keras.preprocessing.image.img_to_array(jet_heatmap)\n\n# Superimpose the heatmap on original image\nsuperimposed_img = jet_heatmap * 0.4 + img\nsuperimposed_img = keras.preprocessing.image.array_to_img(superimposed_img)\n\n# Save the superimposed image\nsave_path = \"elephant_cam.jpg\"\nsuperimposed_img.save(save_path)\n\n# Display Grad CAM\ndisplay(Image(save_path))\n", "\"\"\"\nTitle: Classification with Neural Decision Forests\nAuthor: [Khalid Salama](https://www.linkedin.com/in/khalid-salama-24403144/)\nDate created: 2021/01/15\nLast modified: 2021/01/15\nDescription: How to train differentiable decision trees for end-to-end learning in deep neural networks.\n\"\"\"\n\n\"\"\"\n## Introduction\n\nThis example provides an implementation of the\n[Deep Neural Decision Forest](https://ieeexplore.ieee.org/document/7410529)\nmodel introduced by P. Kontschieder et al. for structured data classification.\nIt demonstrates how to build a stochastic and differentiable decision tree model,\ntrain it end-to-end, and unify decision trees with deep representation learning.\n\n## The dataset\n\nThis example uses the\n[United States Census Income Dataset](https://archive.ics.uci.edu/ml/datasets/census+income)\nprovided by the\n[UC Irvine Machine Learning Repository](https://archive.ics.uci.edu/ml/index.php).\nThe task is binary classification\nto predict whether a person is likely to be making over USD 50,000 a year.\n\nThe dataset includes 48,842 instances with 14 input features (such as age, work class, education, occupation, and so on): 5 numerical features\nand 9 categorical features.\n\"\"\"\n\n\"\"\"\n## Setup\n\"\"\"\n\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport math\n\n\"\"\"\n## Prepare the data\n\"\"\"\n\nCSV_HEADER = [\n \"age\",\n \"workclass\",\n \"fnlwgt\",\n \"education\",\n \"education_num\",\n \"marital_status\",\n \"occupation\",\n \"relationship\",\n \"race\",\n \"gender\",\n \"capital_gain\",\n \"capital_loss\",\n \"hours_per_week\",\n \"native_country\",\n \"income_bracket\",\n]\n\ntrain_data_url = (\n \"https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data\"\n)\ntrain_data = pd.read_csv(train_data_url, header=None, names=CSV_HEADER)\n\ntest_data_url = (\n \"https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.test\"\n)\ntest_data = pd.read_csv(test_data_url, header=None, names=CSV_HEADER)\n\nprint(f\"Train dataset shape: {train_data.shape}\")\nprint(f\"Test dataset shape: {test_data.shape}\")\n\n\"\"\"\nRemove the first record (because it is not a valid data example) and a trailing\n'dot' in the class labels.\n\"\"\"\n\ntest_data = test_data[1:]\ntest_data.income_bracket = test_data.income_bracket.apply(\n lambda value: value.replace(\".\", \"\")\n)\n\n\"\"\"\nWe store the training and test data splits locally as CSV files.\n\"\"\"\n\ntrain_data_file = \"train_data.csv\"\ntest_data_file = \"test_data.csv\"\n\ntrain_data.to_csv(train_data_file, index=False, header=False)\ntest_data.to_csv(test_data_file, index=False, header=False)\n\n\"\"\"\n## Define dataset metadata\n\nHere, we define the metadata of the dataset that will be useful for reading and parsing\nand encoding input features.\n\"\"\"\n\n# A list of the numerical feature names.\nNUMERIC_FEATURE_NAMES = [\n \"age\",\n \"education_num\",\n \"capital_gain\",\n \"capital_loss\",\n \"hours_per_week\",\n]\n# A dictionary of the categorical features and their vocabulary.\nCATEGORICAL_FEATURES_WITH_VOCABULARY = {\n \"workclass\": sorted(list(train_data[\"workclass\"].unique())),\n \"education\": sorted(list(train_data[\"education\"].unique())),\n \"marital_status\": sorted(list(train_data[\"marital_status\"].unique())),\n \"occupation\": sorted(list(train_data[\"occupation\"].unique())),\n \"relationship\": sorted(list(train_data[\"relationship\"].unique())),\n \"race\": sorted(list(train_data[\"race\"].unique())),\n \"gender\": sorted(list(train_data[\"gender\"].unique())),\n \"native_country\": sorted(list(train_data[\"native_country\"].unique())),\n}\n# A list of the columns to ignore from the dataset.\nIGNORE_COLUMN_NAMES = [\"fnlwgt\"]\n# A list of the categorical feature names.\nCATEGORICAL_FEATURE_NAMES = list(CATEGORICAL_FEATURES_WITH_VOCABULARY.keys())\n# A list of all the input features.\nFEATURE_NAMES = NUMERIC_FEATURE_NAMES + CATEGORICAL_FEATURE_NAMES\n# A list of column default values for each feature.\nCOLUMN_DEFAULTS = [\n [0.0] if feature_name in NUMERIC_FEATURE_NAMES + IGNORE_COLUMN_NAMES else [\"NA\"]\n for feature_name in CSV_HEADER\n]\n# The name of the target feature.\nTARGET_FEATURE_NAME = \"income_bracket\"\n# A list of the labels of the target features.\nTARGET_LABELS = [\" <=50K\", \" >50K\"]\n\n\"\"\"\n## Create `tf.data.Dataset` objects for training and validation\n\nWe create an input function to read and parse the file, and convert features and labels\ninto a [`tf.data.Dataset`](https://www.tensorflow.org/guide/datasets)\nfor training and validation. We also preprocess the input by mapping the target label\nto an index.\n\"\"\"\n\nfrom tensorflow.keras.layers.experimental.preprocessing import StringLookup\n\ntarget_label_lookup = StringLookup(\n vocabulary=TARGET_LABELS, mask_token=None, num_oov_indices=0\n)\n\n\ndef get_dataset_from_csv(csv_file_path, shuffle=False, batch_size=128):\n dataset = tf.data.experimental.make_csv_dataset(\n csv_file_path,\n batch_size=batch_size,\n column_names=CSV_HEADER,\n column_defaults=COLUMN_DEFAULTS,\n label_name=TARGET_FEATURE_NAME,\n num_epochs=1,\n header=False,\n na_value=\"?\",\n shuffle=shuffle,\n ).map(lambda features, target: (features, target_label_lookup(target)))\n return dataset.cache()\n\n\n\"\"\"\n## Create model inputs\n\"\"\"\n\n\ndef create_model_inputs():\n inputs = {}\n for feature_name in FEATURE_NAMES:\n if feature_name in NUMERIC_FEATURE_NAMES:\n inputs[feature_name] = layers.Input(\n name=feature_name, shape=(), dtype=tf.float32\n )\n else:\n inputs[feature_name] = layers.Input(\n name=feature_name, shape=(), dtype=tf.string\n )\n return inputs\n\n\n\"\"\"\n## Encode input features\n\"\"\"\n\nfrom tensorflow.keras.layers.experimental.preprocessing import CategoryEncoding\nfrom tensorflow.keras.layers.experimental.preprocessing import StringLookup\n\n\ndef encode_inputs(inputs, use_embedding=False):\n encoded_features = []\n for feature_name in inputs:\n if feature_name in CATEGORICAL_FEATURE_NAMES:\n vocabulary = CATEGORICAL_FEATURES_WITH_VOCABULARY[feature_name]\n # Create a lookup to convert a string values to an integer indices.\n # Since we are not using a mask token, nor expecting any out of vocabulary\n # (oov) token, we set mask_token to None and num_oov_indices to 0.\n index = StringLookup(\n vocabulary=vocabulary, mask_token=None, num_oov_indices=0\n )\n # Convert the string input values into integer indices.\n value_index = index(inputs[feature_name])\n if use_embedding:\n embedding_dims = int(math.sqrt(len(vocabulary)))\n # Create an embedding layer with the specified dimensions.\n embedding_ecoder = layers.Embedding(\n input_dim=len(vocabulary), output_dim=embedding_dims\n )\n # Convert the index values to embedding representations.\n encoded_feature = embedding_ecoder(value_index)\n else:\n # Create a one-hot encoder.\n onehot_encoder = CategoryEncoding(output_mode=\"binary\")\n onehot_encoder.adapt(index(vocabulary))\n # Convert the index values to a one-hot representation.\n encoded_feature = onehot_encoder(value_index)\n else:\n # Use the numerical features as-is.\n encoded_feature = inputs[feature_name]\n if inputs[feature_name].shape[-1] is None:\n encoded_feature = tf.expand_dims(encoded_feature, -1)\n\n encoded_features.append(encoded_feature)\n\n encoded_features = layers.concatenate(encoded_features)\n return encoded_features\n\n\n\"\"\"\n## Deep Neural Decision Tree\n\nA neural decision tree model has two sets of weights to learn. The first set is `pi`,\nwhich represents the probability distribution of the classes in the tree leaves.\nThe second set is the weights of the routing layer `decision_fn`, which represents the probability\nof going to each leave. The forward pass of the model works as follows:\n\n1. The model expects input `features` as a single vector encoding all the features of an instance\nin the batch. This vector can be generated from a Convolution Neural Network (CNN) applied to images\nor dense transformations applied to structured data features.\n2. The model first applies a `used_features_mask` to randomly select a subset of input features to use.\n3. Then, the model computes the probabilities (`mu`) for the input instances to reach the tree leaves\nby iteratively performing a *stochastic* routing throughout the tree levels.\n4. Finally, the probabilities of reaching the leaves are combined by the class probabilities at the\nleaves to produce the final `outputs`.\n\"\"\"\n\n\nclass NeuralDecisionTree(keras.Model):\n def __init__(self, depth, num_features, used_features_rate, num_classes):\n super(NeuralDecisionTree, self).__init__()\n self.depth = depth\n self.num_leaves = 2 ** depth\n self.num_classes = num_classes\n\n # Create a mask for the randomly selected features.\n num_used_features = int(num_features * used_features_rate)\n one_hot = np.eye(num_features)\n sampled_feature_indicies = np.random.choice(\n np.arange(num_features), num_used_features, replace=False\n )\n self.used_features_mask = one_hot[sampled_feature_indicies]\n\n # Initialize the weights of the classes in leaves.\n self.pi = tf.Variable(\n initial_value=tf.random_normal_initializer()(\n shape=[self.num_leaves, self.num_classes]\n ),\n dtype=\"float32\",\n trainable=True,\n )\n\n # Initialize the stochastic routing layer.\n self.decision_fn = layers.Dense(\n units=self.num_leaves, activation=\"sigmoid\", name=\"decision\"\n )\n\n def call(self, features):\n batch_size = tf.shape(features)[0]\n\n # Apply the feature mask to the input features.\n features = tf.matmul(\n features, self.used_features_mask, transpose_b=True\n ) # [batch_size, num_used_features]\n # Compute the routing probabilities.\n decisions = tf.expand_dims(\n self.decision_fn(features), axis=2\n ) # [batch_size, num_leaves, 1]\n # Concatenate the routing probabilities with their complements.\n decisions = layers.concatenate(\n [decisions, 1 - decisions], axis=2\n ) # [batch_size, num_leaves, 2]\n\n mu = tf.ones([batch_size, 1, 1])\n\n begin_idx = 1\n end_idx = 2\n # Traverse the tree in breadth-first order.\n for level in range(self.depth):\n mu = tf.reshape(mu, [batch_size, -1, 1]) # [batch_size, 2 ** level, 1]\n mu = tf.tile(mu, (1, 1, 2)) # [batch_size, 2 ** level, 2]\n level_decisions = decisions[\n :, begin_idx:end_idx, :\n ] # [batch_size, 2 ** level, 2]\n mu = mu * level_decisions # [batch_size, 2**level, 2]\n begin_idx = end_idx\n end_idx = begin_idx + 2 ** (level + 1)\n\n mu = tf.reshape(mu, [batch_size, self.num_leaves]) # [batch_size, num_leaves]\n probabilities = keras.activations.softmax(self.pi) # [num_leaves, num_classes]\n outputs = tf.matmul(mu, probabilities) # [batch_size, num_classes]\n return outputs\n\n\n\"\"\"\n## Deep Neural Decision Forest\n\nThe neural decision forest model consists of a set of neural decision trees that are\ntrained simultaneously. The output of the forest model is the average outputs of its trees.\n\"\"\"\n\n\nclass NeuralDecisionForest(keras.Model):\n def __init__(self, num_trees, depth, num_features, used_features_rate, num_classes):\n super(NeuralDecisionForest, self).__init__()\n self.ensemble = []\n # Initialize the ensemble by adding NeuralDecisionTree instances.\n # Each tree will have its own randomly selected input features to use.\n for _ in range(num_trees):\n self.ensemble.append(\n NeuralDecisionTree(depth, num_features, used_features_rate, num_classes)\n )\n\n def call(self, inputs):\n # Initialize the outputs: a [batch_size, num_classes] matrix of zeros.\n batch_size = tf.shape(inputs)[0]\n outputs = tf.zeros([batch_size, num_classes])\n\n # Aggregate the outputs of trees in the ensemble.\n for tree in self.ensemble:\n outputs += tree(inputs)\n # Divide the outputs by the ensemble size to get the average.\n outputs /= len(self.ensemble)\n return outputs\n\n\n\"\"\"\nFinally, let's set up the code that will train and evaluate the model.\n\"\"\"\n\nlearning_rate = 0.01\nbatch_size = 265\nnum_epochs = 10\nhidden_units = [64, 64]\n\n\ndef run_experiment(model):\n\n model.compile(\n optimizer=keras.optimizers.Adam(learning_rate=learning_rate),\n loss=keras.losses.SparseCategoricalCrossentropy(),\n metrics=[keras.metrics.SparseCategoricalAccuracy()],\n )\n\n print(\"Start training the model...\")\n train_dataset = get_dataset_from_csv(\n train_data_file, shuffle=True, batch_size=batch_size\n )\n\n model.fit(train_dataset, epochs=num_epochs)\n print(\"Model training finished\")\n\n print(\"Evaluating the model on the test data...\")\n test_dataset = get_dataset_from_csv(test_data_file, batch_size=batch_size)\n\n _, accuracy = model.evaluate(test_dataset)\n print(f\"Test accuracy: {round(accuracy * 100, 2)}%\")\n\n\n\"\"\"\n## Experiment 1: train a decision tree model\n\nIn this experiment, we train a single neural decision tree model\nwhere we use all input features.\n\"\"\"\n\nnum_trees = 10\ndepth = 10\nused_features_rate = 1.0\nnum_classes = len(TARGET_LABELS)\n\n\ndef create_tree_model():\n inputs = create_model_inputs()\n features = encode_inputs(inputs, use_embedding=True)\n features = layers.BatchNormalization()(features)\n num_features = features.shape[1]\n\n tree = NeuralDecisionTree(depth, num_features, used_features_rate, num_classes)\n\n outputs = tree(features)\n model = keras.Model(inputs=inputs, outputs=outputs)\n return model\n\n\ntree_model = create_tree_model()\nrun_experiment(tree_model)\n\n\n\"\"\"\n## Experiment 2: train a forest model\n\nIn this experiment, we train a neural decision forest with `num_trees` trees\nwhere each tree uses randomly selected 50% of the input features. You can control the number\nof features to be used in each tree by setting the `used_features_rate` variable.\nIn addition, we set the depth to 5 instead of 10 compared to the previous experiment.\n\"\"\"\n\nnum_trees = 25\ndepth = 5\nused_features_rate = 0.5\n\n\ndef create_forest_model():\n inputs = create_model_inputs()\n features = encode_inputs(inputs, use_embedding=True)\n features = layers.BatchNormalization()(features)\n num_features = features.shape[1]\n\n forest_model = NeuralDecisionForest(\n num_trees, depth, num_features, used_features_rate, num_classes\n )\n\n outputs = forest_model(features)\n model = keras.Model(inputs=inputs, outputs=outputs)\n return model\n\n\nforest_model = create_forest_model()\n\nrun_experiment(forest_model)\n" ]
[ [ "numpy.expand_dims", "numpy.maximum", "tensorflow.keras.Input", "tensorflow.keras.preprocessing.image.load_img", "tensorflow.reduce_mean", "numpy.uint8", "tensorflow.keras.preprocessing.image.array_to_img", "numpy.arange", "tensorflow.keras.Model", "numpy.max", "tensorflow.keras.utils.get_file", "numpy.mean", "matplotlib.cm.get_cmap", "matplotlib.pyplot.matshow", "tensorflow.argmax", "matplotlib.pyplot.show", "tensorflow.keras.preprocessing.image.img_to_array", "tensorflow.GradientTape" ], [ "tensorflow.zeros", "tensorflow.keras.activations.softmax", "pandas.read_csv", "numpy.arange", "numpy.eye", "tensorflow.keras.layers.experimental.preprocessing.CategoryEncoding", "tensorflow.random_normal_initializer", "tensorflow.tile", "tensorflow.matmul", "tensorflow.keras.layers.experimental.preprocessing.StringLookup", "tensorflow.shape", "tensorflow.keras.layers.Dense", "tensorflow.keras.Model", "tensorflow.data.experimental.make_csv_dataset", "tensorflow.keras.losses.SparseCategoricalCrossentropy", "tensorflow.reshape", "tensorflow.keras.layers.concatenate", "tensorflow.ones", "tensorflow.expand_dims", "tensorflow.keras.layers.BatchNormalization", "tensorflow.keras.optimizers.Adam", "tensorflow.keras.metrics.SparseCategoricalAccuracy", "tensorflow.keras.layers.Input" ] ]
big-data-lab-team/spark
[ "340f5c587b16563ee8e55da89cd8f50926995815" ]
[ "experiments/notebooks/generate_figures.py" ]
[ "#!/usr/bin/env python3\nimport json\nfrom statistics import mean\nfrom matplotlib import pyplot as plt\nimport matplotlib.lines as mlines\nimport numpy as np\nimport sys\n\n\ndef load_json(fn):\n with open(fn, 'r') as f:\n return json.load(f)\n\n\nbatch = None #load_json(sys.argv[1])\npilots8 = None #load_json(sys.argv[2])\npilots16 = None #load_json(sys.argv[3])\n\nsystem = None #sys.argv[4]\n\n# NOTE: 3600 is 1hour in seconds - essentially, pipeline would not have passed if longer\nmax_queue = 3600\n\ndef makespan_dict():\n return { 'batch': [], '8pilots': [], '16pilots': [] }\n\n\ndef all_succeeded(i):\n return (batch[i]['success']\n and pilots8[i]['success']\n and pilots16[i]['success'])\n\n\ndedicated_1 = makespan_dict()\ndedicated_2 = makespan_dict()\ndedicated_3 = makespan_dict()\ndedicated_4 = makespan_dict()\n\nget_makespan = lambda x: (x['end_time'] - x['start_time']\n if x['success'] and x['end_time'] is not None\n else 0)\nis_same = lambda x, i: x in pilots8[i]['name'] and x in pilots16[i]['name']\n\ndef pilot_queueing_times(s):\n global max_queue\n return ([p['start_time'] - s['start_time']\n if p['start_time'] is not None else max_queue\n for p in s['sid']] \n if s['success'] and s['end_time'] is not None\n else [0] )\n\ndef fill_dictionaries(dedicated_1, dedicated_2, dedicated_3,\n dedicated_4, queue=False):\n global max_queue\n current_dict = None\n for i in range(len(batch)):\n if 'single' in batch[i]['name']:\n assert(is_same('1d', i))\n current_dict = dedicated_1\n elif 'double' in batch[i]['name']:\n assert(is_same('2d', i))\n current_dict = dedicated_2\n elif 'triple' in batch[i]['name']:\n assert(is_same('3d', i))\n current_dict = dedicated_3\n elif 'quadruple' in batch[i]['name']:\n assert(is_same('4d', i))\n current_dict = dedicated_4\n\n if queue:\n batch_pq = pilot_queueing_times(batch[i])\n pilot8_pq = pilot_queueing_times(pilots8[i])\n pilot16_pq = pilot_queueing_times(pilots16[i])\n current_dict['batch'] \\\n .append(mean(batch_pq))\n current_dict['8pilots'] \\\n .append(mean(pilot8_pq))\n current_dict['16pilots'] \\\n .append(mean(pilot16_pq))\n else:\n current_dict['batch'].append(get_makespan(batch[i]))\n current_dict['8pilots'].append(get_makespan(pilots8[i]))\n current_dict['16pilots'].append(get_makespan(pilots16[i]))\n\n\ndef repetition_fig(data, n_dedicated, system=\"Beluga\", save=None, ylim=None):\n n_groups = len(data['batch'])\n print(n_groups)\n\n fig, ax = plt.subplots()\n\n index = np.arange(n_groups)\n bar_width = 0.30\n opacity = 0.4\n\n rects1 = ax.bar(index, data['batch'], bar_width, alpha=opacity,\n color='r', label='batch')\n\n rects2 = ax.bar(index + bar_width, data['8pilots'], bar_width,\n alpha=opacity, color='b', label='8 pilots')\n\n rects3 = ax.bar(index + 2*bar_width, data['16pilots'], bar_width,\n alpha=opacity, color='green', label='16 pilots')\n\n\n ax.set_xlabel('Repetition')\n ax.set_ylabel('Makespan (s)')\n\n if ylim is not None:\n ax.set_ylim(0, ylim)\n elif system == \"beluga\":\n ax.set_ylim(0, 28000)\n else:\n ax.set_ylim(0, 28000) # 60000\n\n ax.set_xticks(index + bar_width / 2)\n ax.set_xticklabels((i + 1 for i in range(n_groups)))\n ax.legend()\n \n if save is None:\n ax.set_title('{0} - {1} dedicated'.format(system, n_dedicated))\n plt.show()\n else:\n plt.savefig(save)\n\n\ndef nworkers_fig(data, n_dedicated, system=\"Beluga\", save=None, ylim=None):\n n_groups = len(data['batch'])\n print(n_groups)\n\n fig, ax = plt.subplots()\n\n index = np.arange(n_groups)\n bar_width = 0.30\n opacity = 0.4\n\n pilot8_diff = [elem - data['8pilots'][i] for i,elem in enumerate(data['batch']) if elem != 0 or data['8pilots'][i] != 0]\n pilot16_diff = [elem - data['16pilots'][i] for i,elem in enumerate(data['batch']) if elem != 0 or data['16pilots'][i] != 0]\n rects2 = ax.bar(index, pilot8_diff, bar_width,\n alpha=opacity, color='b', label='batch - 8 pilots')\n\n rects3 = ax.bar(index + bar_width, pilot16_diff, bar_width,\n alpha=opacity, color='green', label='batch - 16 pilots')\n\n\n ax.set_xlabel('Repetition')\n ax.set_ylabel('Average number of worker difference (Batch - Pilot)')\n\n if ylim is not None:\n ax.set_ylim(0, ylim)\n elif system == \"beluga\":\n ax.set_ylim(-60, 50)\n else:\n ax.set_ylim(-60, 50) # 60000\n\n ax.set_xticks(index + bar_width / 2)\n ax.set_xticklabels((i + 1 for i in range(n_groups)))\n ax.legend()\n \n if save is None:\n ax.set_title('{0} - {1} dedicated'.format(system, n_dedicated))\n plt.show()\n else:\n plt.savefig(save)\n\n\ndef get_makespan_diff(d, num_pilots):\n b = d['batch']\n p = d['{}pilots'.format(num_pilots)]\n data = [b[i] - p[i] for i in range(len(b)) if b[i] != 0 and p[i] != 0]\n\n return data\n\n\ndef makespan_box(d1, d2, d3, d4, num_pilots, system=\"Beluga\", save=None):\n fig, ax = plt.subplots()\n data = [get_makespan_diff(d1, num_pilots),\n get_makespan_diff(d2, num_pilots),\n get_makespan_diff(d3, num_pilots),\n get_makespan_diff(d4, num_pilots)]\n\n pos = np.array(range(len(data))) + 1\n bp = ax.boxplot(data, sym='k+', positions=pos)\n\n ax.set_xlabel('# dedicated')\n ax.set_ylabel('Makespan (s)')\n plt.setp(bp['whiskers'], color='k', linestyle='-')\n plt.setp(bp['fliers'], markersize=3.0)\n\n if save is None:\n ax.set_title('{0} - {1} pilots'.format(system, num_pilots))\n plt.show()\n else:\n plt.savefig(save)\n\n\ndef basic_model(xy1, xy2, xy3, xy4, num_pilots, xlabel, ylabel, system=\"Beluga\", save=None): \n fig, ax = plt.subplots()\n execution_mode = \"Batch\" if type(num_pilots) == str and \"batch\" in num_pilots else \"Pilots\" \n \n ax.scatter(xy1[0], xy1[1], c=\"#6600cc\", alpha=0.5, label=\"{} 1 dedicated\".format(execution_mode)) \n ax.scatter(xy2[0], xy2[1], c=\"#ff0000\", alpha=0.5, label=\"{} 2 dedicated\".format(execution_mode))\n ax.scatter(xy3[0], xy3[1], c=\"#ffa500\", alpha=0.5, label=\"{} 3 dedicated\".format(execution_mode))\n ax.scatter(xy4[0], xy4[1], c=\"#008000\", alpha=0.5, label=\"{} 4 dedicated\".format(execution_mode))\n \n if len(xy1) > 2:\n ax.scatter(xy1[2], xy1[3], c=\"#290066\", marker=\"v\", alpha=0.5, label=\"Pilots 1 dedicated\")\n ax.scatter(xy2[2], xy2[3], c=\"#800033\", marker=\"v\", alpha=0.5, label=\"Pilots 2 dedicated\")\n ax.scatter(xy3[2], xy3[3], c=\"#ff6600\", marker=\"v\", alpha=0.5, label=\"Pilots 3 dedicated\")\n ax.scatter(xy4[2], xy4[3], c=\"#003300\", marker=\"v\", alpha=0.5, label=\"Pilots 4 dedicated\")\n if len(xy1) > 4:\n ax.scatter(xy1[4], xy1[5], c=\"#290066\", marker=\"+\", alpha=0.5, label=\"Pilots 1 dedicated\")\n ax.scatter(xy2[4], xy2[5], c=\"#800033\", marker=\"+\", alpha=0.5, label=\"Pilots 2 dedicated\")\n ax.scatter(xy3[4], xy3[5], c=\"#ff6600\", marker=\"+\", alpha=0.5, label=\"Pilots 3 dedicated\")\n ax.scatter(xy4[4], xy4[5], c=\"#003300\", marker=\"+\", alpha=0.5, label=\"Pilots 4 dedicated\")\n \n lgnd = []\n if len(xy1) > 2:\n pilot_symbol = mlines.Line2D([], [], color=\"black\", alpha=0.5, marker='v', linestyle='None',\n label='Pilots')\n lgnd.append(pilot_symbol)\n if len(xy1) > 4:\n pilot8_symbol = mlines.Line2D([], [], color=\"black\", alpha=0.5, marker='v', linestyle='None',\n label='8 Pilots')\n pilot16_symbol = mlines.Line2D([], [], color=\"black\", alpha=0.5, marker='+', linestyle='None',\n label='16 Pilots')\n lgnd = [ pilot8_symbol, pilot16_symbol ]\n\n model_symbol = mlines.Line2D([], [], color=\"gray\", alpha=0.5, linestyle='-',\n label='Batch model, non DL')\n batch_symbol = mlines.Line2D([], [], color=\"black\", alpha=0.5, marker='o', linestyle='None',\n label=execution_mode)\n d1_symbol = mlines.Line2D([], [], color=\"purple\", alpha=0.5, linestyle='-',\n label='Configuration 1')\n d2_symbol = mlines.Line2D([], [], color=\"red\", alpha=0.5, linestyle='-',\n label='Configuration 2')\n d3_symbol = mlines.Line2D([], [], color=\"orange\", alpha=0.5, linestyle='-',\n label='Configuration 3')\n d4_symbol = mlines.Line2D([], [], color=\"green\", alpha=0.5, linestyle='-',\n label='Configuration 4')\n\n lgnd.insert(0, batch_symbol)\n lgnd.extend([d1_symbol, d2_symbol, d3_symbol, d4_symbol, model_symbol])\n ax.legend(handles=lgnd)\n \n get_c = lambda x, y, z=False : (10*(x+20)*125)/y if z else 10*(x+20)*np.ceil(125/y)\n ceil_results = True\n n_workers = np.arange(5, 70)\n \n a = 0.2\n ax.plot(n_workers, get_c(45, n_workers, ceil_results),'-', c='purple', alpha=a)\n ax.plot(n_workers, get_c(90, n_workers, ceil_results), '-', c='red', alpha=a)\n ax.plot(n_workers, get_c(120, n_workers, ceil_results), '-', c='orange', alpha=a)\n ax.plot(n_workers, get_c(180, n_workers, ceil_results), '-', c='green', alpha=a)\n\n # gray line\n ax.plot(n_workers, get_c(45, n_workers, False),'-', c='gray', alpha=a)\n ax.plot(n_workers, get_c(90, n_workers, False), '-', c='gray', alpha=a)\n ax.plot(n_workers, get_c(120, n_workers, False), '-', c='gray', alpha=a)\n ax.plot(n_workers, get_c(180, n_workers, False), '-', c='gray', alpha=a)\n\n ax.set_xlabel(xlabel) \n ax.set_ylabel(ylabel) \n ax.set_ylim(0, 14000)#(0,61000)\n \n if save is None: \n ax.set_title('{0} - {1} pilots'.format(system, num_pilots)) \n plt.show() \n else: \n plt.savefig(save) \n\n\ndef queuing_time(bd, pd):\n return [bd[i]['sid'][0]['start_time'] -\n min([p['start_time'] for p in pd[i]['sid']\n if p['start_time'] is not None])\n for i in range(len(bd))\n if bd[i]['success'] and bd[i]['end_time'] is not None\n and pd[i]['success'] and pd[i]['end_time'] is not None]\n\n\ndef makespan_all(bd, pd):\n return [(bd[i]['end_time'] - bd[i]['start_time']) - \n (pd[i]['end_time'] - pd[i]['start_time'])\n for i in range(len(bd))\n if bd[i]['success'] and bd[i]['end_time'] is not None\n and pd[i]['success'] and pd[i]['end_time'] is not None]\n\n\ndef makespan_queue(num_pilot):\n pilot_data = None\n if num_pilot == 8:\n pilot_data = pilots8\n else:\n pilot_data = pilots16\n return (queuing_time(batch, pilot_data), makespan_all(batch, pilot_data))\n\n\ndef scatter_fig(x, y, num_pilots, xlabel, ylabel, system=\"Beluga\", save=None):\n fig, ax = plt.subplots()\n ax.scatter(x, y, alpha=0.5)\n\n b, m = np.polynomial.polynomial.polyfit(x, y, 1)\n ax.plot(np.asarray(x), b + m*np.asarray(x), 'k-')\n ax.set_xlabel(xlabel)\n ax.set_ylabel(ylabel)\n\n if save is None:\n ax.set_title('{0} - {1} pilots'.format(system, num_pilots))\n plt.show()\n else:\n plt.savefig(save)\n\n\ndef add_kv(d, k, v, w=True):\n\n if len(v) > 0 and type(v[0]) == dict:\n v = get_ld_keys(v, w)\n\n if k is not None:\n if k not in d:\n d[k] = set(v)\n else:\n d[k].update(v)\n\n\ndef get_ld_keys(l, w=False):\n temp = []\n if w:\n for el in l:\n temp.extend([\"{0}:{1}\".format(k, p) for k,v in el.items()\n for p in v])\n else:\n for el in l:\n temp.extend(el.keys())\n\n return temp\n\n\n\ndef get_pilot_info(job, t, w=False):\n if job['end_time'] is None:\n return []\n\n makespan_dict = {}\n \n makespan_dict[job['start_time']] = set()\n makespan_dict[job['end_time']] = set()\n\n true_t = None\n\n # First passage\n for sid in job['sid']:\n if sid['end_time'] is None:\n sid['end_time'] = job['end_time']\n\n sid[t] = sid[t] if type(sid[t]) == list else [sid[t]]\n\n start = (max(sid['start_time'], sid['job_start'])\n if 'job_start' in sid and sid['job_start'] is not None\n else sid['start_time'])\n\n add_kv(makespan_dict, start, sid[t], w)\n add_kv(makespan_dict, sid['end_time'], sid[t], w)\n\n # Second passage\n for sid in job['sid']:\n start = (max(sid['start_time'], sid['job_start'])\n if 'job_start' in sid and sid['job_start'] is not None\n else sid['start_time'])\n for k,v in makespan_dict.items():\n if (sid['end_time'] is not None and start is not None\n and k >= start and k <= sid['end_time']):\n if t == 'nodes':\n v.update(get_ld_keys(sid[t], w))\n else:\n v.update(sid[t])\n return [(k, len(v)) for k, v in sorted(makespan_dict.items())]\n\n\npilot_avgtype = lambda x: (sum([(x[i][1]*(x[i+1][0] - x[i][0])) \n for i in range(1, len(x) - 1)]) \n / (x[-1][0] - x[0][0]))\n\nget_pilot_avgnodes = lambda x,y: ((pilot_avgtype(get_pilot_info(x, 'nodes'))),\n ((y['end_time'] - y['start_time'])\n - (x['end_time'] - x['start_time'])),\n x['end_time'] - x['start_time'])\n\n\nget_batch_avgnodes = lambda x:(((len(set(x['sid'][0]['nodes'].keys()))\n * (x['sid'][0]['end_time']\n - x['sid'][0]['start_time']))\n / (x['end_time'] - x['start_time'])),\n x['end_time'] - x['start_time'])\n\n\nget_avgpilots = lambda x,y: ((pilot_avgtype(get_pilot_info(x, 'id'))),\n ((y['end_time'] - y['start_time'])\n - (x['end_time'] - x['start_time'])))\n\n\ndef get_ncpus(name):\n if 'single' in name or 'double' in name or 'triple' in name:\n return 16\n elif '8n1d' in name:\n return 2\n elif '16n1d' in name:\n return 1\n elif '8n2d' in name:\n return 4\n elif '16n2d' in name:\n return 2\n elif '8n3d' in name:\n return 6\n elif '16n3d':\n return 3\n\nget_pilot_avgpilots = lambda x,y: ((pilot_avgtype(get_pilot_info(x, 'id'))),\n ((y['end_time'] - y['start_time'])\n - (x['end_time'] - x['start_time'])),\n x['end_time'] - x['start_time'])\n\nget_pilot_avgw = lambda x,y: ((pilot_avgtype(get_pilot_info(x, 'nodes', True))),\n ((y['end_time'] - y['start_time'])\n - (x['end_time'] - x['start_time'])),\n x['end_time'] - x['start_time'])\n\n\n\nget_batch_avgpilots = lambda x:(((len(set(x['sid'][0]['nodes']))\n * (x['sid'][0]['end_time']\n - (max(x['sid'][0]['start_time'],\n x['sid'][0]['job_start'])\n if 'job_start' in x['sid'][0]\n and x['sid'][0]['job_start'] is not None\n else x['sid'][0]['start_time'])))\n / (x['end_time'] - x['start_time'])),\n x['end_time'] - x['start_time'])\n\nget_batch_avgw = lambda x:(((len(set(['{0}:{1}'.format(k, p)\n for k,v in x['sid'][0]['nodes'].items()\n for p in v]))\n * (x['sid'][0]['end_time']\n - (max(x['sid'][0]['start_time'],\n x['sid'][0]['job_start'])\n if 'job_start' in x['sid'][0]\n and x['sid'][0]['job_start'] is not None\n else x['sid'][0]['start_time'])))\n / (x['end_time'] - x['start_time'])),\n x['end_time'] - x['start_time'])\n\nm = lambda x,y : [el['end_time'] - el['start_time']\n if el['success']\n and el['end_time'] is not None\n else 0\n for el in x\n if y in el['name']]\n\nw_batch = lambda y :[get_batch_avgw(el)[0]\n if el['success']\n and el['end_time'] is not None\n else 0\n for el in batch\n if y in el['name']]\nw_pilot = lambda x,y: [get_pilot_avgw(el, el)[0]\n if el['success'] and el['end_time'] is not None\n else 0\n for el in x\n if y in el['name']]\n\ndef get_m_w(mode):\n if mode == 'batch':\n return [(w_batch(n), m(batch, n)) for n in ['single', 'double',\n 'triple', 'quadruple']]\n elif mode == '8p':\n return [(w_pilot(pilots8, n), m(pilots8, n)) for n in ['1d', '2d',\n '3d', '4d']]\n else:\n return [(w_pilot(pilots16, n), m(pilots16, n)) for n in ['1d', '2d',\n '3d', '4d']]\n\ndef average_speed_up(dedicated_dict, pilots=8):\n pilots = \"{}pilots\".format(pilots)\n return mean([elem / dedicated_dict[pilots][i]\n for i, elem in enumerate(dedicated_dict['batch'])\n if elem > 0 and dedicated_dict[pilots][i] > 0])\n\n\n\ndef main():\n global batch, pilots8, pilots16\n batch = load_json(sys.argv[1])\n pilots8 = load_json(sys.argv[2])\n pilots16 = load_json(sys.argv[3])\n\n system = sys.argv[4]\n\n assert(len(batch)==len(pilots8)==len(pilots16)), len(batch)\n\n global dedicated_1, dedicated_2, dedicated_3, dedicated_4\n\n fill_dictionaries(dedicated_1, dedicated_2, dedicated_3, dedicated_4)\n\n pq_1 = makespan_dict()\n pq_2 = makespan_dict()\n pq_3 = makespan_dict()\n pq_4 = makespan_dict()\n\n fill_dictionaries(pq_1, pq_2, pq_3, pq_4, queue=True)\n\n repetition_fig(pq_1, 1, system=system,\n save=\"figures/pq_1_{}\".format(system))\n repetition_fig(pq_2, 2, system=system,\n save=\"figures/pq_2_{}\".format(system))\n repetition_fig(pq_3, 3, system=system,\n save=\"figures/pq_3_{}\".format(system))\n repetition_fig(pq_4, 4, system=system,\n save=\"figures/pq_4_{}\".format(system))\n\n repetition_fig(dedicated_1, 1, system=system,\n save=\"figures/dedicated_1_{}.pdf\".format(system))\n repetition_fig(dedicated_2, 2, system=system,\n save=\"figures/dedicated_2_{}.pdf\".format(system))\n repetition_fig(dedicated_3, 3, system=system,\n save=\"figures/dedicated_3_{}.pdf\".format(system))\n repetition_fig(dedicated_4, 4, system=system,\n save=\"figures/dedicated_4_{}.pdf\".format(system))\n\n print(dedicated_1['batch'][7])\n batchmw_1d, batchmw_2d, batchmw_3d, batchmw_4d = tuple(get_m_w(\"batch\"))\n pilots8mw_1d, pilots8mw_2d, pilots8mw_3d, pilots8mw_4d = tuple(get_m_w(\"8p\"))\n pilots16mw_1d, pilots16mw_2d, pilots16mw_3d, pilots16mw_4d = tuple(get_m_w(\"16p\"))\n\n print(get_batch_avgw(batch[6])[0], batchmw_4d)\n print(len(batchmw_1d[0]), len(pilots8mw_1d[0]), len(pilots16mw_1d[0]))\n\n nworkers_fig({'batch': batchmw_1d[0], '8pilots': pilots8mw_1d[0],\n '16pilots': pilots16mw_1d[0] }, 1, system=system,\n save=\"figures/nworkers_1_{}.pdf\".format(system))\n nworkers_fig({'batch': batchmw_2d[0], '8pilots': pilots8mw_2d[0],\n '16pilots': pilots16mw_2d[0] }, 1, system=system,\n save=\"figures/nworkers_2_{}.pdf\".format(system))\n nworkers_fig({'batch': batchmw_3d[0], '8pilots': pilots8mw_3d[0],\n '16pilots': pilots16mw_3d[0] }, 1, system=system,\n save=\"figures/nworkers_3_{}.pdf\".format(system))\n nworkers_fig({'batch': batchmw_4d[0], '8pilots': pilots8mw_4d[0],\n '16pilots': pilots16mw_4d[0] }, 1, system=system,\n save=\"figures/nworkers_4_{}.pdf\".format(system))\n\n print(\"{} average speedup:\".format(system))\n print(\"8pilots 1 dedicated\", average_speed_up(dedicated_1, 8))\n print(\"8pilots 2 dedicated\", average_speed_up(dedicated_2, 8))\n print(\"8pilots 3 dedicated\", average_speed_up(dedicated_3, 8))\n print(\"8pilots 4 dedicated\", average_speed_up(dedicated_4, 8))\n print(\"16pilots 1 dedicated\", average_speed_up(dedicated_1, 16))\n print(\"16pilots 2 dedicated\", average_speed_up(dedicated_2, 16))\n print(\"16pilots 3 dedicated\", average_speed_up(dedicated_3, 16))\n print(\"16pilots 4 dedicated\", average_speed_up(dedicated_4, 16))\n\n #data = get_pilot_info(pilots8[1], 'nodes', True)\n #print(pilots8[1][\"name\"], data)\n #print(sum([data[i][1]*(data[i + 1][0] - data[i][0]) for i in range(len(data) - 1)]) / ( data[-1][0] - data[0][0] ))\n\n\n def keep_successful(data):\n w = []\n m = []\n for i, elem in enumerate(data[0]):\n if elem != 0 and data[1][i] != 0:\n w.append(elem)\n m.append(data[1][i])\n return (w, m)\n\n batchmw_1d = keep_successful(batchmw_1d) \n batchmw_2d = keep_successful(batchmw_2d) \n batchmw_3d = keep_successful(batchmw_3d) \n batchmw_4d = keep_successful(batchmw_4d) \n pilots8mw_1d = keep_successful(pilots8mw_1d) \n pilots8mw_2d = keep_successful(pilots8mw_2d) \n pilots8mw_3d = keep_successful(pilots8mw_3d) \n pilots8mw_4d = keep_successful(pilots8mw_4d) \n pilots16mw_1d = keep_successful(pilots16mw_1d) \n pilots16mw_2d = keep_successful(pilots16mw_2d) \n pilots16mw_3d = keep_successful(pilots16mw_3d) \n pilots16mw_4d = keep_successful(pilots16mw_4d) \n\n print(pilots8mw_1d)\n\n basic_model(batchmw_1d + pilots8mw_1d,\n batchmw_2d + pilots8mw_2d,\n batchmw_3d + pilots8mw_3d,\n batchmw_4d + pilots8mw_4d, \"batch - 8\", \"W\", \"M\",\n system=system, save=\"figures/mw_8_{}.pdf\".format(system))\n\n basic_model(batchmw_1d + pilots16mw_1d,\n batchmw_2d + pilots16mw_2d,\n batchmw_3d + pilots16mw_3d,\n batchmw_4d + pilots16mw_4d, \"batch - 16\", \"W\", \"M\",\n system=system, save=\"figures/mw_16_{}.pdf\".format(system))\n\n basic_model(batchmw_1d + pilots8mw_1d + pilots16mw_1d,\n batchmw_2d + pilots8mw_2d + pilots16mw_2d,\n batchmw_3d + pilots8mw_3d + pilots16mw_3d,\n batchmw_4d + pilots8mw_4d + pilots16mw_4d, \"batch - 8 - 16\",\n \"W\", \"M\", system=system,\n save=\"figures/mw_{}.pdf\".format(system))\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.polynomial.polynomial.polyfit", "numpy.arange", "numpy.asarray", "matplotlib.lines.Line2D", "matplotlib.pyplot.subplots", "matplotlib.pyplot.savefig", "numpy.ceil", "matplotlib.pyplot.setp", "matplotlib.pyplot.show" ] ]
cricketclub/gridspace-stanford-harper-valley
[ "0bd721e877c4a85d8c13ff837e68661ea6200a98" ]
[ "experiments/src/models/recognition/tasks.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass TaskTypePredictor(nn.Module):\n\n def __init__(self, input_dim, task_type_num_classes):\n super().__init__()\n self.task_fc = nn.Linear(input_dim, task_type_num_classes)\n self.task_type_num_classes = task_type_num_classes\n\n def forward(self, inputs):\n task_logits = self.task_fc(inputs)\n task_log_probs = F.log_softmax(task_logits, dim=1)\n return task_log_probs\n \n def get_loss(self, log_probs, targets):\n return F.nll_loss(log_probs, targets)\n\n\nclass DialogActsPredictor(nn.Module):\n\n def __init__(self, input_dim, num_dialog_acts):\n super().__init__()\n self.dialogacts_fc = nn.Linear(input_dim, num_dialog_acts)\n self.num_dialog_acts = num_dialog_acts\n\n def forward(self, inputs):\n dialogacts_logits = self.dialogacts_fc(inputs)\n # one person can have multiple dialog actions\n dialogacts_probs = torch.sigmoid(dialogacts_logits)\n return dialogacts_probs\n\n def get_loss(self, probs, targets):\n # probs : batch_size x num_dialog_acts\n # targets : batch_size x num_dialog_acts\n return F.binary_cross_entropy(probs.view(-1), targets.view(-1).float())\n\n\nclass SentimentPredictor(nn.Module):\n\n def __init__(self, input_dim, sentiment_num_classes):\n super().__init__()\n self.sentiment_fc = nn.Linear(input_dim, sentiment_num_classes)\n self.sentiment_num_classes = sentiment_num_classes\n\n def forward(self, inputs):\n sentiment_logits = self.sentiment_fc(inputs)\n sentiment_log_probs = F.log_softmax(sentiment_logits, dim=1)\n return sentiment_log_probs\n\n def get_loss(self, pred_log_probs, target_probs):\n # pred_logits : batch_size x num_sentiment_class\n # target_logits : batch_size x num_sentiment_class\n xentropy = -torch.sum(target_probs * pred_log_probs, dim=1)\n return torch.mean(xentropy)\n\n\nclass SpeakerIdPredictor(nn.Module):\n\n def __init__(self, input_dim, num_speaker_ids):\n super().__init__()\n self.speaker_id_fc = nn.Linear(input_dim, num_speaker_ids)\n self.num_speaker_ids = num_speaker_ids\n\n def forward(self, inputs):\n speaker_id_logits = self.speaker_id_fc(inputs)\n speaker_id_log_probs = F.log_softmax(speaker_id_logits, dim=1)\n return speaker_id_log_probs\n\n def get_loss(self, log_probs, targets):\n return F.nll_loss(log_probs, targets)\n\n" ]
[ [ "torch.mean", "torch.sigmoid", "torch.nn.functional.nll_loss", "torch.nn.functional.log_softmax", "torch.sum", "torch.nn.Linear" ] ]
kmhk-naka/python-esn
[ "9885ef81a66981f3942fbab954972c224fd6a8d4" ]
[ "src/logistic.py" ]
[ "from pathlib import Path\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom esn import EchoStateNetwork as ESN\n\n\ndef logistic(x: float, alpha: float):\n return alpha * x * (1 - x)\n\n\nimage_path = Path('./images').resolve()\nimage_path.mkdir(mode=0o775, parents=True, exist_ok=True)\n\ninit_length = 1000\ntrain_length = 200_000\ntest_length = 1000\ntmax = train_length + test_length\n\nnp.random.seed(0)\n\ndata = np.zeros((tmax + 1, 1))\na = 4\ndata[0] = np.random.rand(1)\nfor t in range(tmax):\n data[t + 1] = logistic(data[t], a)\n\nmodel = ESN(\n init_length=init_length,\n train_length=train_length,\n test_length=test_length,\n tmax=tmax\n)\n\nd = data[init_length + 1:train_length + 1]\n\nmodel.fit(data[:train_length], d)\npredict_result = model.predict(data[train_length:])\n\n# Plot options\nbbox_to_anchor = (1.02, 0)\nbbox_loc = 'lower left'\n\nfig = plt.figure(figsize=(10, 8))\n\n# Plot prediction\nax1 = fig.add_subplot(211)\nindex = np.arange(train_length, tmax)\nax1.plot(index, data[train_length:-1], label='input data')\nax1.plot(index, predict_result[train_length:-1, 0], label='predict result')\nax1.legend(bbox_to_anchor=bbox_to_anchor, loc=bbox_loc, borderaxespad=0)\nax1.set_xlabel(r'$n$')\nax1.set_ylabel(r'$y_n$')\nax1.set_title('Prediction')\n\n# Plot prediction (enlarged)\nax2 = fig.add_subplot(212)\nenlarge_length = 200\nenlarge_tmax = train_length + enlarge_length\nindex = np.arange(train_length, enlarge_tmax)\nax2.plot(index, data[train_length:enlarge_tmax], label='input data')\nax2.plot(index, predict_result[train_length:enlarge_tmax, 0], label='predict result')\nax2.legend(bbox_to_anchor=bbox_to_anchor, loc=bbox_loc, borderaxespad=0)\nax2.set_xlabel(r'$n$')\nax2.set_ylabel(r'$y_n$')\nax2.set_title('Prediction (enlarged)')\n\nfig.subplots_adjust(right=0.8, hspace=0.5)\n\nplt.savefig(image_path / 'logistic.png', bbox_inches='tight', pad_inches=0.1)\n\nplt.clf()\n\n# Plot prediction feature\nax1 = fig.add_subplot(211)\nax1.scatter(predict_result[:-1, 0], predict_result[1:, 0])\nax1.set_xlabel(r'$y_n$')\nax1.set_ylabel(r'$y_{n+1}$')\nax1.set_title('Prediction')\n\n# Plot Logistic feature\nax2 = fig.add_subplot(212)\nax2.scatter(data[train_length:-1, 0], data[train_length + 1:, 0])\nax2.set_xlabel(r'$y_n$')\nax2.set_ylabel(r'$y_{n+1}$')\nax2.set_title('Logistic')\n\nfig.subplots_adjust(right=0.8, hspace=0.5)\n\nplt.savefig(image_path / 'logistic-feature.png', bbox_inches='tight', pad_inches=0.1)\n\nplt.clf()\n" ]
[ [ "numpy.random.seed", "numpy.arange", "matplotlib.pyplot.savefig", "matplotlib.pyplot.clf", "numpy.random.rand", "numpy.zeros", "matplotlib.pyplot.figure" ] ]
a-sansanwal/DALI
[ "83aeb96792d053f60dd4252b8efa0fc8fdd9012a" ]
[ "dali/python/nvidia/dali/plugin/mxnet.py" ]
[ "# Copyright (c) 2017-2019, NVIDIA CORPORATION. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom nvidia.dali.backend import TensorGPU, TensorListGPU\nfrom nvidia.dali import types\nfrom nvidia.dali.plugin.base_iterator import _DaliBaseIterator\nimport mxnet as mx\nimport ctypes\nimport numpy as np\nfrom collections import Iterable\n\n\n##################################################\n##################################################\n################## Common utils ##################\n##################################################\n##################################################\n\n\n# MXNet currently does not expose WaitToWrite C API call\n# in Python API\ndef _wait_to_write(arr):\n if not isinstance(arr, mx.nd.NDArray):\n raise RuntimeError(\"Can only wait for NDArray\")\n mx.base._LIB.MXNDArrayWaitToWrite(arr.handle)\n\ndef feed_ndarray(dali_tensor, arr, cuda_stream = None):\n \"\"\"\n Copy contents of DALI tensor to MXNet's NDArray.\n\n Parameters\n ----------\n `dali_tensor` : nvidia.dali.backend.TensorCPU or nvidia.dali.backend.TensorGPU\n Tensor from which to copy\n `arr` : mxnet.nd.NDArray\n Destination of the copy\n `cuda_stream` : cudaStream_t handle or any value that can be cast to cudaStream_t.\n CUDA stream to be used for the copy\n (if not provided, an internal user stream will be selected)\n In most cases, using the default internal user stream or stream 0\n is expected.\n \"\"\"\n # Wait until arr is no longer used by the engine\n _wait_to_write(arr)\n assert dali_tensor.shape() == list(arr.shape), \\\n (\"Shapes do not match: DALI tensor has shape {0}\"\n \", but NDArray has shape {1}\".format(dali_tensor.shape(), list(arr.shape)))\n # Get CTypes void pointer to the underlying memory held by arr\n ptr = ctypes.c_void_p()\n mx.base._LIB.MXNDArrayGetData(arr.handle, ctypes.byref(ptr))\n\n cuda_stream = types._raw_cuda_stream(cuda_stream)\n\n # Copy data from DALI tensor to ptr\n if isinstance(dali_tensor, (TensorGPU, TensorListGPU)):\n dali_tensor.copy_to_external(ptr, None if cuda_stream is None else ctypes.c_void_p(cuda_stream))\n else:\n dali_tensor.copy_to_external(ptr)\n\nclass _DALIMXNetIteratorBase(mx.io.DataIter, _DaliBaseIterator):\n \"\"\"\n Base class with methods shared by both DALIGenericIterator and DALIGluonIterator.\n \"\"\"\n def __init__(self,\n pipelines,\n size=-1,\n reader_name=None,\n fill_last_batch=False,\n last_batch_padded=False,\n auto_reset=False):\n _DaliBaseIterator.__init__(self, pipelines, size, reader_name, auto_reset, fill_last_batch, last_batch_padded)\n\n def next(self):\n \"\"\"\n Returns the next batch of data.\n \"\"\"\n return self.__next__()\n\n def reset(self):\n \"\"\"\n Resets the iterator after the full epoch.\n DALI iterators do not support resetting before the end of the epoch\n and will ignore such request.\n \"\"\"\n _DaliBaseIterator.reset(self)\n\ndef get_mx_array(shape, ctx=None, dtype=None):\n # WAR\n # ToDo (jlisiecki) - fix when upstream MXNet fixes this\n # mx.nd.empty doesn't support np.longlong as mx.nd.zeros does, but it does np.int64\n # which from our point of view is the same\n if dtype == np.longlong:\n dtype = np.int64\n # mx.nd.empy doesn't handle scalaras as shape\n if not isinstance(shape, Iterable):\n shape = [shape]\n\n return mx.nd.empty(shape, ctx, dtype)\n\n\n###################################################\n###################################################\n################## MXNet Sym API ##################\n###################################################\n###################################################\n\nclass DALIGenericIterator(_DALIMXNetIteratorBase):\n \"\"\"\n General DALI iterator for MXNet. It can return any number of\n outputs from the DALI pipeline in the form of MXNet's DataBatch\n of NDArrays.\n\n Please keep in mind that NDArrays returned by the iterator are\n still owned by DALI. They are valid till the next iterator call.\n If the content needs to be preserved please copy it to another NDArray.\n\n Parameters\n ----------\n pipelines : list of nvidia.dali.pipeline.Pipeline\n List of pipelines to use\n output_map : list of (str, str)\n List of pairs (output_name, tag) which maps consecutive\n outputs of DALI pipelines to proper field in MXNet's\n DataBatch.\n tag is one of DALIGenericIterator.DATA_TAG\n and DALIGenericIterator.LABEL_TAG mapping given output\n for data or label correspondingly.\n output_names should be distinct.\n size : int, default = -1\n Number of samples in the shard for the wrapped pipeline (if there is more than one it is a sum)\n Providing -1 means that the iterator will work until StopIteration is raised\n from the inside of iter_setup(). The options `fill_last_batch`, `last_batch_padded` and\n `auto_reset` don't work in such case. It works with only one pipeline inside\n the iterator.\n Mutually exclusive with `reader_name` argument\n reader_name : str, default = None\n Name of the reader which will be queried to the shard size, number of shards and\n all other properties necessary to count properly the number of relevant and padded\n samples that iterator needs to deal with. It automatically sets `fill_last_batch` and\n `last_batch_padded` accordingly to match the reader's configuration\n data_layout : str, optional, default = 'NCHW'\n Either 'NHWC' or 'NCHW' - layout of the pipeline outputs.\n fill_last_batch : bool, optional, default = True\n Whether to fill the last batch with data up to 'self.batch_size'.\n The iterator would return the first integer multiple\n of self._num_gpus * self.batch_size entries which exceeds 'size'.\n Setting this flag to False will cause the iterator to return\n exactly 'size' entries.\n auto_reset : bool, optional, default = False\n Whether the iterator resets itself for the next epoch\n or it requires reset() to be called separately.\n squeeze_labels: bool, optional, default = True\n Whether the iterator should squeeze the labels before\n copying them to the ndarray.\n dynamic_shape: bool, optional, default = False\n Whether the shape of the output of the DALI pipeline can\n change during execution. If True, the mxnet.ndarray will be resized accordingly\n if the shape of DALI returned tensors changes during execution.\n If False, the iterator will fail in case of change.\n last_batch_padded : bool, optional, default = False\n Whether the last batch provided by DALI is padded with the last sample\n or it just wraps up. In the conjunction with ``fill_last_batch`` it tells\n if the iterator returning last batch with data only partially filled with\n data from the current epoch is dropping padding samples or samples from\n the next epoch (it doesn't literally drop but sets ``pad`` field of ndarray\n so the following code could use it to drop the data). If set to False next\n epoch will end sooner as data from it was consumed but dropped. If set to\n True next epoch would be the same length as the first one. For this to happen,\n the option `pad_last_batch` in the reader needs to be set to True as well.\n It is overwritten when `reader_name` argument is provided\n\n Example\n -------\n With the data set ``[1,2,3,4,5,6,7]`` and the batch size 2:\n\n fill_last_batch = False, last_batch_padded = True -> last batch = ``[7]``, next iteration will return ``[1, 2]``\n\n fill_last_batch = False, last_batch_padded = False -> last batch = ``[7]``, next iteration will return ``[2, 3]``\n\n fill_last_batch = True, last_batch_padded = True -> last batch = ``[7, 7]``, next iteration will return ``[1, 2]``\n\n fill_last_batch = True, last_batch_padded = False -> last batch = ``[7, 1]``, next iteration will return ``[2, 3]``\n \"\"\"\n def __init__(self,\n pipelines,\n output_map,\n size=-1,\n reader_name=None,\n data_layout='NCHW',\n fill_last_batch=True,\n auto_reset=False,\n squeeze_labels=True,\n dynamic_shape=False,\n last_batch_padded=False):\n super(DALIGenericIterator, self).__init__(\n pipelines,\n size,\n reader_name,\n fill_last_batch,\n last_batch_padded,\n auto_reset)\n self._squeeze_labels = squeeze_labels\n self._dynamic_shape = dynamic_shape\n # Use double-buffering of data batches\n self._data_batches = [[None] for i in range(self._num_gpus)]\n self._current_data_batch = 0\n self._output_names_map = [x[0] for x in output_map]\n self._output_categories_map = [x[1] for x in output_map]\n self._output_categories = {DALIGenericIterator.DATA_TAG, DALIGenericIterator.LABEL_TAG}\n assert set(self._output_categories_map) <= self._output_categories, \\\n \"Only DATA_TAG and LABEL_TAG are allowed\"\n assert len(set(self._output_names_map)) == len(self._output_names_map), \\\n \"output_names in output_map should be distinct\"\n self.output_map = output_map\n\n # We need data about the batches (like shape information),\n # so we need to run a single batch as part of setup to get that info\n for p in self._pipes:\n with p._check_api_type_scope(types.PipelineAPIType.ITERATOR):\n p.schedule_run()\n self._first_batch = None\n self._first_batch = self.next()\n # Set data descriptors for MXNet\n self.provide_data = []\n self.provide_label = []\n\n category_names = {key : [] for key in self._output_categories}\n for name, category in output_map:\n category_names[category].append(name)\n for i, data in enumerate(self._first_batch[0].data):\n data_shape = (data.shape[0] * self._num_gpus,) + data.shape[1:]\n self.provide_data.append(mx.io.DataDesc(category_names[DALIGenericIterator.DATA_TAG][i], \\\n data_shape, data.dtype, layout=data_layout))\n for i, label in enumerate(self._first_batch[0].label):\n label_shape = (label.shape[0] * self._num_gpus,) + label.shape[1:]\n self.provide_label.append(mx.io.DataDesc(category_names[DALIGenericIterator.LABEL_TAG][i], \\\n label_shape, label.dtype))\n\n\n def __next__(self):\n if self._first_batch is not None:\n batch = self._first_batch\n self._first_batch = None\n return batch\n self._check_stop()\n # Gather outputs\n outputs = []\n for p in self._pipes:\n with p._check_api_type_scope(types.PipelineAPIType.ITERATOR):\n outputs.append(p.share_outputs())\n for i in range(self._num_gpus):\n # MXNet wants batches with clear distinction between\n # data and label entries, so segregate outputs into\n # 2 categories\n category_outputs = {key : [] for key in self._output_categories}\n for j, out in enumerate(outputs[i]):\n category_outputs[self._output_categories_map[j]].append(out)\n # Change DALI TensorLists into Tensors\n category_tensors = dict()\n category_info = dict()\n # For data proceed normally\n category_tensors[DALIGenericIterator.DATA_TAG] = \\\n [x.as_tensor() for x in category_outputs[DALIGenericIterator.DATA_TAG]]\n category_info[DALIGenericIterator.DATA_TAG] = \\\n [(x.shape(), np.dtype(x.dtype())) for x in category_tensors[DALIGenericIterator.DATA_TAG]]\n # For labels we squeeze the tensors\n category_tensors[DALIGenericIterator.LABEL_TAG] = \\\n [x.as_tensor() for x in category_outputs[DALIGenericIterator.LABEL_TAG]]\n if self._squeeze_labels:\n for label in category_tensors[DALIGenericIterator.LABEL_TAG]:\n label.squeeze()\n category_info[DALIGenericIterator.LABEL_TAG] = \\\n [(x.shape(), np.dtype(x.dtype())) for x in category_tensors[DALIGenericIterator.LABEL_TAG]]\n\n # If we did not yet allocate memory for that batch, do it now\n if self._data_batches[i][self._current_data_batch] is None:\n mx_gpu_device = mx.gpu(self._pipes[i].device_id)\n mx_cpu_device = mx.cpu(0)\n category_device = {key : [] for key in self._output_categories}\n for category in self._output_categories:\n for t in category_tensors[category]:\n if type(t) is TensorGPU:\n category_device[category].append(mx_gpu_device)\n else:\n category_device[category].append(mx_cpu_device)\n d = []\n l = []\n for j, (shape, dtype) in enumerate(category_info[DALIGenericIterator.DATA_TAG]):\n d.append(get_mx_array(shape, category_device[DALIGenericIterator.DATA_TAG][j], dtype = dtype))\n for j, (shape, dtype) in enumerate(category_info[DALIGenericIterator.LABEL_TAG]):\n l.append(get_mx_array(shape, category_device[DALIGenericIterator.LABEL_TAG][j], dtype = dtype))\n\n self._data_batches[i][self._current_data_batch] = mx.io.DataBatch(data=d, label=l)\n\n d = self._data_batches[i][self._current_data_batch].data\n l = self._data_batches[i][self._current_data_batch].label\n # Copy data from DALI Tensors to MXNet NDArrays\n if self._dynamic_shape:\n for j, (shape, dtype) in enumerate(category_info[DALIGenericIterator.DATA_TAG]):\n if list(d[j].shape) != shape:\n d[j] = get_mx_array(shape, d[j].context, dtype = dtype)\n for j, (shape, dtype) in enumerate(category_info[DALIGenericIterator.LABEL_TAG]):\n if list(l[j].shape) != shape:\n l[j] = get_mx_array(shape, l[j].context, dtype = dtype)\n\n for j, d_arr in enumerate(d):\n feed_ndarray(category_tensors[DALIGenericIterator.DATA_TAG][j], d_arr)\n for j, l_arr in enumerate(l):\n feed_ndarray(category_tensors[DALIGenericIterator.LABEL_TAG][j], l_arr)\n\n for p in self._pipes:\n with p._check_api_type_scope(types.PipelineAPIType.ITERATOR):\n p.release_outputs()\n p.schedule_run()\n\n copy_db_index = self._current_data_batch\n if self._reader_name:\n self._counter += self.batch_size\n if_drop, left = self._remove_padded()\n if np.any(if_drop):\n left = [self.batch_size - l for l in left]\n for i, to_pad in zip(range(self._num_gpus), left):\n self._data_batches[i][copy_db_index].pad = to_pad\n else:\n for batch in self._data_batches:\n batch[copy_db_index].pad = 0\n\n else:\n self._counter += self._num_gpus * self.batch_size\n\n # padding the last batch\n if (not self._fill_last_batch) and (self._counter > self._size) and self._size > 0:\n # this is the last batch and we need to pad\n overflow = self._counter - self._size\n overflow_per_device = overflow // self._num_gpus\n difference = self._num_gpus - (overflow % self._num_gpus)\n for i in range(self._num_gpus):\n if i < difference:\n self._data_batches[i][copy_db_index].pad = overflow_per_device\n else:\n self._data_batches[i][copy_db_index].pad = overflow_per_device + 1\n else:\n for db in self._data_batches:\n db[copy_db_index].pad = 0\n\n return [db[copy_db_index] for db in self._data_batches]\n\n DATA_TAG = \"data\"\n LABEL_TAG = \"label\"\n\nclass DALIClassificationIterator(DALIGenericIterator):\n \"\"\"\n DALI iterator for classification tasks for MXNet. It returns 2 outputs\n (data and label) in the form of MXNet's DataBatch of NDArrays.\n\n Calling\n\n .. code-block:: python\n\n DALIClassificationIterator(pipelines, size, data_name, label_name, data_layout)\n\n is equivalent to calling\n\n .. code-block:: python\n\n DALIGenericIterator(pipelines,\n [(data_name, DALIClassificationIterator.DATA_TAG),\n (label_name, DALIClassificationIterator.LABEL_TAG)],\n size,\n data_layout)\n\n Please keep in mind that NDArrays returned by the iterator are\n still owned by DALI. They are valid till the next iterator call.\n If the content needs to be preserved please copy it to another NDArray.\n\n Parameters\n ----------\n pipelines : list of nvidia.dali.pipeline.Pipeline\n List of pipelines to use\n size : int, default = -1\n Number of samples in the shard for the wrapped pipeline (if there is more than one it is a sum)\n Providing -1 means that the iterator will work until StopIteration is raised\n from the inside of iter_setup(). The options `fill_last_batch`, `last_batch_padded` and\n `auto_reset` don't work in such case. It works with only one pipeline inside\n the iterator.\n Mutually exclusive with `reader_name` argument\n reader_name : str, default = None\n Name of the reader which will be queried to the shard size, number of shards and\n all other properties necessary to count properly the number of relevant and padded\n samples that iterator needs to deal with. It automatically sets `fill_last_batch` and\n `last_batch_padded` accordingly to match the reader's configuration\n data_name : str, optional, default = 'data'\n Data name for provided symbols.\n label_name : str, optional, default = 'softmax_label'\n Label name for provided symbols.\n data_layout : str, optional, default = 'NCHW'\n Either 'NHWC' or 'NCHW' - layout of the pipeline outputs.\n fill_last_batch : bool, optional, default = True\n Whether to fill the last batch with data up to 'self.batch_size'.\n The iterator would return the first integer multiple\n of self._num_gpus * self.batch_size entries which exceeds 'size'.\n Setting this flag to False will cause the iterator to return\n exactly 'size' entries.\n auto_reset : bool, optional, default = False\n Whether the iterator resets itself for the next epoch\n or it requires reset() to be called separately.\n squeeze_labels: bool, optional, default = True\n Whether the iterator should squeeze the labels before\n copying them to the ndarray.\n dynamic_shape: bool, optional, default = False\n Whether the shape of the output of the DALI pipeline can\n change during execution. If True, the mxnet.ndarray will be resized accordingly\n if the shape of DALI returned tensors changes during execution.\n If False, the iterator will fail in case of change.\n last_batch_padded : bool, optional, default = False\n Whether the last batch provided by DALI is padded with the last sample\n or it just wraps up. In the conjunction with ``fill_last_batch`` it tells\n if the iterator returning last batch with data only partially filled with\n data from the current epoch is dropping padding samples or samples from\n the next epoch (it doesn't literally drop but sets ``pad`` field of ndarray\n so the following code could use it to drop the data). If set to False next\n epoch will end sooner as data from it was consumed but dropped. If set to\n True next epoch would be the same length as the first one. For this to happen,\n the option `pad_last_batch` in the reader needs to be set to True as well.\n It is overwritten when `reader_name` argument is provided\n\n Example\n -------\n With the data set ``[1,2,3,4,5,6,7]`` and the batch size 2:\n\n fill_last_batch = False, last_batch_padded = True -> last batch = ``[7]``, next iteration will return ``[1, 2]``\n\n fill_last_batch = False, last_batch_padded = False -> last batch = ``[7]``, next iteration will return ``[2, 3]``\n\n fill_last_batch = True, last_batch_padded = True -> last batch = ``[7, 7]``, next iteration will return ``[1, 2]``\n\n fill_last_batch = True, last_batch_padded = False -> last batch = ``[7, 1]``, next iteration will return ``[2, 3]``\n \"\"\"\n def __init__(self,\n pipelines,\n size=-1,\n reader_name=None,\n data_name='data',\n label_name='softmax_label',\n data_layout='NCHW',\n fill_last_batch=True,\n auto_reset=False,\n squeeze_labels=True,\n dynamic_shape=False,\n last_batch_padded=False):\n super(DALIClassificationIterator, self).__init__(pipelines,\n [(data_name, DALIClassificationIterator.DATA_TAG),\n (label_name, DALIClassificationIterator.LABEL_TAG)],\n size,\n reader_name=reader_name,\n data_layout=data_layout,\n fill_last_batch=fill_last_batch,\n auto_reset = auto_reset,\n squeeze_labels=squeeze_labels,\n dynamic_shape=dynamic_shape,\n last_batch_padded = last_batch_padded)\n\n###############################################\n###############################################\n################## Gluon API ##################\n###############################################\n###############################################\n\n\nclass SmartArray(object):\n def __init__(self, array):\n self._data = array.reshape(-1)\n self._view = array\n\n def resize(self, shape):\n new_size = np.prod(shape)\n\n if new_size > self._data.size:\n self._data = get_mx_array(new_size, self._data.context, dtype=self._data.dtype)\n self._view = self._data\n elif new_size < self._data.size:\n self._view = self._data[:new_size]\n else:\n self._view = self._data\n self._view = self._view.reshape(shape)\n return self._view\n\n @property\n def view(self):\n return self._view\n\n\nclass DALIGluonIterator(_DALIMXNetIteratorBase):\n \"\"\"\n General DALI iterator for MXNet with Gluon API. It can return any number of\n outputs from the DALI pipeline in the form of per GPU tuples. These tuples consisting of\n NDArrays (for outputs marked as DALIGluonIterator.DENSE_TAG) and list of NDArrays (for\n output marked as DALIGluonIterator.SPARSE_TAG).\n\n Please keep in mind that NDArrays returned by the iterator are\n still owned by DALI. They are valid till the next iterator call.\n If the content needs to be preserved please copy it to another NDArray.\n\n Parameters\n ----------\n pipelines : list of nvidia.dali.pipeline.Pipeline\n List of pipelines to use\n size : int, default = -1\n Number of samples in the shard for the wrapped pipeline (if there is more than one it is a sum)\n Providing -1 means that the iterator will work until StopIteration is raised\n from the inside of iter_setup(). The options `fill_last_batch`, `last_batch_padded` and\n `auto_reset` don't work in such case. It works with only one pipeline inside\n the iterator.\n Mutually exclusive with `reader_name` argument\n reader_name : str, default = None\n Name of the reader which will be queried to the shard size, number of shards and\n all other properties necessary to count properly the number of relevant and padded\n samples that iterator needs to deal with. It automatically sets `fill_last_batch` and\n `last_batch_padded` accordingly to match the reader's configuration\n output_types : list of str, optional, default = None\n List of tags indicating whether the pipeline(s) output batch is\n uniform (all the samples have the same size) or not. Batch output marked\n as the former will be returned as a single NDArray, the latter\n will be returned as a list of NDArray.\n Must be either DALIGluonIterator.DENSE_TAG\n or DALIGluonIterator.SPARSE_TAG.\n Length of output_types must match the number of output of the pipeline(s).\n If not set, all outputs are considered to be marked with DALIGluonIterator.DENSE_TAG.\n auto_reset : bool, optional, default = False\n Whether the iterator resets itself for the next epoch\n or it requires reset() to be called separately.\n fill_last_batch : bool, optional, default = True\n Whether to fill the last batch with data up to 'self.batch_size'.\n The iterator would return the first integer multiple\n of self._num_gpus * self.batch_size entries which exceeds 'size'.\n Setting this flag to False will cause the iterator to return\n exactly 'size' entries.\n last_batch_padded : bool, optional, default = False\n Whether the last batch provided by DALI is padded with the last sample\n or it just wraps up. In the conjunction with ``fill_last_batch`` it tells\n if the iterator returning last batch with data only partially filled with\n data from the current epoch is dropping padding samples or samples from\n the next epoch (it doesn't literally drop but sets ``pad`` field of ndarray\n so the following code could use it to drop the data). If set to False next\n epoch will end sooner as data from it was consumed but dropped. If set to\n True next epoch would be the same length as the first one. For this to happen,\n the option `pad_last_batch` in the reader needs to be set to True as well.\n It is overwritten when `reader_name` argument is provided\n\n Example\n -------\n With the data set ``[1,2,3,4,5,6,7]`` and the batch size 2:\n\n fill_last_batch = False, last_batch_padded = True -> last batch = ``[7]``, next iteration will return ``[1, 2]``\n\n fill_last_batch = False, last_batch_padded = False -> last batch = ``[7]``, next iteration will return ``[2, 3]``\n\n fill_last_batch = True, last_batch_padded = True -> last batch = ``[7, 7]``, next iteration will return ``[1, 2]``\n\n fill_last_batch = True, last_batch_padded = False -> last batch = ``[7, 1]``, next iteration will return ``[2, 3]``\n\n \"\"\"\n def __init__(self,\n pipelines,\n size=-1,\n reader_name=None,\n output_types=None,\n auto_reset=False,\n fill_last_batch=True,\n last_batch_padded=False):\n super(DALIGluonIterator, self).__init__(\n pipelines,\n size,\n reader_name,\n fill_last_batch,\n last_batch_padded,\n auto_reset)\n\n self._data_batches = [None for i in range(self._num_gpus)]\n self._output_tags = {DALIGluonIterator.DENSE_TAG, DALIGluonIterator.SPARSE_TAG}\n assert output_types is None or set(output_types) <= self._output_tags, \\\n \"Only DENSE_TAG and SPARSE_TAG are allowed\"\n\n self._outputs_types = output_types\n\n # We need data about the batches (like shape information),\n # so we need to run a single batch as part of setup to get that info\n for p in self._pipes:\n with p._check_api_type_scope(types.PipelineAPIType.ITERATOR):\n p.schedule_run()\n\n\n def __next__(self):\n self._check_stop()\n # Gather outputs\n dali_outputs = []\n for p in self._pipes:\n with p._check_api_type_scope(types.PipelineAPIType.ITERATOR):\n dali_outputs.append(p.share_outputs())\n for i in range(self._num_gpus):\n output_elements = []\n shapes = []\n for j, out in enumerate(dali_outputs[i]):\n if self._outputs_types is None or self._outputs_types[j] == DALIGluonIterator.DENSE_TAG:\n output_elements.append(out.as_tensor())\n shapes.append(output_elements[-1].shape())\n else:\n output_elements.append([out[sample_idx] for sample_idx in range(self.batch_size)])\n s = [t.shape() for t in output_elements[-1]]\n shapes.append(s)\n\n if self._data_batches[i] is None:\n self._data_batches[i] = self._create_data_batch(output_elements, shapes, self._pipes[i].device_id)\n\n batch = self._data_batches[i]\n # Copy data from DALI Tensors to MXNet NDArrays\n for j, output_el in enumerate(output_elements):\n if self._outputs_types is None or self._outputs_types[j] == DALIGluonIterator.DENSE_TAG:\n ndarray = batch[j].resize(shapes[j])\n feed_ndarray(output_el, ndarray)\n else:\n for sample_idx in range(self.batch_size):\n ndarray = batch[j][sample_idx].resize(shapes[j][sample_idx])\n feed_ndarray(output_el[sample_idx], ndarray)\n\n batches = [[([sample.view for sample in output_el] if isinstance(output_el,list) else output_el.view)\n for output_el in batch]\n for batch in self._data_batches]\n\n for p in self._pipes:\n with p._check_api_type_scope(types.PipelineAPIType.ITERATOR):\n p.release_outputs()\n p.schedule_run()\n\n if self._reader_name:\n self._counter += self.batch_size\n if_drop, left = self._remove_padded()\n if np.any(if_drop):\n output = []\n for batch, to_copy in zip(batches, left):\n batch = batch.copy()\n for element_idx in range(len(batch)):\n batch[element_idx] = batch[element_idx][0:to_copy]\n output.append(batch)\n return output\n\n else:\n self._counter += self._num_gpus * self.batch_size\n if (not self._fill_last_batch) and (self._counter > self._size) and self._size > 0:\n # First calculate how much data is required to return exactly self._size entries.\n diff = self._num_gpus * self.batch_size - (self._counter - self._size)\n # Figure out how many GPUs to grab from.\n numGPUs_tograb = int(np.ceil(diff/self.batch_size))\n # Figure out how many results to grab from the last GPU (as a fractional GPU batch may be required to\n # bring us right up to self._size).\n mod_diff = diff % self.batch_size\n data_fromlastGPU = mod_diff if mod_diff else self.batch_size\n\n # Grab the relevant data.\n # 1) Grab everything from the relevant GPUs.\n # 2) Grab the right data from the last GPU.\n # 3) Append data together correctly and return.\n output = batches[0:numGPUs_tograb]\n output[-1] = output[-1].copy()\n for element_idx in range(len(output[-1])):\n output[-1][element_idx] = output[-1][element_idx][0:data_fromlastGPU]\n return output\n\n return batches\n\n def _create_data_batch(self, output_elements, shapes, device_id):\n mx_gpu_device = mx.gpu(device_id)\n mx_cpu_device = mx.cpu(0)\n new_batch = []\n for j, output_el in enumerate(output_elements):\n first_t = output_el if self._outputs_types is None or self._outputs_types[j] == DALIGluonIterator.DENSE_TAG else output_el[0]\n dtype = np.dtype(first_t.dtype())\n device = mx_gpu_device if type(first_t) is TensorGPU else mx_cpu_device\n if self._outputs_types is None or self._outputs_types[j] == DALIGluonIterator.DENSE_TAG:\n new_batch.append(SmartArray(get_mx_array(shapes[j], device, dtype=dtype)))\n else:\n l = []\n for sample_idx in range(self.batch_size):\n l.append(SmartArray(get_mx_array(shapes[j][sample_idx], device, dtype=dtype)))\n new_batch.append(l)\n return new_batch\n\n DENSE_TAG = \"dense\"\n SPARSE_TAG = \"sparse\"\n" ]
[ [ "numpy.ceil", "numpy.any", "numpy.prod" ] ]
BossunWang/soft-intro-vae-pytorch
[ "1d240f60a99682e8409363c5829aba14869ba140" ]
[ "soft_intro_vae_3d/render/plyfile.py" ]
[ "# Copyright 2014 Darsh Ranjan\n#\n# This file is part of python-plyfile.\n#\n# python-plyfile is free software: you can redistribute it and/or\n# modify it under the terms of the GNU General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# python-plyfile is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with python-plyfile. If not, see\n# <http://www.gnu.org/licenses/>.\n\nfrom itertools import islice as _islice\n\nimport numpy as _np\nfrom sys import byteorder as _byteorder\n\n\ntry:\n _range = xrange\nexcept NameError:\n _range = range\n\n\n# Many-many relation\n_data_type_relation = [\n ('int8', 'i1'),\n ('char', 'i1'),\n ('uint8', 'u1'),\n ('uchar', 'b1'),\n ('uchar', 'u1'),\n ('int16', 'i2'),\n ('short', 'i2'),\n ('uint16', 'u2'),\n ('ushort', 'u2'),\n ('int32', 'i4'),\n ('int', 'i4'),\n ('uint32', 'u4'),\n ('uint', 'u4'),\n ('float32', 'f4'),\n ('float', 'f4'),\n ('float64', 'f8'),\n ('double', 'f8')\n]\n\n_data_types = dict(_data_type_relation)\n_data_type_reverse = dict((b, a) for (a, b) in _data_type_relation)\n\n_types_list = []\n_types_set = set()\nfor (_a, _b) in _data_type_relation:\n if _a not in _types_set:\n _types_list.append(_a)\n _types_set.add(_a)\n if _b not in _types_set:\n _types_list.append(_b)\n _types_set.add(_b)\n\n\n_byte_order_map = {\n 'ascii': '=',\n 'binary_little_endian': '<',\n 'binary_big_endian': '>'\n}\n\n_byte_order_reverse = {\n '<': 'binary_little_endian',\n '>': 'binary_big_endian'\n}\n\n_native_byte_order = {'little': '<', 'big': '>'}[_byteorder]\n\n\ndef _lookup_type(type_str):\n if type_str not in _data_type_reverse:\n try:\n type_str = _data_types[type_str]\n except KeyError:\n raise ValueError(\"field type %r not in %r\" %\n (type_str, _types_list))\n\n return _data_type_reverse[type_str]\n\n\ndef make2d(array, cols=None, dtype=None):\n '''\n Make a 2D array from an array of arrays. The `cols' and `dtype'\n arguments can be omitted if the array is not empty.\n '''\n if not len(array):\n if cols is None or dtype is None:\n raise RuntimeError(\n \"cols and dtype must be specified for empty array\"\n )\n return _np.empty((0, cols), dtype=dtype)\n return _np.vstack(array)\n\n\nclass _PlyHeaderParser(object):\n def __init__(self):\n self.format = None\n self.elements = []\n self.comments = []\n self.obj_info = []\n self.lines = 0\n self._allowed = ['ply']\n\n def consume(self, raw_line):\n self.lines += 1\n if not raw_line:\n self._error(\"early end-of-file\")\n\n line = raw_line.decode('ascii').strip()\n try:\n keyword = line.split(None, 1)[0]\n except IndexError:\n self._error()\n\n if keyword not in self._allowed:\n self._error(\"expected one of {%s}\" %\n \", \".join(self._allowed))\n\n getattr(self, 'parse_' + keyword)(line[len(keyword)+1:])\n return self._allowed\n\n def _error(self, message=\"parse error\"):\n raise PlyHeaderParseError(message, self.lines)\n\n def parse_ply(self, data):\n if data:\n self._error(\"unexpected characters after 'ply'\")\n self._allowed = ['format', 'comment', 'obj_info']\n\n def parse_format(self, data):\n fields = data.strip().split()\n if len(fields) != 2:\n self._error(\"expected \\\"format {format} 1.0\\\"\")\n\n self.format = fields[0]\n if self.format not in _byte_order_map:\n self._error(\"don't understand format %r\" % format)\n\n if fields[1] != '1.0':\n self._error(\"expected version '1.0'\")\n\n self._allowed = ['element', 'comment', 'obj_info', 'end_header']\n\n def parse_comment(self, data):\n if not self.elements:\n self.comments.append(data)\n else:\n self.elements[-1][3].append(data)\n\n def parse_obj_info(self, data):\n self.obj_info.append(data)\n\n def parse_element(self, data):\n fields = data.strip().split()\n if len(fields) != 2:\n self._error(\"expected \\\"element {name} {count}\\\"\")\n\n name = fields[0]\n try:\n count = int(fields[1])\n except ValueError:\n self._error(\"expected integer count\")\n\n self.elements.append((name, [], count, []))\n self._allowed = ['element', 'comment', 'property', 'end_header']\n\n def parse_property(self, data):\n properties = self.elements[-1][1]\n fields = data.strip().split()\n if len(fields) < 2:\n self._error(\"bad 'property' line\")\n\n if fields[0] == 'list':\n if len(fields) != 4:\n self._error(\"expected \\\"property list \"\n \"{len_type} {val_type} {name}\\\"\")\n\n try:\n properties.append(\n PlyListProperty(fields[3], fields[1], fields[2])\n )\n except ValueError as e:\n self._error(str(e))\n\n else:\n if len(fields) != 2:\n self._error(\"expected \\\"property {type} {name}\\\"\")\n\n try:\n properties.append(\n PlyProperty(fields[1], fields[0])\n )\n except ValueError as e:\n self._error(str(e))\n\n def parse_end_header(self, data):\n if data:\n self._error(\"unexpected data after 'end_header'\")\n self._allowed = []\n\n\nclass PlyParseError(Exception):\n\n '''\n Base class for PLY parsing errors.\n '''\n\n pass\n\n\nclass PlyElementParseError(PlyParseError):\n\n '''\n Raised when a PLY element cannot be parsed.\n The attributes `element', `row', `property', and `message' give\n additional information.\n '''\n\n def __init__(self, message, element=None, row=None, prop=None):\n self.message = message\n self.element = element\n self.row = row\n self.prop = prop\n\n s = ''\n if self.element:\n s += 'element %r: ' % self.element.name\n if self.row is not None:\n s += 'row %d: ' % self.row\n if self.prop:\n s += 'property %r: ' % self.prop.name\n s += self.message\n\n Exception.__init__(self, s)\n\n def __repr__(self):\n return ('%s(%r, element=%r, row=%r, prop=%r)' %\n (self.__class__.__name__,\n self.message, self.element, self.row, self.prop))\n\n\nclass PlyHeaderParseError(PlyParseError):\n\n '''\n Raised when a PLY header cannot be parsed.\n The attribute `line' provides additional information.\n '''\n\n def __init__(self, message, line=None):\n self.message = message\n self.line = line\n\n s = ''\n if self.line:\n s += 'line %r: ' % self.line\n s += self.message\n\n Exception.__init__(self, s)\n\n def __repr__(self):\n return ('%s(%r, line=%r)' %\n (self.__class__.__name__,\n self.message, self.line))\n\n\nclass PlyData(object):\n\n '''\n PLY file header and data.\n A PlyData instance is created in one of two ways: by the static\n method PlyData.read (to read a PLY file), or directly from __init__\n given a sequence of elements (which can then be written to a PLY\n file).\n '''\n\n def __init__(self, elements=[], text=False, byte_order='=',\n comments=[], obj_info=[]):\n '''\n elements: sequence of PlyElement instances.\n text: whether the resulting PLY file will be text (True) or\n binary (False).\n byte_order: '<' for little-endian, '>' for big-endian, or '='\n for native. This is only relevant if `text' is False.\n comments: sequence of strings that will be placed in the header\n between the 'ply' and 'format ...' lines.\n obj_info: like comments, but will be placed in the header with\n \"obj_info ...\" instead of \"comment ...\".\n '''\n if byte_order == '=' and not text:\n byte_order = _native_byte_order\n\n self.byte_order = byte_order\n self.text = text\n\n self.comments = comments\n self.obj_info = obj_info\n self.elements = elements\n\n def _get_elements(self):\n return self._elements\n\n def _set_elements(self, elements):\n self._elements = tuple(elements)\n self._index()\n\n elements = property(_get_elements, _set_elements)\n\n def _get_byte_order(self):\n return self._byte_order\n\n def _set_byte_order(self, byte_order):\n if byte_order not in ['<', '>', '=']:\n raise ValueError(\"byte order must be '<', '>', or '='\")\n\n self._byte_order = byte_order\n\n byte_order = property(_get_byte_order, _set_byte_order)\n\n def _index(self):\n self._element_lookup = dict((elt.name, elt) for elt in\n self._elements)\n if len(self._element_lookup) != len(self._elements):\n raise ValueError(\"two elements with same name\")\n\n def _get_comments(self):\n return list(self._comments)\n\n def _set_comments(self, comments):\n _check_comments(comments)\n self._comments = list(comments)\n\n comments = property(_get_comments, _set_comments)\n\n def _get_obj_info(self):\n return list(self._obj_info)\n\n def _set_obj_info(self, obj_info):\n _check_comments(obj_info)\n self._obj_info = list(obj_info)\n\n obj_info = property(_get_obj_info, _set_obj_info)\n\n @staticmethod\n def _parse_header(stream):\n '''\n Parse a PLY header from a readable file-like stream.\n '''\n parser = _PlyHeaderParser()\n while parser.consume(stream.readline()):\n pass\n\n return PlyData(\n [PlyElement(*e) for e in parser.elements],\n parser.format == 'ascii',\n _byte_order_map[parser.format],\n parser.comments,\n parser.obj_info\n )\n\n @staticmethod\n def read(stream):\n '''\n Read PLY data from a readable file-like object or filename.\n '''\n (must_close, stream) = _open_stream(stream, 'read')\n try:\n data = PlyData._parse_header(stream)\n for elt in data:\n elt._read(stream, data.text, data.byte_order)\n finally:\n if must_close:\n stream.close()\n\n return data\n\n def write(self, stream):\n '''\n Write PLY data to a writeable file-like object or filename.\n '''\n (must_close, stream) = _open_stream(stream, 'write')\n try:\n stream.write(self.header.encode('ascii'))\n stream.write(b'\\n')\n for elt in self:\n elt._write(stream, self.text, self.byte_order)\n finally:\n if must_close:\n stream.close()\n\n @property\n def header(self):\n '''\n Provide PLY-formatted metadata for the instance.\n '''\n lines = ['ply']\n\n if self.text:\n lines.append('format ascii 1.0')\n else:\n lines.append('format ' +\n _byte_order_reverse[self.byte_order] +\n ' 1.0')\n\n # Some information is lost here, since all comments are placed\n # between the 'format' line and the first element.\n for c in self.comments:\n lines.append('comment ' + c)\n\n for c in self.obj_info:\n lines.append('obj_info ' + c)\n\n lines.extend(elt.header for elt in self.elements)\n lines.append('end_header')\n return '\\n'.join(lines)\n\n def __iter__(self):\n return iter(self.elements)\n\n def __len__(self):\n return len(self.elements)\n\n def __contains__(self, name):\n return name in self._element_lookup\n\n def __getitem__(self, name):\n return self._element_lookup[name]\n\n def __str__(self):\n return self.header\n\n def __repr__(self):\n return ('PlyData(%r, text=%r, byte_order=%r, '\n 'comments=%r, obj_info=%r)' %\n (self.elements, self.text, self.byte_order,\n self.comments, self.obj_info))\n\n\ndef _open_stream(stream, read_or_write):\n if hasattr(stream, read_or_write):\n return (False, stream)\n try:\n return (True, open(stream, read_or_write[0] + 'b'))\n except TypeError:\n raise RuntimeError(\"expected open file or filename\")\n\n\nclass PlyElement(object):\n\n '''\n PLY file element.\n A client of this library doesn't normally need to instantiate this\n directly, so the following is only for the sake of documenting the\n internals.\n Creating a PlyElement instance is generally done in one of two ways:\n as a byproduct of PlyData.read (when reading a PLY file) and by\n PlyElement.describe (before writing a PLY file).\n '''\n\n def __init__(self, name, properties, count, comments=[]):\n '''\n This is not part of the public interface. The preferred methods\n of obtaining PlyElement instances are PlyData.read (to read from\n a file) and PlyElement.describe (to construct from a numpy\n array).\n '''\n _check_name(name)\n self._name = str(name)\n self._count = count\n\n self._properties = tuple(properties)\n self._index()\n\n self.comments = comments\n\n self._have_list = any(isinstance(p, PlyListProperty)\n for p in self.properties)\n\n @property\n def count(self):\n return self._count\n\n def _get_data(self):\n return self._data\n\n def _set_data(self, data):\n self._data = data\n self._count = len(data)\n self._check_sanity()\n\n data = property(_get_data, _set_data)\n\n def _check_sanity(self):\n for prop in self.properties:\n if prop.name not in self._data.dtype.fields:\n raise ValueError(\"dangling property %r\" % prop.name)\n\n def _get_properties(self):\n return self._properties\n\n def _set_properties(self, properties):\n self._properties = tuple(properties)\n self._check_sanity()\n self._index()\n\n properties = property(_get_properties, _set_properties)\n\n def _get_comments(self):\n return list(self._comments)\n\n def _set_comments(self, comments):\n _check_comments(comments)\n self._comments = list(comments)\n\n comments = property(_get_comments, _set_comments)\n\n def _index(self):\n self._property_lookup = dict((prop.name, prop)\n for prop in self._properties)\n if len(self._property_lookup) != len(self._properties):\n raise ValueError(\"two properties with same name\")\n\n def ply_property(self, name):\n return self._property_lookup[name]\n\n @property\n def name(self):\n return self._name\n\n def dtype(self, byte_order='='):\n '''\n Return the numpy dtype of the in-memory representation of the\n data. (If there are no list properties, and the PLY format is\n binary, then this also accurately describes the on-disk\n representation of the element.)\n '''\n return _np.dtype([(prop.name, prop.dtype(byte_order))\n for prop in self.properties])\n\n @staticmethod\n def describe(data, name, len_types={}, val_types={},\n comments=[]):\n '''\n Construct a PlyElement from an array's metadata.\n len_types and val_types can be given as mappings from list\n property names to type strings (like 'u1', 'f4', etc., or\n 'int8', 'float32', etc.). These can be used to define the length\n and value types of list properties. List property lengths\n always default to type 'u1' (8-bit unsigned integer), and value\n types default to 'i4' (32-bit integer).\n '''\n if not isinstance(data, _np.ndarray):\n raise TypeError(\"only numpy arrays are supported\")\n\n if len(data.shape) != 1:\n raise ValueError(\"only one-dimensional arrays are \"\n \"supported\")\n\n count = len(data)\n\n properties = []\n descr = data.dtype.descr\n\n for t in descr:\n if not isinstance(t[1], str):\n raise ValueError(\"nested records not supported\")\n\n if not t[0]:\n raise ValueError(\"field with empty name\")\n\n if len(t) != 2 or t[1][1] == 'O':\n # non-scalar field, which corresponds to a list\n # property in PLY.\n\n if t[1][1] == 'O':\n if len(t) != 2:\n raise ValueError(\"non-scalar object fields not \"\n \"supported\")\n\n len_str = _data_type_reverse[len_types.get(t[0], 'u1')]\n if t[1][1] == 'O':\n val_type = val_types.get(t[0], 'i4')\n val_str = _lookup_type(val_type)\n else:\n val_str = _lookup_type(t[1][1:])\n\n prop = PlyListProperty(t[0], len_str, val_str)\n else:\n val_str = _lookup_type(t[1][1:])\n prop = PlyProperty(t[0], val_str)\n\n properties.append(prop)\n\n elt = PlyElement(name, properties, count, comments)\n elt.data = data\n\n return elt\n\n def _read(self, stream, text, byte_order):\n '''\n Read the actual data from a PLY file.\n '''\n dtype = self.dtype(byte_order)\n if text:\n self._read_txt(stream)\n elif _can_mmap(stream) and not self._have_list:\n # Loading the data is straightforward. We will memory map\n # the file in copy-on-write mode.\n num_bytes = self.count * dtype.itemsize\n offset = stream.tell()\n stream.seek(0, 2)\n max_bytes = stream.tell() - offset\n if max_bytes < num_bytes:\n raise PlyElementParseError(\"early end-of-file\", self,\n max_bytes // dtype.itemsize)\n self._data = _np.memmap(stream, dtype,\n 'c', offset, self.count)\n # Fix stream position\n stream.seek(offset + self.count * dtype.itemsize)\n else:\n # A simple load is impossible.\n self._read_bin(stream, byte_order)\n\n self._check_sanity()\n\n def _write(self, stream, text, byte_order):\n '''\n Write the data to a PLY file.\n '''\n if text:\n self._write_txt(stream)\n else:\n if self._have_list:\n # There are list properties, so serialization is\n # slightly complicated.\n self._write_bin(stream, byte_order)\n else:\n # no list properties, so serialization is\n # straightforward.\n stream.write(self.data.astype(self.dtype(byte_order),\n copy=False).data)\n\n def _read_txt(self, stream):\n '''\n Load a PLY element from an ASCII-format PLY file. The element\n may contain list properties.\n '''\n self._data = _np.empty(self.count, dtype=self.dtype())\n\n k = 0\n for line in _islice(iter(stream.readline, b''), self.count):\n fields = iter(line.strip().split())\n for prop in self.properties:\n try:\n self._data[prop.name][k] = prop._from_fields(fields)\n except StopIteration:\n raise PlyElementParseError(\"early end-of-line\",\n self, k, prop)\n except ValueError:\n raise PlyElementParseError(\"malformed input\",\n self, k, prop)\n try:\n next(fields)\n except StopIteration:\n pass\n else:\n raise PlyElementParseError(\"expected end-of-line\",\n self, k)\n k += 1\n\n if k < self.count:\n del self._data\n raise PlyElementParseError(\"early end-of-file\", self, k)\n\n def _write_txt(self, stream):\n '''\n Save a PLY element to an ASCII-format PLY file. The element may\n contain list properties.\n '''\n for rec in self.data:\n fields = []\n for prop in self.properties:\n fields.extend(prop._to_fields(rec[prop.name]))\n\n _np.savetxt(stream, [fields], '%.18g', newline='\\n')\n\n def _read_bin(self, stream, byte_order):\n '''\n Load a PLY element from a binary PLY file. The element may\n contain list properties.\n '''\n self._data = _np.empty(self.count, dtype=self.dtype(byte_order))\n\n for k in _range(self.count):\n for prop in self.properties:\n try:\n self._data[prop.name][k] = \\\n prop._read_bin(stream, byte_order)\n except StopIteration:\n raise PlyElementParseError(\"early end-of-file\",\n self, k, prop)\n\n def _write_bin(self, stream, byte_order):\n '''\n Save a PLY element to a binary PLY file. The element may\n contain list properties.\n '''\n for rec in self.data:\n for prop in self.properties:\n prop._write_bin(rec[prop.name], stream, byte_order)\n\n @property\n def header(self):\n '''\n Format this element's metadata as it would appear in a PLY\n header.\n '''\n lines = ['element %s %d' % (self.name, self.count)]\n\n # Some information is lost here, since all comments are placed\n # between the 'element' line and the first property definition.\n for c in self.comments:\n lines.append('comment ' + c)\n\n lines.extend(list(map(str, self.properties)))\n\n return '\\n'.join(lines)\n\n def __getitem__(self, key):\n return self.data[key]\n\n def __setitem__(self, key, value):\n self.data[key] = value\n\n def __str__(self):\n return self.header\n\n def __repr__(self):\n return ('PlyElement(%r, %r, count=%d, comments=%r)' %\n (self.name, self.properties, self.count,\n self.comments))\n\n\ndef _check_comments(comments):\n for comment in comments:\n for char in comment:\n if not 0 <= ord(char) < 128:\n raise ValueError(\"non-ASCII character in comment\")\n if char == '\\n':\n raise ValueError(\"embedded newline in comment\")\n\n\nclass PlyProperty(object):\n\n '''\n PLY property description. This class is pure metadata; the data\n itself is contained in PlyElement instances.\n '''\n\n def __init__(self, name, val_dtype):\n _check_name(name)\n self._name = str(name)\n self.val_dtype = val_dtype\n\n def _get_val_dtype(self):\n return self._val_dtype\n\n def _set_val_dtype(self, val_dtype):\n self._val_dtype = _data_types[_lookup_type(val_dtype)]\n\n val_dtype = property(_get_val_dtype, _set_val_dtype)\n\n @property\n def name(self):\n return self._name\n\n def dtype(self, byte_order='='):\n '''\n Return the numpy dtype description for this property (as a tuple\n of strings).\n '''\n return byte_order + self.val_dtype\n\n def _from_fields(self, fields):\n '''\n Parse from generator. Raise StopIteration if the property could\n not be read.\n '''\n return _np.dtype(self.dtype()).type(next(fields))\n\n def _to_fields(self, data):\n '''\n Return generator over one item.\n '''\n yield _np.dtype(self.dtype()).type(data)\n\n def _read_bin(self, stream, byte_order):\n '''\n Read data from a binary stream. Raise StopIteration if the\n property could not be read.\n '''\n try:\n return _read_array(stream, self.dtype(byte_order), 1)[0]\n except IndexError:\n raise StopIteration\n\n def _write_bin(self, data, stream, byte_order):\n '''\n Write data to a binary stream.\n '''\n _write_array(stream, _np.dtype(self.dtype(byte_order)).type(data))\n\n def __str__(self):\n val_str = _data_type_reverse[self.val_dtype]\n return 'property %s %s' % (val_str, self.name)\n\n def __repr__(self):\n return 'PlyProperty(%r, %r)' % (self.name,\n _lookup_type(self.val_dtype))\n\n\nclass PlyListProperty(PlyProperty):\n\n '''\n PLY list property description.\n '''\n\n def __init__(self, name, len_dtype, val_dtype):\n PlyProperty.__init__(self, name, val_dtype)\n\n self.len_dtype = len_dtype\n\n def _get_len_dtype(self):\n return self._len_dtype\n\n def _set_len_dtype(self, len_dtype):\n self._len_dtype = _data_types[_lookup_type(len_dtype)]\n\n len_dtype = property(_get_len_dtype, _set_len_dtype)\n\n def dtype(self, byte_order='='):\n '''\n List properties always have a numpy dtype of \"object\".\n '''\n return '|O'\n\n def list_dtype(self, byte_order='='):\n '''\n Return the pair (len_dtype, val_dtype) (both numpy-friendly\n strings).\n '''\n return (byte_order + self.len_dtype,\n byte_order + self.val_dtype)\n\n def _from_fields(self, fields):\n (len_t, val_t) = self.list_dtype()\n\n n = int(_np.dtype(len_t).type(next(fields)))\n\n data = _np.loadtxt(list(_islice(fields, n)), val_t, ndmin=1)\n if len(data) < n:\n raise StopIteration\n\n return data\n\n def _to_fields(self, data):\n '''\n Return generator over the (numerical) PLY representation of the\n list data (length followed by actual data).\n '''\n (len_t, val_t) = self.list_dtype()\n\n data = _np.asarray(data, dtype=val_t).ravel()\n\n yield _np.dtype(len_t).type(data.size)\n for x in data:\n yield x\n\n def _read_bin(self, stream, byte_order):\n (len_t, val_t) = self.list_dtype(byte_order)\n\n try:\n n = _read_array(stream, _np.dtype(len_t), 1)[0]\n except IndexError:\n raise StopIteration\n\n data = _read_array(stream, _np.dtype(val_t), n)\n if len(data) < n:\n raise StopIteration\n\n return data\n\n def _write_bin(self, data, stream, byte_order):\n '''\n Write data to a binary stream.\n '''\n (len_t, val_t) = self.list_dtype(byte_order)\n\n data = _np.asarray(data, dtype=val_t).ravel()\n\n _write_array(stream, _np.array(data.size, dtype=len_t))\n _write_array(stream, data)\n\n def __str__(self):\n len_str = _data_type_reverse[self.len_dtype]\n val_str = _data_type_reverse[self.val_dtype]\n return 'property list %s %s %s' % (len_str, val_str, self.name)\n\n def __repr__(self):\n return ('PlyListProperty(%r, %r, %r)' %\n (self.name,\n _lookup_type(self.len_dtype),\n _lookup_type(self.val_dtype)))\n\n\ndef _check_name(name):\n for char in name:\n if not 0 <= ord(char) < 128:\n raise ValueError(\"non-ASCII character in name %r\" % name)\n if char.isspace():\n raise ValueError(\"space character(s) in name %r\" % name)\n\n\ndef _read_array(stream, dtype, n):\n try:\n size = int(_np.dtype(dtype).itemsize * n)\n return _np.frombuffer(stream.read(size), dtype)\n except Exception:\n raise StopIteration\n\n\ndef _write_array(stream, array):\n stream.write(array.tostring())\n\n\ndef _can_mmap(stream):\n try:\n pos = stream.tell()\n try:\n _np.memmap(stream, 'u1', 'c')\n stream.seek(pos)\n return True\n except Exception as e:\n stream.seek(pos)\n return False\n except Exception as e:\n return False\n" ]
[ [ "numpy.asarray", "numpy.vstack", "numpy.memmap", "numpy.dtype", "numpy.savetxt", "numpy.array", "numpy.empty" ] ]
MarmerMax/Gender-Recognizer
[ "9f11c3486442ac5661a698729b99483ead244686" ]
[ "NN.py" ]
[ "from os import walk\nimport os\nfrom python_speech_features import mfcc\nimport scipy.io.wavfile as wav\nimport tensorflow as tf\nimport numpy as np\n\ndef prepare_data(path):\n x = np.empty((0, 13), float)\n y = np.empty((0, 1), int)\n for (dirpath, dirnames, filenames) in walk(path):\n for filename in filenames:\n f = os.path.basename(dirpath)\n if f == \"male\":\n a = np.array([[0]])\n y = np.vstack([y, a])\n else:\n a = np.array([[1]])\n y = np.vstack([y, a])\n (rate, sig) = wav.read(dirpath + \"\\\\\" + filename)\n mfcc_feat = mfcc(sig, rate)\n mfcc_acc = np.mean(mfcc_feat, 0)\n features = np.reshape(mfcc_acc, 13)\n x = np.vstack([x, features])\n return x, y\n\n\ndef logistic_fun(z):\n return 1 / (1.0 + np.exp(-z))\n\ndef test(path):\n really_female = 0\n really_male = 0\n classified_female = 0\n classified_male = 0\n really_and_class_female = 0\n really_and_class_male = 0\n for (dirpath, dirnames, filenames) in walk(path):\n for filename in filenames:\n f = os.path.basename(dirpath)\n if f == \"female\":\n really_female = really_female+1\n if f == \"male\":\n really_male = really_male+1\n (rate, sig) = wav.read(dirpath + \"\\\\\" + filename)\n mfcc_feat = mfcc(sig, rate)\n mfcc_acc = np.mean(mfcc_feat, 0)\n features = np.reshape(mfcc_acc, 13)\n prediction = y.eval(session=sess, feed_dict={x: [features]})[0][0]\n if prediction > 0.5:\n classified_female = classified_female+1\n if f == 'female':\n really_and_class_female = really_and_class_female+1\n else:\n classified_male = classified_male+1\n if f == 'male':\n really_and_class_male = really_and_class_male+1\n print('ReallyFemale: %d ReallyMale: %d ClassifiedFemale %d ClassifiedMale: %d RealyAndClassFemale: %d RealyAndClassMale: %d' %\n (really_female, really_male, classified_female, classified_male, really_and_class_female, really_and_class_male))\n\n\nfeatures = 13\n(hidden1_size, hidden2_size, hidden3_size, hidden4_size) = (70, 100, 60, 30)\nx = tf.placeholder(tf.float32, [None, features])\ny_ = tf.placeholder(tf.float32, [None, 1])\nW1 = tf.Variable(tf.truncated_normal([features, hidden1_size], stddev=0.1))\nb1 = tf.Variable(tf.constant(0.1, shape=[hidden1_size]))\nz1 = tf.nn.relu(tf.matmul(x, W1)+b1)\nW2 = tf.Variable(tf.truncated_normal([hidden1_size, 1], stddev=0.1))\nb2 = tf.Variable(tf.constant(0.1, shape=[hidden2_size]))\nz2 = tf.nn.relu(tf.matmul(z1, W2)+b2)\nW3 = tf.Variable(tf.truncated_normal([hidden2_size, hidden3_size], stddev=0.1))\nb3 = tf.Variable(tf.constant(0.1, shape=[hidden3_size]))\nz3 = tf.nn.relu(tf.matmul(z2, W3)+b3)\nW4 = tf.Variable(tf.truncated_normal([hidden3_size, hidden4_size], stddev=0.1))\nb4 = tf.Variable(tf.constant(0.1, shape=[hidden4_size]))\nz4 = tf.nn.relu(tf.matmul(z3, W4)+b4)\nW5 = tf.Variable(tf.truncated_normal([hidden4_size, 1], stddev=0.1))\nb5 = tf.Variable(0.)\n\ny = tf.nn.sigmoid(tf.matmul(z4, W5)+b5)\nloss1 = tf.nn.sigmoid_cross_entropy_with_logits(labels=y_, logits=y)\nloss = tf.reduce_mean(loss1)\nupdate = tf.train.GradientDescentOptimizer(0.001).minimize(loss)\n\nsource = \"C:\\\\Users\\\\caron\\\\Desktop\\\\vo\\\\train\"\n\ndata_x, data_y = prepare_data(source)\n\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\nfor i in range(0, 10000):\n sess.run(update, feed_dict={x: data_x, y_: data_y})\n if i % 1000 == 0:\n print('Iteration:', i, ' W5:', sess.run(W5), ' b5:', sess.run(b5), ' loss:',\n loss.eval(session=sess, feed_dict={x: data_x, y_: data_y}))\n\n\ntest(\"C:\\\\Users\\\\caron\\\\Desktop\\\\vo\\\\test\")\n" ]
[ [ "tensorflow.matmul", "tensorflow.truncated_normal", "tensorflow.constant", "tensorflow.Variable", "tensorflow.reduce_mean", "numpy.reshape", "numpy.vstack", "tensorflow.placeholder", "tensorflow.nn.sigmoid_cross_entropy_with_logits", "tensorflow.global_variables_initializer", "tensorflow.train.GradientDescentOptimizer", "numpy.mean", "tensorflow.Session", "numpy.array", "numpy.exp", "scipy.io.wavfile.read", "numpy.empty" ] ]
muazhari/Poset-Lattice
[ "962c77ee896dba670baca4d0fb29f8c4366ed7a2" ]
[ "poset_lattice.py" ]
[ "'''\nNeed improvement from the code and knowledge is used to built this.\nSorry for the readableness and the quality of code not as your expectation.\n'''\n\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom itertools import combinations\n\n\n# return GCD from pair of nums by modulating the nums iteratively.\ndef gcd(a, b):\n while b > 0:\n a, b = b, a % b\n return a\n\n\ndef lcm(a, b):\n return a * b / gcd(a, b)\n\n\ndef unique(seq):\n seen = {}\n pos = 0\n for item in seq:\n if item not in seen:\n seen[item] = True\n seq[pos] = item\n pos += 1\n del seq[pos:]\n\n\n# Parent class, define and relationing input of a set.\nclass definerSet:\n def __init__(self, setInput):\n self.raw = setInput\n self.raw.sort()\n self.rawCombs = [x for x in combinations(self.raw, 2)]\n self.relation = list()\n self.rTypes = {0: \"Divisible\"}\n self.rChosen = None\n self.isPoset = None\n self.isLattice = None\n\n self.hasse = hasse(definerSet=self)\n\n # Generate pair of divisible relation from Input.\n def rDivisible(self):\n self.rChosen = 0\n unique(self.raw)\n\n self.relation = [(divisor, num)\n for divisor in self.raw\n for num in self.raw\n if num % divisor == 0]\n\n def rWhat(self):\n return self.rTypes[self.rChosen]\n\n # For not directly pointing to private variable.\n def getter(self, fromVar):\n return fromVar\n\n\n# Subclass, to do hasse things.\nclass hasse:\n def __init__(self, definerSet):\n self.definerSet = definerSet\n self.hDiagram = nx.DiGraph()\n\n self.sortOut = sortOut(hasse=self)\n\n def Sortedf(self):\n return self.sortOut.degreeOut()\n\n # Draw hasse diagram by rules.\n def draw(self):\n assert self.definerSet.isPoset is True\n self.hDiagram.add_edges_from(self.sortOut.degreeOut())\n\n print('Sorry too slow,')\n\n if self.definerSet.isLattice is True:\n iLattie = \"Lattice\"\n elif self.definerSet.isLattice is False:\n iLattie = \"Not a Lattice\"\n\n type = '{} Hasse Digram [{}]'.format(iLattie, self.definerSet.rWhat())\n plt.title(type)\n\n # pos = nx.circular_layout(h)\n pos = nx.spring_layout(self.hDiagram)\n nx.draw(self.hDiagram,\n pos,\n with_labels=True,\n node_color='r',\n edge_labels=True)\n\n plt.show()\n\n\n# Subclass of hasse, Sorting wrapper.\nclass sortOut(hasse):\n def __init__(self, hasse):\n self.hasse = hasse\n\n # Compare its own without reflective pair.\n @staticmethod\n def ruleR(from_set, target_set):\n for (a, b), (c, d) in combinations(from_set, 2):\n if a != b and c != d:\n if all(r in target_set for r in ((a, b), (c, d), (b, d))):\n yield (a, b, c, d)\n\n\n # Remove unneeded transitive pair\n # if b ≤ d and no p ∈ rule1 so that b ≤ p and p ≤ d.\n def ruleOut(self):\n rule = self.hasse.definerSet.getter(self.hasse.definerSet.relation)\n\n for a, b, c, d in sortOut.ruleR(self.hasse.definerSet.relation, rule):\n if a == c:\n rule.remove((c, d))\n\n return rule\n\n # Choose the most lower degree if 0 ≤ a and 0 ≤ c.\n def degreeOut(self):\n '''\n This loop has a bug if the same count of degree arise,\n I don't have reliable knowledge to do it right,\n Sorry, and I really appreciate if someone could fix it.\n '''\n\n rule1 = rule2 = self.ruleOut()\n count_a = count_c = 0\n\n for a, b, c, d in sortOut.ruleR(rule1, rule2):\n if b == d:\n for i, j in rule2:\n if i == a:\n count_a += 1\n elif i == c:\n count_c += 1\n\n if count_a > count_c:\n rule2.remove((a, b))\n elif count_c > count_a:\n rule2.remove((c, d))\n\n # Need a fix.\n elif (count_a + count_c) != 4 and count_a == count_c:\n if a > c:\n rule2.remove((c, d))\n elif c > a:\n rule2.remove((a, b))\n\n count_a = count_c = 0\n\n # print('rule1', rule1)\n # print('rule2', rule2)\n return rule2\n\n\n# Subclass, to do poset things.\nclass poset(definerSet):\n def __init__(self, definerSet):\n self.definerSet = definerSet\n\n self.laws = {'Reflective': self.reflective(),\n 'Antisimetric': self.antisimetric(),\n 'Transitive': self.transitive()}\n\n self.definerSet.isPoset = self.isItPoset()\n\n self.bounds = bounds(poset=self)\n\n def getter(self, fromVar):\n return fromVar\n\n def __repr__(self):\n if self.Poset is False:\n return(\"Not a Poset.\")\n\n # Return True if every pair of element ∈ self.definerSet.raw reflective.\n def reflective(self, rlist=False):\n aRa = [a for a, b in self.definerSet.relation if a == b]\n\n if rlist is True:\n return aRa\n\n if len(aRa) == len(self.definerSet.raw):\n return True\n else:\n return False\n\n # Return True if atleast has a pair by if aRb and cRd, a = b and b = c.\n def antisimetric(self, rlist=False):\n aRb = [(a, c) for a, b in self.definerSet.relation\n for c, d in self.definerSet.relation\n if a == d and b == c]\n\n if rlist is True:\n return aRb\n\n if len(aRb) > 0:\n return True\n else:\n return False\n\n # Return True if aRb and cRd, b = c,\n # so that aRc, in every pair of element ∈ self.definerSet.raw.\n def transitive(self, rlist=False):\n for a, b in self.definerSet.relation:\n for c, d in self.definerSet.relation:\n if b == c:\n if ((a, d) not in self.definerSet.relation):\n print('For', (a, d), 'from', (a, b),\n 'and', (c, d), 'not in Set.')\n return False\n\n if rlist is True:\n return self.definerSet.relation\n\n return True\n\n # True if all of 3 laws are True.\n def isItPoset(self):\n if all(self.laws.values()):\n return True\n else:\n return False\n\n# Subclass of poset, infimum & supremum wrapper.\nclass bounds(poset):\n '''\n Algorithm too slow, is there any efficient way or formula to do it?\n Bug arise when comparing transitive relations that should not be is.\n '''\n def __init__(self, poset):\n self.poset = poset\n self.definerSet = self.poset.definerSet\n\n def comBs(self, a, b):\n for (i, j), (k, l) in combinations(self.definerSet.relation, 2):\n yield i, j, k, l\n\n # Supremum, yield true when j is the most closer to a and b while exist in self.definerSet.raw.\n def _leastUpper(self):\n for a, b in self.definerSet.rawCombs:\n last = None\n for i, j, k, l in self.comBs(a, b):\n if i == a and k == b:\n if j == l:\n last = True\n yield last\n break\n if last is not True:\n yield False\n\n #Return j, For each X that is another upper bound of (a, b), applies j ≤ X.\n def leastUpper(self, compara=None):\n if compara is None:\n return self._leastUpper()\n\n elif compara is not None:\n for a, b in [compara]:\n for i, j, k, l in self.comBs(a, b):\n if i == a and k == b:\n if j == l:\n return j\n return None\n\n # Infimum, yield true when j is the most closer to a and b while exist in self.definerSet.raw.\n def _greatestLower(self):\n for a, b in self.definerSet.rawCombs:\n last = None\n for i, j, k, l in self.comBs(a, b):\n if j == a and l == b:\n if i == k:\n last = True\n yield last\n break\n if last is not True:\n yield False\n\n #Return i, For each X that is another lower bound of (a, b), applies X ≤ i.\n def greatestLower(self, compara=None):\n if compara is None:\n return self._greatestLower()\n elif compara is not None:\n for a, b in [compara]:\n for i, j, k, l in self.comBs(a, b):\n if j == a and l == b:\n if i == k:\n return i\n return None\n\n\n# Subclass, to do lattice things. for now, only support divisible lattice.\nclass lattice(poset):\n def __init__(self, poset):\n self.poset = poset\n self.definerSet = self.poset.definerSet\n self.definerSet.isLattice = self.isItLattice()\n self.irreducible = irreducible(lattice=self)\n if self.definerSet.isLattice is False:\n print(\"This Works should be Lattice Only.\")\n\n def __repr__(self):\n if self.definerSet.isLattice is False:\n return(\"Not a Lattice.\")\n\n # infimum(a,b) and supremum (a,b) of self.poset is exist for each pair of elements a and b in self.definerSet.raw.\n def isItLattice(self):\n if all(self.poset.bounds.leastUpper()) and all(self.poset.bounds.greatestLower()):\n return True\n else:\n return False\n\n # Compare by its own lcm and gcd if match to the smallest & biggest element.\n def complement(self, arg=None):\n complements = []\n if arg is not None:\n for a in self.definerSet.raw:\n if lcm(a, arg) == self.definerSet.raw[-1] and gcd(a, arg) == self.definerSet.raw[0]:\n return True\n\n return False\n\n elif arg is None:\n for a, b in self.definerSet.rawCombs:\n if lcm(a, b) == self.definerSet.raw[-1] and gcd(a, b) == self.definerSet.raw[0]:\n complements.append((a, b))\n\n return complements\n\n\n# Compare gcd & lcm to find meet irreducible and join irreducible.\nclass irreducible(lattice):\n def __init__(self, lattice):\n self.lattice = lattice\n self.definerSet = self.lattice.definerSet\n\n def meet(self, arg):\n for a, b in self.definerSet.rawCombs:\n if gcd(a, b) in (a, b):\n if arg in (a, b):\n return True\n return False\n\n def join(self, arg):\n for a, b in self.definerSet.rawCombs:\n if lcm(a, b) in (a, b):\n if arg in (a, b):\n return True\n return False\n" ]
[ [ "matplotlib.pyplot.show", "matplotlib.pyplot.title" ] ]
1483795887/ubiquant_danet
[ "fd63de3aad527aca93c1eb7aa34c9e833dceb3bd" ]
[ "DAN_Task.py" ]
[ "import torch\nimport numpy as np\nfrom scipy.special import softmax\nfrom lib.utils import PredictDataset\nfrom abstract_model import DANsModel\nfrom lib.multiclass_utils import infer_output_dim, check_output_dim\nfrom torch.utils.data import DataLoader\nfrom torch.nn.functional import cross_entropy, mse_loss\n\nclass DANetClassifier(DANsModel):\n def __post_init__(self):\n super(DANetClassifier, self).__post_init__()\n self._task = 'classification'\n self._default_loss = cross_entropy\n self._default_metric = 'accuracy'\n\n def weight_updater(self, weights):\n \"\"\"\n Updates weights dictionary according to target_mapper.\n\n Parameters\n ----------\n weights : bool or dict\n Given weights for balancing training.\n\n Returns\n -------\n bool or dict\n Same bool if weights are bool, updated dict otherwise.\n\n \"\"\"\n if isinstance(weights, int):\n return weights\n elif isinstance(weights, dict):\n return {self.target_mapper[key]: value for key, value in weights.items()}\n else:\n return weights\n\n def prepare_target(self, y):\n return np.vectorize(self.target_mapper.get)(y)\n\n def compute_loss(self, y_pred, y_true):\n return self.loss_fn(y_pred, y_true.long())\n\n def update_fit_params(\n self,\n X_train,\n y_train,\n eval_set\n ):\n output_dim, train_labels = infer_output_dim(y_train)\n for X, y in eval_set:\n check_output_dim(train_labels, y)\n self.output_dim = output_dim\n self._default_metric = 'accuracy'\n self.classes_ = train_labels\n self.target_mapper = {class_label: index for index, class_label in enumerate(self.classes_)}\n self.preds_mapper = {str(index): class_label for index, class_label in enumerate(self.classes_)}\n\n def stack_batches(self, list_y_true, list_y_score):\n y_true = np.hstack(list_y_true)\n y_score = np.vstack(list_y_score)\n y_score = softmax(y_score, axis=1)\n return y_true, y_score\n\n def predict_func(self, outputs):\n outputs = np.argmax(outputs, axis=1)\n return outputs\n\n def predict_proba(self, X):\n \"\"\"\n Make predictions for classification on a batch (valid)\n\n Parameters\n ----------\n X : a :tensor: `torch.Tensor`\n Input data\n\n Returns\n -------\n res : np.ndarray\n\n \"\"\"\n self.network.eval()\n\n dataloader = DataLoader(\n PredictDataset(X),\n batch_size=1024,\n shuffle=False,\n )\n\n results = []\n for batch_nb, data in enumerate(dataloader):\n data = data.to(self.device).float()\n output = self.network(data)\n predictions = torch.nn.Softmax(dim=1)(output).cpu().detach().numpy()\n results.append(predictions)\n res = np.vstack(results)\n return res\n\n\nclass DANetRegressor(DANsModel):\n def __post_init__(self):\n super(DANetRegressor, self).__post_init__()\n self._task = 'regression'\n self._default_loss = mse_loss\n self._default_metric = 'mse'\n\n def prepare_target(self, y):\n return y\n\n def compute_loss(self, y_pred, y_true):\n return self.loss_fn(y_pred, y_true)\n\n def update_fit_params(\n self,\n X_train,\n y_train,\n eval_set\n ):\n if len(y_train.shape) != 2:\n msg = \"Targets should be 2D : (n_samples, n_regression) \" + \\\n f\"but y_train.shape={y_train.shape} given.\\n\" + \\\n \"Use reshape(-1, 1) for single regression.\"\n raise ValueError(msg)\n self.output_dim = y_train.shape[1]\n self.preds_mapper = None\n\n\n def predict_func(self, outputs):\n return outputs\n\n def stack_batches(self, list_y_true, list_y_score):\n y_true = np.vstack(list_y_true)\n y_score = np.vstack(list_y_score)\n return y_true, y_score\n" ]
[ [ "numpy.hstack", "torch.nn.Softmax", "numpy.argmax", "numpy.vectorize", "scipy.special.softmax", "numpy.vstack" ] ]
YoshiRi/ImRegPOC
[ "97025b68979cb043fc359731886a0a62333d6f09" ]
[ "python_package/Tests/PhaseCorrelation.py" ]
[ "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n''' Phase Correlation based image matching and registration libraries\n'''\n__author__ = \"Yoshi Ri\"\n__copyright__ = \"Copyright 2017, The University of Tokyo\"\n__credits__ = [\"Yoshi Ri\"]\n__license__ = \"BSD\"\n__version__ = \"1.0.1\"\n__maintainer__ = \"Yoshi Ri\"\n__email__ = \"[email protected]\"\n__status__ = \"Production\"\n\n# Code Begins from Here\n \nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt # matplotlibの描画系\nimport math\n\n# Get peak point\ndef CenterOfGravity(mat):\n hei,wid = mat.shape\n Tile=np.arange(wid,dtype=float)-(wid-1.0)/2.0\n Tx = np.tile(Tile,[hei,1]) # Ty = Tx.T\n Sum = np.sum(mat)\n #print(mat)\n Ax = np.sum(mat*Tx)/Sum\n Ay = np.sum(mat*Tx.T)/Sum\n return [Ay,Ax]\n\n# Weighted Center Of Gravity\ndef WeightedCOG(mat):\n if mat.size == 0:\n print(\"Skip subpixel estimation!\")\n Res = [0,0]\n else:\n peak = mat.max()\n newmat = mat*(mat>peak/10)\n Res = CenterOfGravity(newmat)\n return Res\n\n# Phase Correlation\ndef PhaseCorrelation(a, b):\n height,width = a.shape\n #dt = a.dtype # data type\n # Windowing\n hann_ = cv2.createHanningWindow((height, width),cv2.CV_64F)\n #hann = hann_.astype(dt) # convert to correspoinding dtype\n rhann = np.sqrt(hann_)\n rhann = hann_\n\n # FFT\n G_a = np.fft.fft2(a*rhann)\n G_b = np.fft.fft2(b*rhann)\n conj_b = np.ma.conjugate(G_b)\n R = G_a*conj_b\n R /= np.absolute(R)\n r = np.fft.fftshift(np.fft.ifft2(R).real)\n # Get result and Interpolation\n DY,DX = np.unravel_index(r.argmax(), r.shape)\n # Subpixel Accuracy\n boxsize = 5\n box = r[DY-int((boxsize-1)/2):DY+int((boxsize-1)/2)+1,DX-int((boxsize-1)/2):DX+int((boxsize-1)/2)+1] # x times x box\n #TY,TX= CenterOfGravity(box)\n TY,TX= WeightedCOG(box)\n sDY = TY+DY\n sDX = TX+DX\n # Show the result\n # print('DX=',width/2-sDX,'DY=',height/2-sDY)\n # print('CorrelationVal=',r[DY,DX])\n plt.imshow(r,vmin=r.min(), vmax=r.max())\n return [width/2-sDX,height/2-sDY],r[DY,DX]\n" ]
[ [ "numpy.fft.fft2", "numpy.absolute", "numpy.fft.ifft2", "numpy.sqrt", "numpy.arange", "numpy.tile", "numpy.ma.conjugate", "numpy.sum" ] ]
daniel616/DL
[ "b62087bb86bcfa4cdaa692bb0ae724d416761de3" ]
[ "mmdet/models/backbones/vgg.py" ]
[ "import logging\n\nimport torch.nn as nn\n\nfrom mmcv.cnn.weight_init import constant_init, normal_init, kaiming_init\nfrom mmcv.runner import load_checkpoint\n\n\nfrom ..registry import BACKBONES\n\ndef conv3x3(in_planes, out_planes, dilation=1):\n \"3x3 convolution with padding\"\n return nn.Conv2d(\n in_planes,\n out_planes,\n kernel_size=3,\n padding=dilation,\n dilation=dilation)\n\n\ndef make_vgg_layer(inplanes, planes, num_blocks, dilation=1, with_bn=False,\n ceil_mode=False):\n layers = []\n for _ in range(num_blocks):\n layers.append(conv3x3(inplanes, planes, dilation))\n if with_bn:\n layers.append(nn.BatchNorm2d(planes))\n layers.append(nn.ReLU(inplace=True))\n inplanes = planes\n layers.append(nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=ceil_mode))\n\n return layers\n\[email protected]_module\nclass VGG(nn.Module):\n \"\"\"VGG backbone.\n\n Args:\n depth (int): Depth of vgg, from {11, 13, 16, 19}.\n with_bn (bool): Use BatchNorm or not.\n num_classes (int): number of classes for classification.\n num_stages (int): VGG stages, normally 5.\n dilations (Sequence[int]): Dilation of each stage.\n out_indices (Sequence[int]): Output from which stages.\n frozen_stages (int): Stages to be frozen (all param fixed). -1 means\n not freezing any parameters.\n bn_eval (bool): Whether to set BN layers as eval mode, namely, freeze\n running stats (mean and var).\n bn_frozen (bool): Whether to freeze weight and bias of BN layers.\n \"\"\"\n\n arch_settings = {\n 11: (1, 1, 2, 2, 2),\n 13: (2, 2, 2, 2, 2),\n 16: (2, 2, 3, 3, 3),\n 19: (2, 2, 4, 4, 4)\n }\n\n def __init__(self,\n depth,\n with_bn=False,\n num_classes=-1,\n num_stages=5,\n dilations=(1, 1, 1, 1, 1),\n out_indices=(0, 1, 2, 3, 4),\n frozen_stages=-1,\n bn_eval=True,\n bn_frozen=False,\n ceil_mode=False,\n with_last_pool=True):\n super(VGG, self).__init__()\n if depth not in self.arch_settings:\n raise KeyError('invalid depth {} for vgg'.format(depth))\n assert num_stages >= 1 and num_stages <= 5\n stage_blocks = self.arch_settings[depth]\n self.stage_blocks = stage_blocks[:num_stages]\n assert len(dilations) == num_stages\n assert max(out_indices) <= num_stages\n\n self.num_classes = num_classes\n self.out_indices = out_indices\n self.frozen_stages = frozen_stages\n self.bn_eval = bn_eval\n self.bn_frozen = bn_frozen\n\n self.inplanes = 3\n start_idx = 0\n vgg_layers = []\n self.range_sub_modules = []\n for i, num_blocks in enumerate(self.stage_blocks):\n num_modules = num_blocks * (2 + with_bn) + 1\n end_idx = start_idx + num_modules\n dilation = dilations[i]\n planes = 64 * 2**i if i < 4 else 512\n vgg_layer = make_vgg_layer(\n self.inplanes,\n planes,\n num_blocks,\n dilation=dilation,\n with_bn=with_bn,\n ceil_mode=ceil_mode)\n vgg_layers.extend(vgg_layer)\n self.inplanes = planes\n self.range_sub_modules.append([start_idx, end_idx])\n start_idx = end_idx\n if not with_last_pool:\n vgg_layers.pop(-1)\n self.module_name = 'features'\n self.add_module(self.module_name, nn.Sequential(*vgg_layers))\n\n if self.num_classes > 0:\n self.classifier = nn.Sequential(\n nn.Linear(512 * 7 * 7, 4096),\n nn.ReLU(True),\n nn.Dropout(),\n nn.Linear(4096, 4096),\n nn.ReLU(True),\n nn.Dropout(),\n nn.Linear(4096, num_classes),\n )\n\n def init_weights(self, pretrained=None):\n if isinstance(pretrained, str):\n logger = logging.getLogger()\n load_checkpoint(self, pretrained, strict=False, logger=logger)\n elif pretrained is None:\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n kaiming_init(m)\n elif isinstance(m, nn.BatchNorm2d):\n constant_init(m, 1)\n elif isinstance(m, nn.Linear):\n normal_init(m, std=0.01)\n else:\n raise TypeError('pretrained must be a str or None')\n\n def forward(self, x):\n outs = []\n vgg_layers = getattr(self, self.module_name)\n for i, num_blocks in enumerate(self.stage_blocks):\n for j in range(*self.range_sub_modules[i]):\n vgg_layer = vgg_layers[j]\n x = vgg_layer(x)\n if i in self.out_indices:\n outs.append(x)\n if self.num_classes > 0:\n x = x.view(x.size(0), -1)\n x = self.classifier(x)\n outs.append(x)\n if len(outs) == 1:\n return outs[0]\n else:\n return tuple(outs)\n\n def train(self, mode=True):\n super(VGG, self).train(mode)\n if self.bn_eval:\n for m in self.modules():\n if isinstance(m, nn.BatchNorm2d):\n m.eval()\n if self.bn_frozen:\n for params in m.parameters():\n params.requires_grad = False\n vgg_layers = getattr(self, self.module_name)\n if mode and self.frozen_stages >= 0:\n for i in range(self.frozen_stages):\n for j in range(*self.range_sub_modules[i]):\n mod = vgg_layers[j]\n mod.eval()\n for param in mod.parameters():\n param.requires_grad = False\n" ]
[ [ "torch.nn.Sequential", "torch.nn.Dropout", "torch.nn.Conv2d", "torch.nn.MaxPool2d", "torch.nn.Linear", "torch.nn.BatchNorm2d", "torch.nn.ReLU" ] ]
boostcampaitech2/model-optimization-level3-cv-07
[ "952a2fc6902a62eee602bc4f823d3bddfe7a792b" ]
[ "inference_obtu.py" ]
[ "\"\"\"Example code for submit.\n\n- Author: Junghoon Kim, Jongkuk Lim\n- Contact: [email protected], [email protected]\n\"\"\"\nimport argparse\nimport json\nimport os\nimport time\nfrom datetime import datetime\n\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torchvision.datasets import ImageFolder\nfrom torchvision.transforms import Resize\nfrom tqdm import tqdm\n\nfrom src.augmentation.policies import simple_augment_test\nfrom src.model import Model\nfrom src.utils.common import read_yaml\n\nif torch.__version__ >= \"1.8.1\":\n from torch import profiler\nelse:\n from torch.autograd import profiler\n\nCLASSES = [\n \"Metal\",\n \"Paper\",\n \"Paperpack\",\n \"Plastic\",\n \"Plasticbag\",\n \"Styrofoam\",\n]\n\n\nclass CustomImageFolder(ImageFolder):\n \"\"\"ImageFolder with filename.\"\"\"\n\n def __getitem__(self, index):\n img_gt = super(CustomImageFolder, self).__getitem__(index)\n fdir = self.imgs[index][0]\n fname = fdir.rsplit(os.path.sep, 1)[-1]\n return img_gt + (fname,)\n\n\ndef get_dataloader(img_root: str, data_config: str) -> DataLoader:\n \"\"\"Get dataloader.\n\n Note:\n Don't forget to set normalization.\n \"\"\"\n # Load yaml\n data_config = read_yaml(data_config)\n\n transform_test_args = (\n data_confg[\"AUG_TEST_PARAMS\"] if data_config.get(\"AUG_TEST_PARAMS\") else None\n )\n # Transformation for test\n transform_test = getattr(\n __import__(\"src.augmentation.policies\", fromlist=[\"\"]),\n data_config[\"AUG_TEST\"],\n )(dataset=data_config[\"DATASET\"], img_size=data_config[\"IMG_SIZE\"])\n\n dataset = CustomImageFolder(root=img_root, transform=transform_test)\n dataloader = DataLoader(dataset=dataset, batch_size=1, num_workers=8)\n return dataloader\n\n\[email protected]_grad()\ndef inference(model, dataloader, dst_path: str, t0: float) -> None:\n \"\"\"Run inference with given model and dataloader.\n\n Args:\n model: PyTorch model.\n dataloader: PyTorch dataset loader.\n dst_path: destination path for inference result to be written.\n t0: initial time prior to creating model and dataset\n by time.monotonic().\n \"\"\"\n model = model.to(device)\n model.eval()\n\n profile_ = torch.rand(1, 3, 512, 512).to(device)\n for transform in dataloader.dataset.transform.transforms:\n if isinstance(transform, Resize):\n profile_input = torch.rand(1, 3, *transform.size).to(device)\n break\n\n n_profile = 100\n print(f\"Profile input shape: {profile_input.shape}\")\n with profiler.profile(use_cuda=True, profile_memory=False) as prof:\n for _ in tqdm(range(100), \"Running profile ...\"):\n x = model(profile_input)\n avg_time = prof.total_average()\n\n if hasattr(avg_time, \"self_cuda_time_total\"):\n cuda_time = avg_time.self_cuda_time_total / 1e6 / n_profile\n else:\n cuda_time = avg_time.cuda_time_total / 1e6 / n_profile\n\n cpu_time = avg_time.self_cpu_time_total / 1e6 / n_profile\n print(prof.key_averages())\n print(f\"Average CUDA time: {cuda_time}, CPU time: {cpu_time}\")\n\n result = {\n \"inference\": {},\n \"time\": {\n \"profile\": {\"cuda\": float(\"inf\"), \"cpu\": float(\"inf\")},\n \"runtime\": {\"all\": 0, \"inference_only\": 0},\n \"inference\": {},\n },\n \"macs\": float(\"inf\"),\n }\n time_measure_inference = 0\n for img, _, fname in tqdm(dataloader, \"Running inference ...\"):\n t_start = torch.cuda.Event(enable_timing=True)\n t_end = torch.cuda.Event(enable_timing=True)\n\n t_start.record()\n img = img.to(device)\n pred = model(img)\n pred = torch.argmax(pred)\n\n t_end.record()\n torch.cuda.synchronize()\n t_inference = t_start.elapsed_time(t_end) / 1000\n time_measure_inference += t_inference\n\n result[\"inference\"][fname[0]] = CLASSES[int(pred.detach())]\n result[\"time\"][\"inference\"][fname[0]] = t_inference\n\n result[\"time\"][\"profile\"][\"cuda\"] = cuda_time\n result[\"time\"][\"profile\"][\"cpu\"] = cpu_time\n result[\"time\"][\"runtime\"][\"all\"] = time.monotonic() - t0\n result[\"time\"][\"runtime\"][\"inference_only\"] = time_measure_inference\n\n j = json.dumps(result, indent=4)\n save_path = os.path.join(dst_path, \"output.csv\")\n with open(save_path, \"w\") as outfile:\n json.dump(result, outfile)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Submit.\")\n parser.add_argument(\n \"--dst\", type=str, help=\"destination path for submit\",\n default=os.environ.get('SM_OUTPUT_DATA_DIR')\n )\n parser.add_argument(\"--model_dir\", type=str, help=\"Saved model root directory which includes 'best.pt', 'data.yml', and, 'model.yml'\", default='/opt/ml/code/optuna/2nd')\n parser.add_argument(\"--weight_name\", type=str, help=\"Model weight file name. (best.pt, best.ts, ...)\", default=\"0.5632.pt\")\n parser.add_argument(\n \"--img_root\",\n type=str,\n help=\"image folder root. e.g) 'data/test'\",\n default='/opt/ml/data/test'\n )\n args = parser.parse_args()\n assert args.model_dir != '' and args.img_root != '', \"'--model_dir' and '--img_root' must be provided.\"\n\n args.weight = os.path.join(args.model_dir, args.weight_name)\n args.model_config = os.path.join(args.model_dir, \"model.yml\")\n args.data_config = os.path.join(args.model_dir, \"data.yml\")\n\n t0 = time.monotonic()\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n # prepare datalaoder\n dataloader = get_dataloader(img_root=args.img_root, data_config=args.data_config)\n\n # prepare model\n if args.weight.endswith(\"ts\"):\n model = torch.jit.load(args.weight)\n else:\n model_instance = Model(args.model_config, verbose=True)\n model_instance.load_state_dict( # model.\n torch.load(args.weight, map_location=torch.device(\"cpu\"))\n )\n model = model_instance #.model\n\n # inference\n inference(model, dataloader, args.dst, t0)\n\n" ]
[ [ "torch.cuda.synchronize", "torch.jit.load", "torch.cuda.Event", "torch.utils.data.DataLoader", "torch.no_grad", "torch.rand", "torch.cuda.is_available", "torch.device", "torch.autograd.profiler.profile", "torch.argmax" ] ]
georgedeath/bomean
[ "0dad35e0d584cf7c46c9a8cb0445f225875cfa86" ]
[ "bopt/transforms.py" ]
[ "import torch\r\nfrom scipy.stats import median_absolute_deviation\r\n\r\n\r\nclass Transform_Base(object):\r\n \"\"\"\r\n Base class for transformations based on some data.\r\n \"\"\"\r\n\r\n def __init__(self, Ytr):\r\n self.Ytr = Ytr\r\n\r\n # Transform the mean\r\n def scale_mean(self, mu):\r\n return mu\r\n\r\n # Reverse the transformation to the mean\r\n def unscale_mean(self, mu):\r\n return mu\r\n\r\n # Reverse the transformation to the variance\r\n def unscale_var(self, var):\r\n return var\r\n\r\n\r\nclass Transform_Standardize(Transform_Base):\r\n \"\"\"\r\n Standardize the data\r\n \"\"\"\r\n def __init__(self, Ytr):\r\n super().__init__(Ytr)\r\n self.Ytr_mean = Ytr.mean()\r\n self.Ytr_std = Ytr.std()\r\n self.Ytr_var = Ytr.var()\r\n\r\n def scale_mean(self, mu):\r\n return (mu - self.Ytr_mean) / self.Ytr_std\r\n\r\n def unscale_mean(self, mu):\r\n return mu * self.Ytr_std + self.Ytr_mean\r\n\r\n def unscale_var(self, var):\r\n return var * self.Ytr_var\r\n\r\n\r\nclass Transform_StandardizeRobustly(Transform_Base):\r\n \"\"\"\r\n Robustly standardize the data by estimating its scale\r\n \"\"\"\r\n def __init__(self, Ytr):\r\n super().__init__(Ytr)\r\n self.Ytr_median = Ytr.median()\r\n Ytr_numpy = Ytr.numpy().ravel()\r\n self.Ytr_scale = torch.tensor(median_absolute_deviation(Ytr_numpy))\r\n self.Ytr_scaleSQR = self.Ytr_scale**2\r\n\r\n def scale_mean(self, mu):\r\n return (mu - self.Ytr_median) / self.Ytr_scale\r\n\r\n def unscale_mean(self, mu):\r\n return mu * self.Ytr_scale + self.Ytr_median\r\n\r\n def unscale_var(self, var):\r\n return var * self.Ytr_scaleSQR\r\n" ]
[ [ "scipy.stats.median_absolute_deviation" ] ]
msrasmussen/lisa
[ "9c8d790d8897c817a4d9d251dbbea34aa292d883" ]
[ "lisa/notebook.py" ]
[ "# SPDX-License-Identifier: Apache-2.0\n#\n# Copyright (C) 2019, Arm Limited and contributors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# 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, WITHOUT\n# 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\"\"\"\nVarious utilities for interactive notebooks, plus some generic plot-related\nfunctions.\n\"\"\"\n\nimport functools\nimport collections\nimport warnings\nimport importlib\nimport contextlib\nimport inspect\nfrom uuid import uuid4\nfrom itertools import starmap\n\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.figure import Figure\nfrom matplotlib.backend_bases import MouseButton\nimport holoviews as hv\nimport bokeh.models\nimport panel as pn\n\nfrom cycler import cycler as make_cycler\n\nfrom ipywidgets import widgets, Layout, interact\nfrom IPython.display import display\n\nfrom lisa.utils import is_running_ipython, order_as\n\n# Enable all backends, finishing with matplotlib so it becomes the default (for\n# backward compat). Since this also corresponds to holoviews default, we are\n# not loosing anything, as the user will need hv.extension('bokeh') anyway.\n_backends = ['plotly', 'bokeh', 'matplotlib']\n\n# If the user selected a backend already, use it as defaults by activating it\n# last\n_curr_backend = hv.Store.current_backend\nif _curr_backend:\n _backends.remove(_curr_backend)\n _backends.append(_curr_backend)\n\nfor backend in _backends:\n try:\n importlib.import_module(backend)\n except Exception:\n pass\n else:\n hv.extension(backend)\n\nCOLOR_CYCLE = [\n '#377eb8', '#ff7f00', '#4daf4a',\n '#f781bf', '#a65628', '#984ea3',\n '#999999', '#e41a1c', '#dede00'\n]\n\"\"\"\nColorblind-friendly cycle, see https://gist.github.com/thriveth/8560036\n\"\"\"\n\nplt.rcParams['axes.prop_cycle'] = make_cycler(color=COLOR_CYCLE)\n\n\nclass WrappingHBox(widgets.HBox):\n \"\"\"\n HBox that will overflow on multiple lines if the content is too large to\n fit on one line.\n \"\"\"\n def __init__(self, *args, **kwargs):\n layout = Layout(\n # Overflow items to the next line rather than hiding them\n flex_flow='row wrap',\n # Evenly spread on one line of items\n justify_content='space-around',\n )\n super().__init__(*args, layout=layout, **kwargs)\n\n\n# Make a subclass so we can integrate better with mplcursors\nclass _DataframeLinkMarker(mpl.lines.Line2D):\n pass\n\n\n# mplcursors is not a dependency anymore as interactive plots are now done with\n# bokeh, but keep this around for compatibility in case someone needs\n# matplotlib to get a better fixed output and wants a bit of interactivity for\n# development as well.\ntry:\n import mplcursors\nexcept ImportError:\n pass\nelse:\n # Tell mplcursors that we are never selecting the marker line, so that it\n # will still show the coordinates of the data that were plotted, rather\n # than useless coordinates of the marker\n @mplcursors.compute_pick.register(_DataframeLinkMarker)\n def _(artist, event):\n return None\n\n\ndef _make_vline(axis, *args, **kwargs):\n vline = axis.axvline(*args, **kwargs)\n assert type(vline) is mpl.lines.Line2D # pylint: disable=unidiomatic-typecheck\n vline.__class__ = _DataframeLinkMarker\n vline.set_visible(False)\n return vline\n\n\ndef axis_link_dataframes(axis, df_list, before=1, after=5, cursor_color='red', follow_cursor=False):\n \"\"\"\n Link some dataframes to an axis displayed in the interactive matplotlib widget.\n\n\n :param axis: Axis to link to.\n :type axis: matplotlib.axes.Axes\n\n :param df_list: List of pandas dataframe to link.\n :type df_list: list(pandas.DataFrame)\n\n :param before: Number of dataframe rows to display before the selected\n location.\n :type before: int\n\n :param after: Number of dataframe rows to display after the selected\n location.\n :type after: int\n\n :param cursor_color: Color of the vertical line added at the clicked\n location.\n :type cursor_color: str\n\n :param follow_cursor: If ``True``, the cursor will be followed without the\n need to click.\n :type follow_cursor: bool\n\n When the user clicks on the graph, a vertical marker will appear and the\n dataframe slice will update to show the relevant row.\n\n .. note:: This requires the matplotlib widget enabled using ``%matplotlib\n widget`` magic.\n \"\"\"\n df_list = [df for df in df_list if not df.empty]\n output_list = [widgets.Output() for df in df_list]\n layout = Layout(\n # Overflow items to the next line rather than hiding them\n flex_flow='row wrap',\n # Evenly spread on one line of item when there is more than one item,\n # align left otherwise\n justify_content='space-around' if len(df_list) > 1 else 'flex-start',\n )\n hbox = widgets.HBox(output_list, layout=layout)\n\n cursor_vline = _make_vline(axis, color=cursor_color)\n\n def show_loc(loc):\n cursor_vline.set_xdata(loc)\n cursor_vline.set_visible(True)\n\n for df, output in zip(df_list, output_list):\n if loc < df.index[0]:\n iloc = 0\n elif loc > df.index[-1]:\n iloc = -1\n else:\n iloc = df.index.get_loc(loc, method='ffill')\n index_loc = df.index[iloc]\n\n begin = max(iloc - before, 0)\n end = min(iloc + after, len(df))\n sliced_df = df.iloc[begin:end]\n\n def highlight_row(row):\n if row.name == index_loc: # pylint: disable=cell-var-from-loop\n return ['background: lightblue'] * len(row)\n else:\n return [''] * len(row)\n\n styler = sliced_df.style.apply(highlight_row, axis=1)\n styler = styler.set_properties(**{\n 'text-align': 'left',\n # perserve multiple consecutive spaces\n 'white-space': 'pre',\n # Make sure all chars have the same width to preserve column\n # alignments in preformatted strings\n 'font-family': 'monospace',\n })\n\n # wait=True avoids flicker by waiting for new content to be ready\n # to display before clearing the previous one\n output.clear_output(wait=True)\n with output:\n display(styler)\n\n init_loc = min((df.index[0] for df in df_list), default=0)\n show_loc(init_loc)\n\n def handler(event):\n loc = event.xdata\n return show_loc(loc)\n\n event = 'motion_notify_event' if follow_cursor else 'button_press_event'\n axis.get_figure().canvas.mpl_connect(event, handler)\n display(hbox)\n\n\ndef axis_cursor_delta(axis, colors=('blue', 'green'), buttons=(MouseButton.LEFT, MouseButton.RIGHT)):\n \"\"\"\n Display the time delta between two vertical lines drawn on clicks.\n\n :param axis: Axis to link to.\n :type axis: matplotlib.axes.Axes\n\n :param colors: List of colors to use for vertical lines.\n :type colors: list(str)\n\n :param buttons: Mouse buttons to use for each vertical line.\n :type buttons: list(matplotlib.backend_bases.MouseButton)\n\n .. note:: This requires the matplotlib widget enabled using\n ``%matplotlib widget`` magic.\n \"\"\"\n delta_widget = widgets.Text(\n value='0',\n placeholder='0',\n description='Cursors delta',\n disabled=False,\n )\n\n vlines = [\n _make_vline(axis, color=color)\n for color in colors\n ]\n\n assert len(vlines) == 2\n vlines_map = dict(zip(buttons, vlines))\n vlines_loc = collections.defaultdict(\n lambda: min(axis.get_xbound())\n )\n\n def handler(event):\n loc = event.xdata\n button = event.button\n\n vline = vlines_map[button]\n vlines_loc[button] = loc\n vline.set_xdata(loc)\n vline.set_visible(True)\n locs = [\n vlines_loc[button]\n for button in buttons\n ]\n delta = locs[1] - locs[0]\n delta_widget.value = str(delta)\n\n axis.get_figure().canvas.mpl_connect('button_press_event', handler)\n display(delta_widget)\n\n\ndef interact_tasks(trace, tasks=None, kind=None):\n \"\"\"\n Decorator to make a block of code parametrized on a task that can be\n selected from a dropdown.\n\n :param trace: Trace object in use\n :type trace: lisa.trace.Trace\n\n :param tasks: List of tasks that are available. See ``kind`` for\n alternative way of specifying tasks.\n :type tasks: list(int or str or lisa.trace.TaskID) or None\n\n :param kind: Alternatively to ``tasks``, a kind can be provided and the\n tasks will be selected from the trace for you. It can be:\n\n * ``rtapp`` to select all rt-app tasks\n * ``all`` to select all tasks.\n\n :type kind: str or None\n\n **Example**::\n\n trace = Trace('trace.dat')\n\n # Allow selecting any rtapp task\n @interact_tasks(trace, kind='rtapp')\n def do_plot(task):\n trace.ana.load_tracking.plot_task_signals(task)\n \"\"\"\n if tasks is not None:\n tasks = [\n trace.get_task_id(task, update=False)\n for task in tasks\n ]\n else:\n kind = kind or 'all'\n if kind == 'all':\n tasks = trace.task_ids\n elif kind == 'rtapp':\n tasks = trace.ana.rta.rtapp_tasks\n else:\n raise ValueError(f'Unknown task kind: {kind}')\n\n # Map of friendly names to actual objects\n task_map = {\n str(task): task\n for task in tasks\n }\n\n def decorator(f):\n @functools.wraps(f)\n @interact\n def wrapper(task=sorted(task_map.keys())):\n task = task_map[task]\n return f(task)\n return wrapper\n\n return decorator\n\n\ndef make_figure(width, height, nrows, ncols, interactive=None, **kwargs):\n \"\"\"\n Make a :class:`matplotlib.figure.Figure` and its axes.\n\n :param width: Width of the figure.\n :type width: int\n\n :param height: Height of the figure.\n :type height: int\n\n :param interactive: If ``True``, create an interactive figure. Defaults to\n ``True`` when running under IPython, ``False`` otherwise.\n :type interactive: bool or None\n\n :Variable keyword arguments: Forwarded to :class:`matplotlib.figure.Figure`\n\n :returns: A tuple of:\n * :class:`matplotlib.figure.Figure`\n * :class:`matplotlib.axes.Axes` as a scalar, an iterable (1D) or iterable of iterable matrix (2D)\n \"\"\"\n if interactive is None:\n interactive = is_running_ipython()\n\n if not interactive and tuple(map(int, mpl.__version__.split('.'))) <= (3, 0, 3):\n warnings.warn('This version of matplotlib does not allow saving figures from axis created using Figure(), forcing interactive=True')\n interactive = True\n\n width *= ncols\n height *= nrows\n\n if interactive:\n figure, axes = plt.subplots(\n figsize=(width, height),\n nrows=nrows,\n ncols=ncols,\n **kwargs,\n )\n else:\n figure = Figure(figsize=(width, height))\n axes = figure.subplots(ncols=ncols, nrows=nrows, **kwargs)\n\n return (figure, axes)\n\n\ndef plot_signal(series, name=None, interpolation=None, add_markers=True):\n \"\"\"\n Plot a signal using ``holoviews`` library.\n\n :param series: Series of values to plot.\n :type series: pandas.Series\n\n :param name: Name of the signal. Defaults to the series name.\n :type name: str or None\n\n :param interpolation: Interpolate type for the signal. Defaults to\n ``steps-post`` which is the correct value for signals encoded as a\n series of updates.\n :type interpolation: str or None\n\n :param add_markers: Add markers to the plot.\n :type add_markers: bool\n \"\"\"\n if isinstance(series, pd.DataFrame):\n try:\n col, = series.columns\n except ValueError:\n raise ValueError('Can only pass Series or DataFrame with one column')\n else:\n series = series[col]\n\n label = name or series.name\n interpolation = interpolation or 'steps-post'\n kdims = [\n # Ensure shared_axes works well across plots.\n # We don't set the unit as this will prevent shared_axes to work if\n # the other plots do not set the unit, which is what usually\n # happens, since only name/label is taken from pandas index names.\n hv.Dimension('Time'),\n ]\n fig = hv.Curve(\n series,\n label=label,\n kdims=kdims,\n ).opts(\n interpolation=interpolation,\n title=label,\n )\n if add_markers:\n # The \"marker\" group for Scatter is used to provide marker-specific\n # styling in generic code..\n # TODO: use mute_legend=True once this bug is fixed:\n # https://github.com/holoviz/holoviews/issues/3936\n fig *= hv.Scatter(\n series,\n label=label,\n group='marker',\n kdims=kdims,\n )\n return fig\n\n\n# TODO: revisit when this discussion is solved:\n# https://github.com/holoviz/holoviews/issues/4988\ndef _hv_neutral():\n \"\"\"\n Neutral element of holoviews operations such that\n ``x <op> holoviews_neutral() == x``.\n\n .. note:: Holoviews currently does not have a perfectly neutral element.\n \"\"\"\n return hv.Curve([])\n\n\ndef _hv_backend_twinx(backend, display, y_range):\n def hook(plot, element):\n p = plot.state\n\n if backend == 'bokeh':\n glyph = p.renderers[-1]\n vals = glyph.data_source.data['y']\n\n if y_range is None:\n _y_range = (vals.min(), vals.max())\n else:\n _y_range = y_range\n\n name = uuid4().hex\n p.extra_y_ranges.update({\n name: bokeh.models.Range1d(start=_y_range[0], end=_y_range[1])\n })\n glyph.y_range_name = name\n\n if display:\n p.add_layout(\n bokeh.models.LinearAxis(y_range_name=name),\n 'right'\n )\n elif backend == 'matplotlib':\n ax = plot.handles['axis']\n twin = ax.twinx()\n plot.handles['axis'] = twin\n if not display:\n twin.get_yaxis().set_ticks([])\n if y_range is not None:\n twin.set_ylim(y_range)\n else:\n raise ValueError(f'Unsupported backend={backend}')\n\n return hook\n\ndef _hv_twinx(fig, display=True, y_range=None):\n \"\"\"\n Similar to matplotlib's twinx feature where the element's Y axis is\n separated from the default one and drawn on the right of the plot.\n\n :param display: If ``True``, the ticks will be displayed on the right of\n the plot. Otherwise, it will be hidden.\n :type display: bool\n\n .. note:: This uses a custom hook for each backend, so it will be disabled\n if the user also set their own hook.\n \"\"\"\n kwargs = dict(\n display=display,\n y_range=y_range,\n )\n return fig.options(\n backend='bokeh',\n hooks=[_hv_backend_twinx('bokeh', **kwargs)],\n ).options(\n backend='matplotlib',\n hooks=[_hv_backend_twinx('matplotlib', **kwargs)],\n )\n\ndef _hv_multi_line_title_hook(plot, element):\n p = plot.state\n # Add in reverse since titles will pile upwards\n lines = list(reversed(plot.title.splitlines()))\n if len(lines) > 1:\n for line in lines:\n title = bokeh.models.Title(\n text=line,\n standoff=1,\n )\n p.add_layout(title, 'above')\n\n # Add an empty line at the top to provide visual separation\n # with other plots\n p.add_layout(bokeh.models.Title(text=' '), 'above')\n del p.title\n\n # Adjust the width of the plot so that the title is not truncated\n max_len = max(map(len, lines))\n # Empirical, should probably inspect the title font size instead\n px_per_char = 12\n p.width = max(p.width, max_len * px_per_char)\n\n\ndef _hv_multi_line_title(fig):\n \"\"\"\n Holoviews hook to allow multiline titles.\n\n Also enlarges the plot if its too small for its title.\n \"\"\"\n return fig.options(hooks=[_hv_multi_line_title_hook])\n\n\[email protected]\ndef _hv_set_backend(backend):\n \"\"\"\n Context manager to work around this issue:\n https://github.com/holoviz/holoviews/issues/4962\n \"\"\"\n old_backend = hv.Store.current_backend\n try:\n # This is safe to do as long as the backend has been\n # loaded with hv.extension() beforehand, which happens\n # at import time\n hv.Store.set_current_backend(backend)\n yield\n finally:\n if old_backend:\n hv.Store.set_current_backend(old_backend)\n\n\ndef _hv_link_dataframes(fig, dfs):\n \"\"\"\n Link the provided dataframes to the holoviews figure.\n\n :returns: A panel displaying the dataframes and the figure.\n \"\"\"\n def make_table(i, df):\n event_header = [\n col for col in df.columns\n if (\n col.startswith('__') or\n col == 'event'\n )\n ]\n df = df[order_as(df.columns, event_header)]\n\n if df.index.name in df.columns:\n df.index = df.index.copy(deep=False)\n df.index.name = ''\n\n df_widget = pn.widgets.DataFrame(\n df,\n name=df.attrs.get('name', f'dataframe #{i}'),\n formatters={\n 'bool': {'type': 'tickCross'}\n },\n # Disable edition of the dataframe\n disabled=True,\n sortable=False,\n # Ensure some columns are always displayed\n # Note: Tabulator requires a list of column names instead.\n frozen_columns=len(event_header) + 1,\n height=400,\n autosize_mode='fit_viewport',\n row_height=25,\n\n # Only relevant for pn.widgets.Tabulator\n #theme='simple',\n #selectable='checkbox',\n # Avoid transferring too much data at once to the browser\n #pagination='remote',\n #page_size=100,\n )\n return df_widget\n\n def mark_table_selection(tables):\n def plot(*args):\n xs = [\n table.value.index[x]\n for xs, table in zip(args, tables)\n for x in xs\n ]\n return hv.Overlay(\n [\n hv.VLine(x).opts(\n backend='bokeh',\n line_dash='dashed',\n )\n for x in xs\n ]\n )\n\n tables = list(tables)\n streams = [\n table.param.selection\n for table in tables\n ]\n bound = pn.bind(plot, *streams)\n dmap = hv.DynamicMap(bound).opts(framewise=True)\n\n return dmap\n\n def scroll_table(tables):\n def record_taps(x, y):\n for table in tables:\n if x is not None:\n df = table.value\n i = df.index.get_loc(x, method='ffill')\n # On the pn.widgets.DataFrame, this will automatically scroll in the table.\n # On pn.widgets.Tabulator, this will currently not unfortunately\n table.selection = [i]\n return hv.Points([])\n\n tap = hv.streams.SingleTap(transient=True)\n dmap = hv.DynamicMap(record_taps, streams=[tap])\n return dmap\n\n tables = list(starmap(make_table, enumerate(dfs)))\n markers = mark_table_selection(tables)\n scroll = scroll_table(tables)\n\n # Workaround issue:\n # https://github.com/holoviz/holoviews/issues/5003\n if isinstance(fig, hv.Layout):\n ncols = fig._max_cols\n else:\n ncols = None\n\n fig = fig * (scroll * markers)\n\n if ncols is not None:\n fig = fig.cols(ncols)\n\n if len(tables) > 1:\n tables_widget = pn.Tabs(\n *(\n (table.name, table)\n for table in tables\n ),\n align='center',\n )\n else:\n tables_widget = tables[0]\n tables_widget.align = 'center'\n\n return pn.Column(\n fig,\n tables_widget,\n sizing_mode='stretch_both',\n align='center',\n )\n\n\nclass _HoloviewsPanelWrapper:\n \"\"\"\n Dummy base class used to identify classes created by\n :func:`_hv_wrap_fig_cls`.\n \"\"\"\n pass\n\[email protected]_cache(maxsize=None)\ndef _hv_wrap_fig_cls(cls):\n \"\"\"\n Wrap a holoviews element class so that it is displayed inside a panel but\n still exhibits the holoviews API.\n\n .. note:: Due to https://github.com/holoviz/holoviews/issues/3577, ``x <op>\n y`` will not work if ``x`` is a holoviews object, but the opposit will\n work.\n \"\"\"\n\n def wrap_fig(self, x):\n if x.__class__.__module__.startswith('holoviews'):\n return _hv_fig_to_pane(\n fig=x,\n make_pane=self._make_pane,\n )\n else:\n return x\n\n def make_wrapper(f):\n @functools.wraps(f)\n def wrapper(self, *args, **kwargs):\n x = f(self._fig, *args, **kwargs)\n return wrap_fig(self, x)\n\n return wrapper\n\n def make_op(name):\n def op(self, other):\n f = getattr(self._fig, name)\n\n # Unwrap the holoviews figure to avoid exceptions\n if isinstance(other, _HoloviewsPanelWrapper):\n other = other._fig\n\n x = f(other)\n return wrap_fig(self, x)\n return op\n\n class NewCls(_HoloviewsPanelWrapper):\n def __init__(self, fig, make_pane):\n self._fig = fig\n self._make_pane = make_pane\n\n def _repr_mimebundle_(self, *args, **kwargs):\n pane = self._make_pane(self._fig)\n return pane._repr_mimebundle_(*args, **kwargs)\n\n def opts(self, *args, **kwargs):\n return wrap_fig(\n self,\n self._fig.opts(*args, **kwargs),\n )\n\n for attr, x in inspect.getmembers(cls):\n if (not attr.startswith('_')) and inspect.isfunction(x):\n setattr(NewCls, attr, make_wrapper(x))\n\n for name in (\n '__add__',\n '__radd__',\n\n '__sub__',\n '__rsub__',\n\n '__mul__',\n '__rmul__',\n\n '__matmul__',\n '__rmatmul__',\n\n '__truediv__',\n '__rtruediv__',\n\n '__floordiv__',\n '__rfloordiv__',\n\n '__mod__',\n '__rmod__',\n\n '__divmod__',\n '__rdivmod__',\n\n '__pow__',\n '__rpow__',\n\n '__and__',\n '__rand__',\n\n '__xor__',\n '__rxor__',\n\n '__or__',\n '__ror__',\n\n '__rshift__',\n '__rrshift__',\n\n '__lshift__',\n '__rlshift__',\n ):\n if hasattr(cls, name):\n setattr(NewCls, name, make_op(name))\n\n return NewCls\n\n\ndef _hv_fig_to_pane(fig, make_pane):\n \"\"\"\n Stop-gap measure until there is a proper solution for:\n https://discourse.holoviz.org/t/replace-holoviews-notebook-rendering-with-a-panel/2519/12\n \"\"\"\n cls = _hv_wrap_fig_cls(fig.__class__)\n return cls(fig=fig, make_pane=make_pane)\n\n\n\n# vim :set tabstop=4 shiftwidth=4 textwidth=80 expandtab\n" ]
[ [ "matplotlib.__version__.split", "matplotlib.pyplot.subplots", "matplotlib.figure.Figure" ] ]
mmenarini/MetaSense
[ "910cfdc1d05b2f8ad89ce27a9594ee73def6cd37" ]
[ "MetaSenseTransfer/scripts/plot_split.py" ]
[ "import numpy as np\nimport glob\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style('white')\nimport pandas as pd\nimport tqdm\nimport joblib\nfrom path import Path\nimport click\n\nMETRICS = [\"%s %s\"% (gas, metric) for gas in [\"NO2\", \"O3\"]\n for metric in [\"MAE\", \"CvMAE\", \"MSE\", \"rMSE\", \"crMSE\", \"R^2\", \"MBE\"]]\n\ndef load_subu(subu_path, models, name):\n subu_level1 = pd.read_csv(subu_path / 'level1' / 'test.csv')\n subu_level1['Model'] = subu_level1['Model'].apply(eval)\n subu_level1['Testing Location'] = subu_level1['Testing Location'].apply(eval)\n subu_level1['Board'] = subu_level1['Model'].apply(lambda x: int(x[2]))\n subu_level1['Board'] = subu_level1['Board'].astype(np.int32)\n subu_level1['Model'] = subu_level1[['Board', 'Testing Location']].apply(lambda x: (x[1][0], x[1][1], x[0]), axis=1)\n subu_level1['Benchmark'] = \"Level 1\"\n subu_level1 = subu_level1.drop(\"Testing Location\", axis=1)\n subu_level2 = pd.read_csv(subu_path / 'level2' / 'test.csv')\n subu_level2['Model'] = subu_level2['Model'].apply(eval)\n subu_level2['Benchmark'] = \"Level 2\"\n locations = {'elcajon', 'donovan', 'shafter'}\n rounds = {2, 3, 4}\n for i, result in subu_level2.iterrows():\n board_id, trains = result['Model']\n r = set(x[0] for x in trains)\n l = set(x[1] for x in trains)\n triple = (list(rounds - r)[0], list(locations - l)[0], board_id)\n subu_level2.at[i, 'Model'] = triple\n subu_level2.at[i, 'Board'] = board_id\n subu_level2['Board'] = subu_level2['Board'].astype(np.int32)\n subu_level2.loc[:, 'Benchmark'] = \"Level 2\"\n subu_results = pd.concat([subu_level1, subu_level2])\n subu_results.loc[:, 'Calibration'] = name\n subu_results = subu_results.drop('Unnamed: 0', axis=1)\n return subu_results\n\ndef get_results(models):\n results = pd.DataFrame(columns=['Model', 'NO2 MAE', 'O3 MAE', 'NO2 CvMAE', 'O3 CvMAE'])\n for model_name in tqdm.tqdm(models):\n if model_name[-4] == '.' or '_' not in model_name:\n continue\n if len(model_name.split(\"-\")) > 2:\n continue\n model_path = Path(model_name)\n model_split = model_path.split(\"/\")[-1].split(\"-\")\n model_splits = [x.split(\"_\") for x in model_split]\n triples = [(int(x[0]), x[1], int(x[2])) for x in model_splits]\n model_results = pd.read_csv(model_path / 'level1' / 'test.csv')\n model_results = model_results.drop('Unnamed: 0', axis=1)\n model_results['Model'] = model_results['Model'].apply(eval)\n def filter(x):\n return x['Model'] in triples\n filtered = model_results[model_results.apply(filter, axis=1)]\n if len(triples) == 9:\n filtered.loc[:, \"Benchmark\"] = 'Level 2'\n elif len(triples) == 18:\n filtered.loc[:, \"Benchmark\"] = 'Level 1'\n else:\n filtered.loc[:, \"Benchmark\"] = 'Level %u' % (3 - len(triples))\n results = results.append(filtered)\n results.loc[:, 'Calibration'] = 'Split-NN'\n return results, set(results['Model'])\n\ndef merge_results(split_results, subu_results, name):\n merged = pd.concat([split_results, subu_results])\n def filter(x):\n for column in METRICS:\n if x['Calibration'] == 'Split-NN':\n x['%s Improvement' % column] = -(x[column] - merged[(merged['Model'] == x['Model']) & (merged['Calibration'] == name) & (merged['Benchmark'] == x['Benchmark'])][column].mean())\n else:\n x['%s Improvement' % column] = np.nan\n return x\n merged = merged.apply(filter, axis=1)\n return merged\n\ndef plot_results(results, column, out_path):\n results = results[~results[column].isnull()]\n fig, ax = plt.subplots()\n data = results.copy()\n data[\"Model\"] = data[\"Calibration\"]\n sns.boxplot(hue='Model', y=column, data=data[[\"Model\", \"Benchmark\"] + METRICS + [\"%s Improvement\" % x for x in METRICS]], ax=ax, x='Benchmark', whis=2)\n fig.savefig(out_path, bbox_inches='tight')\n\[email protected]()\[email protected]('out_dir', nargs=1)\[email protected]('name', nargs=1)\[email protected]('out_path', nargs=1)\[email protected]('subu_path', nargs=1)\[email protected]('models', nargs=-1, type=str)\ndef main(name, out_dir, out_path, subu_path, models):\n out_path = Path(out_path)\n if models == ['*']:\n split_results, split_models = get_results([out_path / m for m in models])\n else:\n split_results, split_models = get_results(out_path.parent.listdir())\n out_path = out_path / out_dir\n out_path.mkdir_p()\n subu_results = load_subu(Path(subu_path), split_models, name)\n merged_results = merge_results(split_results, subu_results, name)\n merged_results.to_csv(out_path / 'results.csv')\n merged_results.to_latex(out_path / 'results.tex')\n\n for metric in METRICS:\n result = merged_results[merged_results['Calibration'] == 'Split-NN'][metric].dropna().describe()\n print(\"%s[Split]: %.3f ± %.3f\" % (metric, result['mean'], result['std']))\n result = merged_results[merged_results['Calibration'] == name][metric].dropna().describe()\n print(\"%s[%s]: %.3f ± %.3f\" % (metric, name, result['mean'], result['std']))\n\n result = merged_results['%s Improvement' % metric].dropna().describe()\n print(\"%s Improvement: %.3f ± %.3f\" % (metric, result['mean'], result['std']))\n merged_results = merged_results.sort_values('Benchmark')\n\n plot_results(merged_results, metric, out_path / ('%s.png' % metric))\n\n plot_results(merged_results, '%s Improvement' % metric, out_path / ('%s-diff.png' % metric))\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "pandas.concat", "pandas.read_csv", "matplotlib.pyplot.subplots", "pandas.DataFrame" ] ]
harewei/reinforcement_learning
[ "0f3d2fe75cc872883232df4b23969708a701e024" ]
[ "agents/A2CER.py" ]
[ "# Unlike REINFORCE, we do not wait for end of episode to train. Also, the advantage is now calculated\n# from TD error, which are derived using critic network.\n\nimport gym\nimport numpy as np\nimport tensorflow as tf\ntf.compat.v1.disable_eager_execution()\nfrom tensorflow.keras.layers import Dense, Input, Activation\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.optimizers import Adam\nfrom utils.visualizer import visualize\nimport random\nfrom itertools import count\n\n\n# Memory storage method when using proportional method\n# Original Code by @jaara: https://github.com/jaara/AI-blog/blob/master/SumTree.py\nclass SumTree:\n write = 0\n\n def __init__(self, capacity):\n self.capacity = capacity\n self.tree = np.zeros( 2*capacity - 1 )\n self.data = np.zeros( capacity, dtype=object )\n\n def _propagate(self, idx, change):\n parent = (idx - 1) // 2\n\n self.tree[parent] += change\n\n if parent != 0:\n self._propagate(parent, change)\n\n def _retrieve(self, idx, s):\n left = 2 * idx + 1\n right = left + 1\n\n if left >= len(self.tree):\n return idx\n\n if s <= self.tree[left]:\n return self._retrieve(left, s)\n else:\n return self._retrieve(right, s-self.tree[left])\n\n def total(self):\n return self.tree[0]\n\n def add(self, p, data):\n idx = self.write + self.capacity - 1\n\n self.data[self.write] = data\n self.update(idx, p)\n\n self.write += 1\n if self.write >= self.capacity:\n self.write = 0\n\n def update(self, idx, p):\n change = p - self.tree[idx]\n\n self.tree[idx] = p\n self._propagate(idx, change)\n\n def get(self, s):\n idx = self._retrieve(0, s)\n dataIdx = idx - self.capacity + 1\n\n return (idx, self.tree[idx], self.data[dataIdx])\n\n\nclass A2C:\n def __init__(self):\n self.gamma = 0.9 # Reward discount\n self.actor_learning_rate = 0.001\n self.critic_learning_rate = 0.01\n self.memory_size = 10000\n self.memory = SumTree(self.memory_size)\n self.batch_size = 32\n self.replay_frequency = 10\n self.counter = count() # In case multiple memories with same priority\n self.alpha = 0.6 # Used during priority calculation\n self.beta = 0.4 # Used during importance sampling\n self.beta_increase = 0.001\n self.beta_max = 1\n self.constant = 1e-10 # In case priority is 0\n\n def build_actor(self):\n input = Input(shape=(self.num_states,))\n layer = Dense(50, activation='relu')(input)\n layer = Dense(256, activation='relu')(layer)\n logit = Dense(self.num_actions)(layer)\n output = Activation('softmax')(logit)\n model = Model(input, output)\n adam = Adam(lr=self.actor_learning_rate)\n model.compile(loss='categorical_crossentropy', optimizer=adam)\n\n return model\n\n def build_critic(self):\n input = Input(shape=(self.num_states,))\n layer = Dense(50, activation='relu')(input)\n layer = Dense(256, activation='relu')(layer)\n logit = Dense(1)(layer)\n output = Activation('linear')(logit)\n model = Model(input, output)\n adam = Adam(lr=self.critic_learning_rate)\n model.compile(loss='mse', optimizer=adam)\n\n return model\n\n # Select action based on the output of policy network\n def select_action(self, state, model):\n state = np.reshape(state, (1, self.num_states))\n policy = model.predict(state).ravel()\n\n return np.random.choice(self.num_actions, 1, p=policy)[0]\n\n def store_memory(self, priority, state, action, reward, next_state, done):\n self.memory.add(priority, [state, action, reward, next_state, done])\n\n def train(self):\n # Setup environment first\n env = gym.make('CartPole-v1')\n env.seed(1)\n env = env.unwrapped\n\n self.num_actions = env.action_space.n\n self.num_states = env.observation_space.shape[0]\n\n actor = self.build_actor()\n critic = self.build_critic()\n\n max_episode = 100000\n max_step = 10000\n slide_window = 50\n\n # Populate memory first\n state = env.reset()\n print(\"Warming up...\")\n for i in range(self.batch_size):\n action = env.action_space.sample()\n next_state, reward, done, info = env.step(action)\n self.store_memory(1, state, action, reward, next_state, done) # Priority=1 for these transitions\n if done:\n state = env.reset()\n print(\"Warm up complete.\")\n\n for episode_count in range(max_episode):\n state = env.reset()\n current_step = 0\n episode_reward = 0\n\n while True:\n #env.render()\n\n # Actor select action, observe reward and state, then store them\n action = self.select_action(state, actor)\n next_state, reward, done, info = env.step(action)\n\n # Store transition\n episode_reward += reward\n self.store_memory(state, action, reward, next_state, done)\n\n # Sample minibatch from memory\n minibatch = random.sample(self.memory, self.batch_size)\n\n # Transform the minibatch for processing\n minibatch = list(zip(*minibatch))\n\n # Calculate advantage\n states, actions, rewards, next_states, dones = minibatch\n batch_values = critic.predict_on_batch(np.array(states)).ravel()\n batch_next_values = critic.predict_on_batch(np.array(next_states)).ravel()\n td_targets = rewards + self.gamma * (1 - np.array(dones)) * batch_next_values\n td_errors = td_targets - batch_values\n advantages = np.zeros((self.batch_size, self.num_actions))\n for i in range(self.batch_size):\n advantages[i][actions[i]] = td_errors[i]\n\n # Train critic\n critic.train_on_batch(np.array(states), np.array(td_targets))\n\n # Train actor\n actor.train_on_batch(np.array(states), np.array(advantages))\n\n # For logging data\n if done or current_step > max_step:\n visualize(episode_reward, episode_count, slide_window, \"A2C_Offpolicy.png\")\n break\n\n state = next_state\n current_step += 1\n\nif __name__ == '__main__':\n agent = A2C()\n agent.train()\n" ]
[ [ "tensorflow.keras.layers.Activation", "numpy.random.choice", "numpy.reshape", "tensorflow.keras.layers.Dense", "tensorflow.keras.Model", "tensorflow.keras.optimizers.Adam", "tensorflow.compat.v1.disable_eager_execution", "numpy.array", "numpy.zeros", "tensorflow.keras.layers.Input" ] ]
ashish2085/webcrawler
[ "dabb37be05764b762aeec97ae54e8657228a650d" ]
[ "webcrawler.py" ]
[ "from bs4 import BeautifulSoup as soup\nfrom urllib.request import urlopen as uReq\n\n#Package to read config file\nimport configparser\nimport pandas as pd\n\nclass WebCrawler:\n\n\tdef read_ini(self,file_path):\n\t config = configparser.ConfigParser()\n\t config.read(file_path)\n\t return config\n\n\t\n\n\tdef get_title(self,my_url):\n\n\t\t#Requesting URL and getting response\n\t\tuClient = uReq(my_url)\n\t\t#getting response and reading data\n\t\tpage_html = uClient.read()\n\t\t#Closing URL Client Connection\n\t\tuClient.close()\n\t\t#Parsing using HTML parser and beautiful soap\n\t\tpage_soup = soup(page_html, \"html.parser\")\n\n\t\treturn page_soup\n\n\tdef find_title(self,page_soup):\n\t\tlist_title=[]\n\t\t#Finding all title\n\t\ttitle=page_soup.findAll(\"title\")\n\n\t\t#Creating a list of all titles found on the page\n\t\t\n\n\t\t#iterating through the list and eliminating the first 12 character to remove \"Top Story -\" and get final top stories into a list\n\t\tfor i in range(1,len(title)):\n\t\t \n# \t\t print(title[i].get_text()[12:])\n\t\t list_title.append(title[i].get_text()[12:])\n\t\treturn list_title\n\n\tdef create_CSV(self,list_title,file_name):\n\n\t\n\t\t# Create the pandas DataFrame with Top Story as one of the columnn\n\t\tdf = pd.DataFrame(list_title, columns = ['Top Story'])\n\n\t\t#Storing the result into a CSV file\n\t\tdf.to_csv(file_name)\n\t\treturn \"Successfully saved data to file names :\"+file_name\n\n\nif __name__ == '__main__':\n\t#initialise a Class and \n\tWebCrawler=WebCrawler()\n\t#Reading the configuration file\n\tconfig=WebCrawler.read_ini(\"config.ini\")\n\t#Reading the URL to be parsed\n\tmy_url=config[\"DEV_URL\"][\"URL\"]\n\n \n\t#Get the title from the page\n\tpage_soup=WebCrawler.get_title(my_url)\n\n\t#finding all title from the RSSfeed received as response\n\tlist_title=WebCrawler.find_title(page_soup)\n\n \n\t#Creating a CSV using the file name of user's choice\n\tfile_name=config[\"FILE_NAME\"][\"NAME\"]\n\t#Using Pandas to_csv function to create a CSV file as output of the response received\n\tresult=(WebCrawler.create_CSV(list_title,file_name))\n\tprint(result)" ]
[ [ "pandas.DataFrame" ] ]
juliagarriga/h5py
[ "d89bcc4cec7bbce0ae89c998e61d3c7387a9c73d" ]
[ "h5py/tests/test_dtype.py" ]
[ "\"\"\"\n Tests for converting between numpy dtypes and h5py data types\n\"\"\"\n\nfrom itertools import count\nimport platform\nimport numpy as np\nimport h5py\ntry:\n import tables\nexcept ImportError:\n tables = None\n\nfrom .common import ut, TestCase\n\nUNSUPPORTED_LONG_DOUBLE = ('i386', 'i486', 'i586', 'i686', 'ppc64le')\n\n\nclass TestVlen(TestCase):\n\n \"\"\"\n Check that storage of vlen strings is carried out correctly.\n \"\"\"\n def assertVlenArrayEqual(self, dset, arr, message=None, precision=None):\n assert dset.shape == arr.shape, \\\n \"Shape mismatch (%s vs %s)%s\" % (dset.shape, arr.shape, message)\n for (i, d, a) in zip(count(), dset, arr):\n self.assertArrayEqual(d, a, message, precision)\n\n def test_compound(self):\n\n fields = []\n fields.append(('field_1', h5py.string_dtype()))\n fields.append(('field_2', np.int32))\n dt = np.dtype(fields)\n self.f['mytype'] = np.dtype(dt)\n dt_out = self.f['mytype'].dtype.fields['field_1'][0]\n string_inf = h5py.check_string_dtype(dt_out)\n self.assertEqual(string_inf.encoding, 'utf-8')\n\n def test_compound_vlen_bool(self):\n vidt = h5py.vlen_dtype(np.uint8)\n def a(items):\n return np.array(items, dtype=np.uint8)\n\n f = self.f\n\n dt_vb = np.dtype([\n ('foo', vidt),\n ('logical', np.bool)])\n vb = f.create_dataset('dt_vb', shape=(4,), dtype=dt_vb)\n data = np.array([(a([1, 2, 3]), True),\n (a([1 ]), False),\n (a([1, 5 ]), True),\n (a([],), False), ],\n dtype=dt_vb)\n vb[:] = data\n actual = f['dt_vb'][:]\n self.assertVlenArrayEqual(data['foo'], actual['foo'])\n self.assertArrayEqual(data['logical'], actual['logical'])\n\n dt_vv = np.dtype([\n ('foo', vidt),\n ('bar', vidt)])\n f.create_dataset('dt_vv', shape=(4,), dtype=dt_vv)\n\n dt_vvb = np.dtype([\n ('foo', vidt),\n ('bar', vidt),\n ('logical', np.bool)])\n vvb = f.create_dataset('dt_vvb', shape=(2,), dtype=dt_vvb)\n\n dt_bvv = np.dtype([\n ('logical', np.bool),\n ('foo', vidt),\n ('bar', vidt)])\n bvv = f.create_dataset('dt_bvv', shape=(2,), dtype=dt_bvv)\n data = np.array([(True, a([1, 2, 3]), a([1, 2])),\n (False, a([]), a([2, 4, 6])), ],\n dtype=bvv)\n bvv[:] = data\n actual = bvv[:]\n self.assertVlenArrayEqual(data['foo'], actual['foo'])\n self.assertVlenArrayEqual(data['bar'], actual['bar'])\n self.assertArrayEqual(data['logical'], actual['logical'])\n\n def test_compound_vlen_enum(self):\n eidt = h5py.enum_dtype({'OFF': 0, 'ON': 1}, basetype=np.uint8)\n vidt = h5py.vlen_dtype(np.uint8)\n def a(items):\n return np.array(items, dtype=np.uint8)\n\n f = self.f\n\n dt_vve = np.dtype([\n ('foo', vidt),\n ('bar', vidt),\n ('switch', eidt)])\n vve = f.create_dataset('dt_vve', shape=(2,), dtype=dt_vve)\n data = np.array([(a([1, 2, 3]), a([1, 2]), 1),\n (a([]), a([2, 4, 6]), 0), ],\n dtype=dt_vve)\n vve[:] = data\n actual = vve[:]\n self.assertVlenArrayEqual(data['foo'], actual['foo'])\n self.assertVlenArrayEqual(data['bar'], actual['bar'])\n self.assertArrayEqual(data['switch'], actual['switch'])\n\n def test_vlen_enum(self):\n fname = self.mktemp()\n arr1 = [[1], [1, 2]]\n dt1 = h5py.vlen_dtype(h5py.enum_dtype(dict(foo=1, bar=2), 'i'))\n\n with h5py.File(fname, 'w') as f:\n df1 = f.create_dataset('test', (len(arr1),), dtype=dt1)\n df1[:] = np.array(arr1)\n\n with h5py.File(fname, 'r') as f:\n df2 = f['test']\n dt2 = df2.dtype\n arr2 = [e.tolist() for e in df2[:]]\n\n self.assertEqual(arr1, arr2)\n self.assertEqual(h5py.check_enum_dtype(h5py.check_vlen_dtype(dt1)),\n h5py.check_enum_dtype(h5py.check_vlen_dtype(dt2)))\n\n\nclass TestEmptyVlen(TestCase):\n def test_write_empty_vlen(self):\n fname = self.mktemp()\n with h5py.File(fname, 'w') as f:\n d = np.core.records.fromarrays([[], []], names='a,b', formats='|V16,O')\n dset = f.create_dataset('test', data=d, dtype=[('a', '|V16'), ('b', h5py.special_dtype(vlen=np.float_))])\n self.assertEqual(dset.size, 0)\n\n\nclass TestExplicitCast(TestCase):\n def test_f2_casting(self):\n fname = self.mktemp()\n\n np.random.seed(1)\n A = np.random.rand(1500, 20)\n\n # Save to HDF5 file\n with h5py.File(fname, \"w\") as Fid:\n Fid.create_dataset(\"Data\", data=A, dtype='f2')\n\n with h5py.File(fname, \"r\") as Fid:\n B = Fid[\"Data\"][:]\n\n # Compare\n self.assertTrue(np.all(A.astype('f2') == B))\n\n\nclass TestOffsets(TestCase):\n \"\"\"\n Check that compound members with aligned or manual offsets are handled\n correctly.\n \"\"\"\n\n def test_compound_vlen(self):\n vidt = h5py.vlen_dtype(np.uint8)\n eidt = h5py.enum_dtype({'OFF': 0, 'ON': 1}, basetype=np.uint8)\n\n for np_align in (False, True):\n dt = np.dtype([\n ('a', eidt),\n ('foo', vidt),\n ('bar', vidt),\n ('switch', eidt)], align=np_align)\n np_offsets = [dt.fields[i][1] for i in dt.names]\n\n for logical in (False, True):\n if logical and np_align:\n # Vlen types have different size in the numpy struct\n self.assertRaises(TypeError, h5py.h5t.py_create, dt,\n logical=logical)\n else:\n ht = h5py.h5t.py_create(dt, logical=logical)\n offsets = [ht.get_member_offset(i)\n for i in range(ht.get_nmembers())]\n if np_align:\n self.assertEqual(np_offsets, offsets)\n\n def test_aligned_offsets(self):\n dt = np.dtype('i4,i8,i2', align=True)\n ht = h5py.h5t.py_create(dt)\n self.assertEqual(dt.itemsize, ht.get_size())\n self.assertEqual(\n [dt.fields[i][1] for i in dt.names],\n [ht.get_member_offset(i) for i in range(ht.get_nmembers())]\n )\n\n def test_aligned_data(self):\n dt = np.dtype('i4,f8,i2', align=True)\n data = np.empty(10, dtype=dt)\n\n data['f0'] = np.array(np.random.randint(-100, 100, size=data.size),\n dtype='i4')\n data['f1'] = np.random.rand(data.size)\n data['f2'] = np.array(np.random.randint(-100, 100, size=data.size),\n dtype='i2')\n\n fname = self.mktemp()\n\n with h5py.File(fname, 'w') as f:\n f['data'] = data\n\n with h5py.File(fname, 'r') as f:\n self.assertArrayEqual(f['data'], data)\n\n def test_compound_robustness(self):\n # make an out of order compound type with gaps in it, and larger itemsize than minimum\n # Idea is to be robust to type descriptions we *could* get out of HDF5 files, from custom descriptions\n # of types in addition to numpy's flakey history on unaligned fields with non-standard or padded layouts.\n fields = [\n ('f0', np.float64, 25),\n ('f1', np.uint64, 9),\n ('f2', np.uint32, 0),\n ('f3', np.uint16, 5)\n ]\n lastfield = fields[np.argmax([ x[2] for x in fields ])]\n itemsize = lastfield[2] + np.dtype(lastfield[1]).itemsize + 6\n extract_index = lambda index, sequence: [ x[index] for x in sequence ]\n\n dt = np.dtype({\n 'names' : extract_index(0, fields),\n 'formats' : extract_index(1, fields),\n 'offsets' : extract_index(2, fields),\n # 'aligned': False, - already defaults to False\n 'itemsize': itemsize\n })\n\n self.assertTrue(dt.itemsize == itemsize)\n data = np.empty(10, dtype=dt)\n\n # don't trust numpy struct handling , keep fields out of band incase content insertion is erroneous\n # yes... this has also been known to happen.\n f1 = np.array([1 + i * 4 for i in range(data.shape[0])], dtype=dt.fields['f1'][0])\n f2 = np.array([2 + i * 4 for i in range(data.shape[0])], dtype=dt.fields['f2'][0])\n f3 = np.array([3 + i * 4 for i in range(data.shape[0])], dtype=dt.fields['f3'][0])\n f0c = 3.14\n data['f0'] = f0c\n data['f3'] = f3\n data['f1'] = f1\n data['f2'] = f2\n\n # numpy consistency checks\n self.assertTrue(np.all(data['f0'] == f0c))\n self.assertArrayEqual(data['f3'], f3)\n self.assertArrayEqual(data['f1'], f1)\n self.assertArrayEqual(data['f2'], f2)\n\n fname = self.mktemp()\n\n with h5py.File(fname, 'w') as fd:\n fd.create_dataset('data', data=data)\n\n with h5py.File(fname, 'r') as fd:\n readback = fd['data']\n self.assertTrue(readback.dtype == dt)\n self.assertArrayEqual(readback, data)\n self.assertTrue(np.all(readback['f0'] == f0c))\n self.assertArrayEqual(readback['f1'], f1)\n self.assertArrayEqual(readback['f2'], f2)\n self.assertArrayEqual(readback['f3'], f3)\n\n def test_out_of_order_offsets(self):\n dt = np.dtype({\n 'names' : ['f1', 'f2', 'f3'],\n 'formats' : ['<f4', '<i4', '<f8'],\n 'offsets' : [0, 16, 8]\n })\n data = np.empty(10, dtype=dt)\n data['f1'] = np.random.rand(data.size)\n data['f2'] = np.random.randint(-10, 11, data.size)\n data['f3'] = np.random.rand(data.size) * -1\n\n fname = self.mktemp()\n\n with h5py.File(fname, 'w') as fd:\n fd.create_dataset('data', data=data)\n\n with h5py.File(fname, 'r') as fd:\n self.assertArrayEqual(fd['data'], data)\n\n def test_float_round_tripping(self):\n dtypes = set(f for f in np.typeDict.values()\n if (np.issubdtype(f, np.floating) or\n np.issubdtype(f, np.complexfloating)))\n\n if platform.machine() in UNSUPPORTED_LONG_DOUBLE:\n dtype_dset_map = {str(j): d\n for j, d in enumerate(dtypes)\n if d not in (np.float128, np.complex256)}\n else:\n dtype_dset_map = {str(j): d\n for j, d in enumerate(dtypes)}\n\n fname = self.mktemp()\n\n with h5py.File(fname, 'w') as f:\n for n, d in dtype_dset_map.items():\n data = np.arange(10,\n dtype=d)\n\n f.create_dataset(n, data=data)\n\n with h5py.File(fname, 'r') as f:\n for n, d in dtype_dset_map.items():\n ldata = f[n][:]\n self.assertEqual(ldata.dtype, d)\n\n\nclass TestStrings(TestCase):\n def test_vlen_utf8(self):\n dt = h5py.string_dtype()\n\n string_info = h5py.check_string_dtype(dt)\n assert string_info.encoding == 'utf-8'\n assert string_info.length is None\n assert h5py.check_vlen_dtype(dt) is str\n\n def test_vlen_ascii(self):\n dt = h5py.string_dtype(encoding='ascii')\n\n string_info = h5py.check_string_dtype(dt)\n assert string_info.encoding == 'ascii'\n assert string_info.length is None\n assert h5py.check_vlen_dtype(dt) is bytes\n\n def test_fixed_utf8(self):\n dt = h5py.string_dtype(length=10)\n\n string_info = h5py.check_string_dtype(dt)\n assert string_info.encoding == 'utf-8'\n assert string_info.length == 10\n assert h5py.check_vlen_dtype(dt) is None\n\n def test_fixed_ascii(self):\n dt = h5py.string_dtype(encoding='ascii', length=10)\n\n string_info = h5py.check_string_dtype(dt)\n assert string_info.encoding == 'ascii'\n assert string_info.length == 10\n assert h5py.check_vlen_dtype(dt) is None\n\n\[email protected](tables is not None, 'tables is required')\nclass TestB8(TestCase):\n\n \"\"\"\n Test H5T_NATIVE_B8 reading\n \"\"\"\n\n def test_b8_bool(self):\n arr1 = np.array([False, True], dtype=np.bool)\n self._test_b8(arr1)\n self._test_b8(arr1, dtype=np.uint8)\n\n def test_b8_bool_compound(self):\n arr1 = np.array([(False,), (True,)], dtype=np.dtype([('x', '?')]))\n self._test_b8(arr1)\n self._test_b8(arr1, dtype=np.dtype([('x', 'u1')]))\n\n def test_b8_bool_compound_nested(self):\n arr1 = np.array(\n [(True, (True, False)), (True, (False, True))],\n dtype=np.dtype([('x', '?'), ('y', [('a', '?'), ('b', '?')])]),\n )\n self._test_b8(arr1)\n self._test_b8(\n arr1,\n dtype=np.dtype([('x', 'u1'), ('y', [('a', 'u1'), ('b', 'u1')])]),\n )\n\n def test_b8_bool_array(self):\n arr1 = np.array(\n [((True, True, False),), ((True, False, True),)],\n dtype=np.dtype([('x', ('?', (3,)))]),\n )\n self._test_b8(arr1)\n self._test_b8(\n arr1,\n dtype=np.dtype([('x', ('?', (3,)))]),\n )\n\n def _test_b8(self, arr1, dtype=None):\n path = self.mktemp()\n with tables.open_file(path, 'w') as f:\n if arr1.dtype.names:\n f.create_table('/', 'test', obj=arr1)\n else:\n f.create_array('/', 'test', obj=arr1)\n\n with h5py.File(path, 'r') as f:\n dset = f['test']\n\n # read uncast dset to make sure it raises as before\n with self.assertRaises(\n TypeError, msg='No NumPy equivalent for TypeBitfieldID exists'\n ):\n dset[:]\n\n # read cast dset and make sure it's equal\n if dtype is None:\n dtype = arr1.dtype\n with dset.astype(dtype):\n arr2 = dset[:]\n self.assertArrayEqual(arr2, arr1.astype(dtype, copy=False))\n\n # read uncast dataset again to ensure nothing changed permanantly\n with self.assertRaises(\n TypeError, msg='No NumPy equivalent for TypeBitfieldID exists'\n ):\n dset[:]\n" ]
[ [ "numpy.random.seed", "numpy.arange", "numpy.issubdtype", "numpy.dtype", "numpy.all", "numpy.typeDict.values", "numpy.argmax", "numpy.random.rand", "numpy.core.records.fromarrays", "numpy.array", "numpy.empty", "numpy.random.randint" ] ]
foamliu/GST-Tacotron-v2
[ "becca9275d2ec4a560287c63f9db28a3245cd188" ]
[ "utils.py" ]
[ "import argparse\nimport logging\n\nimport cv2 as cv\nimport librosa\nimport matplotlib.pylab as plt\nimport numpy as np\nimport pinyin\nimport torch\n\nfrom config import sampling_rate, char_to_idx, idx_to_char, ref_wav\nfrom models.layers import STFT\n\n\ndef clip_gradient(optimizer, grad_clip):\n \"\"\"\n Clips gradients computed during backpropagation to avoid explosion of gradients.\n :param optimizer: optimizer with the gradients to be clipped\n :param grad_clip: clip value\n \"\"\"\n for group in optimizer.param_groups:\n for param in group['params']:\n if param.grad is not None:\n param.grad.data.clamp_(-grad_clip, grad_clip)\n\n\ndef save_checkpoint(epoch, epochs_since_improvement, model, optimizer, loss, is_best):\n state = {'epoch': epoch,\n 'epochs_since_improvement': epochs_since_improvement,\n 'loss': loss,\n 'model': model,\n 'optimizer': optimizer}\n\n filename = 'checkpoint.tar'\n torch.save(state, filename)\n # If this checkpoint is the best so far, store a copy so it doesn't get overwritten by a worse checkpoint\n if is_best:\n torch.save(state, 'BEST_checkpoint.tar')\n\n\nclass AverageMeter(object):\n \"\"\"\n Keeps track of most recent, average, sum, and count of a metric.\n \"\"\"\n\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n\ndef adjust_learning_rate(optimizer, shrink_factor):\n \"\"\"\n Shrinks learning rate by a specified factor.\n :param optimizer: optimizer whose learning rate must be shrunk.\n :param shrink_factor: factor in interval (0, 1) to multiply learning rate with.\n \"\"\"\n\n print(\"\\nDECAYING learning rate.\")\n for param_group in optimizer.param_groups:\n param_group['lr'] = param_group['lr'] * shrink_factor\n print(\"The new learning rate is %f\\n\" % (optimizer.param_groups[0]['lr'],))\n\n\ndef accuracy(scores, targets, k=1):\n batch_size = targets.size(0)\n _, ind = scores.topk(k, 1, True, True)\n correct = ind.eq(targets.view(-1, 1).expand_as(ind))\n correct_total = correct.view(-1).float().sum() # 0D tensor\n return correct_total.item() * (100.0 / batch_size)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Tacotron2')\n parser.add_argument('--epochs', default=10000, type=int)\n parser.add_argument('--max_norm', default=1, type=float, help='Gradient norm threshold to clip')\n # minibatch\n parser.add_argument('--batch_size', default=48, type=int)\n parser.add_argument('--num-workers', default=4, type=int, help='Number of workers to generate minibatch')\n # logging\n parser.add_argument('--print_freq', default=10, type=int, help='Frequency of printing training information')\n # optimizer\n parser.add_argument('--lr', default=1e-3, type=float, help='Init learning rate')\n parser.add_argument('--l2', default=1e-6, type=float, help='weight decay (L2)')\n parser.add_argument('--checkpoint', type=str, default=None, help='checkpoint')\n args = parser.parse_args()\n return args\n\n\ndef get_logger():\n logger = logging.getLogger()\n handler = logging.StreamHandler()\n formatter = logging.Formatter(\"%(asctime)s %(levelname)s \\t%(message)s\")\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n logger.setLevel(logging.INFO)\n return logger\n\n\ndef ensure_folder(folder):\n import os\n if not os.path.isdir(folder):\n os.mkdir(folder)\n\n\ndef pad_list(xs, pad_value):\n # From: espnet/src/nets/e2e_asr_th.py: pad_list()\n n_batch = len(xs)\n max_len = max(x.size(0) for x in xs)\n pad = xs[0].new(n_batch, max_len, *xs[0].size()[1:]).fill_(pad_value)\n for i in range(n_batch):\n pad[i, :xs[i].size(0)] = xs[i]\n return pad\n\n\ndef get_mask_from_lengths(lengths):\n max_len = torch.max(lengths).item()\n ids = torch.arange(0, max_len, out=torch.cuda.LongTensor(max_len))\n mask = (ids < lengths.unsqueeze(1)).byte()\n return mask\n\n\n# [-0.5, 0.5]\ndef normalize(yt):\n yt_max = np.max(yt)\n yt_min = np.min(yt)\n a = 1.0 / (yt_max - yt_min)\n b = -(yt_max + yt_min) / (2 * (yt_max - yt_min))\n\n yt = yt * a + b\n return yt\n\n\ndef load_wav_to_torch(full_path):\n # sampling_rate, data = read(full_path)\n y, sr = librosa.load(full_path, sampling_rate)\n yt, _ = librosa.effects.trim(y, top_db=20)\n yt = normalize(yt)\n return torch.FloatTensor(yt.astype(np.float32)), sr\n\n\ndef load_filepaths_and_text(filename, split=\"|\"):\n with open(filename, encoding='utf-8') as f:\n filepaths_and_text = [line.strip().split(split) for line in f]\n return filepaths_and_text\n\n\ndef to_gpu(x):\n x = x.contiguous()\n\n if torch.cuda.is_available():\n x = x.cuda(non_blocking=True)\n return torch.autograd.Variable(x)\n\n\ndef text_to_sequence(text):\n result = [char_to_idx[ch] for ch in text if ch in char_to_idx]\n return result\n\n\ndef sequence_to_text(seq):\n result = [idx_to_char[idx] for idx in seq]\n return result\n\n\ndef plot_data(data, figsize=(16, 4)):\n fig, axes = plt.subplots(1, len(data), figsize=figsize)\n for i in range(len(data)):\n axes[i].imshow(data[i], aspect='auto', origin='bottom',\n interpolation='none')\n\n\nclass Denoiser(torch.nn.Module):\n \"\"\" Removes model bias from audio produced with waveglow \"\"\"\n\n def __init__(self, waveglow, filter_length=1024, n_overlap=4,\n win_length=1024, mode='zeros'):\n super(Denoiser, self).__init__()\n self.stft = STFT(filter_length=filter_length,\n hop_length=int(filter_length / n_overlap),\n win_length=win_length).cuda()\n if mode == 'zeros':\n mel_input = torch.zeros(\n (1, 80, 88),\n dtype=waveglow.upsample.weight.dtype,\n device=waveglow.upsample.weight.device)\n elif mode == 'normal':\n mel_input = torch.randn(\n (1, 80, 88),\n dtype=waveglow.upsample.weight.dtype,\n device=waveglow.upsample.weight.device)\n else:\n raise Exception(\"Mode {} if not supported\".format(mode))\n\n with torch.no_grad():\n bias_audio = waveglow.infer(mel_input, sigma=0.0).float()\n bias_spec, _ = self.stft.transform(bias_audio)\n\n self.register_buffer('bias_spec', bias_spec[:, :, 0][:, :, None])\n\n def forward(self, audio, strength=0.1):\n audio_spec, audio_angles = self.stft.transform(audio.cuda().float())\n audio_spec_denoised = audio_spec - self.bias_spec * strength\n audio_spec_denoised = torch.clamp(audio_spec_denoised, 0.0)\n audio_denoised = self.stft.inverse(audio_spec_denoised, audio_angles)\n return audio_denoised\n\n\ndef test(model, step_num, loss, get_mel):\n model.eval()\n text = \"相对论直接和间接的催生了量子力学的诞生\"\n text = pinyin.get(text, format=\"numerical\", delimiter=\" \")\n sequence = np.array(text_to_sequence(text))[None, :]\n sequence = torch.autograd.Variable(torch.from_numpy(sequence)).cuda().long()\n\n ref_mel = get_mel(ref_wav)[None, :]\n ref_mel = torch.autograd.Variable(np.transpose(ref_mel, (0, 2, 1))).cuda().float()\n print('ref_mel.shape: ' + str(ref_mel.shape))\n\n with torch.no_grad():\n mel_outputs, mel_outputs_postnet, _, alignments = model.inference(sequence, ref_mel)\n print('inference done')\n plot_data((mel_outputs.float().data.cpu().numpy()[0],\n mel_outputs_postnet.float().data.cpu().numpy()[0],\n alignments.float().data.cpu().numpy()[0].T))\n print('plot done')\n title = 'step={0}, loss={1:.5f}'.format(step_num, loss)\n plt.title(title)\n filename = 'images/temp.jpg'\n ensure_folder('images')\n plt.savefig(filename)\n print('savefig done')\n img = cv.imread(filename)\n img = cv.cvtColor(img, cv.COLOR_BGR2RGB)\n img = img / 255.\n\n waveglow_path = 'waveglow_256channels.pt'\n waveglow = torch.load(waveglow_path)['model']\n waveglow.cuda().eval().half()\n for k in waveglow.convinv:\n k.float()\n\n mel_outputs_postnet = mel_outputs_postnet.type(torch.float16)\n with torch.no_grad():\n audio = waveglow.infer(mel_outputs_postnet, sigma=0.666)\n\n audio = audio[0].data.cpu().numpy()\n audio = audio.astype(np.float32)\n\n mel_outputs_postnet = mel_outputs_postnet.float().data.cpu().numpy()[0]\n np.save('mel_outputs.npy', mel_outputs_postnet)\n print('save mel done')\n\n return img, audio\n" ]
[ [ "torch.clamp", "torch.max", "numpy.min", "torch.load", "torch.zeros", "torch.randn", "torch.cuda.LongTensor", "matplotlib.pylab.title", "numpy.save", "torch.from_numpy", "numpy.max", "torch.save", "torch.no_grad", "torch.cuda.is_available", "numpy.transpose", "matplotlib.pylab.savefig", "torch.autograd.Variable" ] ]
RuthAngus/LSST-max
[ "88abfa4aedd5837c9d1f1b9e17a8fd2d1713488b" ]
[ "code/LSST_inject_and_recover.py" ]
[ "# coding: utf-8\n# # Recovering rotation periods in simulated LSST data\n# before you run this, remove the files: simulations/l45b-{0}/all_truths.txt &\n# results/l45b-{0}_{1}yr_results.txt\".format(b, yr)\n\nfrom __future__ import print_function\nimport numpy as np\n# import matplotlib.pyplot as plt\nimport pandas as pd\n\nimport sys\nimport os\n\nfrom gatspy.periodic import LombScargle\n\nfrom toy_simulator import simulate_LSST\nfrom trilegal_models import random_stars\nfrom compare_LSST import compare_pgram\nimport simple_gyro as sg\n\n\ndef find_nearest(array, value):\n \"\"\"\n Match a period to a bin.\n array: array of bin heights.\n value: the period of the star.\n Returns the value and index of the bin.\n \"\"\"\n m = np.abs(array-value) == np.abs(array-value).min()\n return array[m], m\n\n\ndef assign_amps(ps, log10P, log10R, stdR):\n \"\"\"\n Take periods and bin values and return an array of amplitudes.\n \"\"\"\n npi = np.array([find_nearest(10**log10P, p) for p in ps])\n inds = npi[:, 1]\n log_ranges = np.array([log10R[i] for i in inds])[:, 0]\n std_ranges = np.array([stdR[i] for i in inds])[:, 0]\n return np.random.randn(len(ps))*std_ranges + log_ranges\n\n\ndef make_arrays(data, temp_bin, ps, teff, rmag):\n \"\"\"\n Amplitude arrays for each temperature bin\n \"\"\"\n P, R, std = np.array(data[\"log10P\"]), np.array(data[\"log10R\"]), \\\n np.array(data[\"stdR\"])\n if temp_bin == 3500:\n m = teff < 3750\n elif temp_bin == 6000:\n m = teff > 6000\n else:\n m = (temp_bin - 250 < teff) * (teff < temp_bin + 250)\n periods, teffs, rmags = ps[m], teff[m], rmag[m]\n amplitudes = assign_amps(periods, P, R, std)\n return periods, amplitudes, teffs, rmags\n\n\ndef LSST_sig(m):\n \"\"\"\n Approximate the noise in figure 2 of arxiv:1603.06638 from the apparent\n r-mag.\n Returns the noise in magnitudes and ppm.\n \"\"\"\n if m < 19:\n return .005\n mags = np.array([19, 20, 21, 22, 23, 24, 25])\n sigs = np.array([.005, .007, .01, .02, .03, .1, .2])\n return sigs[np.abs(mags - m) == np.abs(mags-m).min()][0]\n\n\ndef pgram(N, years, fname):\n \"\"\"\n Calculate periodograms of LSST light curves.\n \"\"\"\n ps = np.linspace(2, 100, 1000) # the period array (in days)\n\n print(\"Computing periodograms\")\n # Now compute LS pgrams for a set of LSST light curves & save highest peak\n ids = np.arange(N)\n periods = np.zeros_like(ids)\n for i, id in enumerate(ids):\n sid = str(int(id)).zfill(4)\n x, y, yerr = np.genfromtxt(\"simulations/{0}/{1}.txt\".format(fname,\n sid)).T\n m = x < years * 365.25\n xt, yt, yerrt = x[m], y[m], yerr[m][m]\n model = LombScargle().fit(xt, yt, yerrt) # compute pgram\n pgram = model.periodogram(ps)\n\n # find peaks\n peaks = np.array([j for j in range(1, len(ps)-1) if pgram[j-1] <\n pgram[j] and pgram[j+1] < pgram[j]])\n if len(peaks):\n period = ps[pgram == max(pgram[peaks])][0]\n else:\n period = 0\n\n periods[i] = period\n\n data = np.vstack((ids, periods))\n f = open(\"results/{0}_{1}yr_results.txt\".format(fname, years), \"a\")\n np.savetxt(f, data.T)\n f.close()\n return periods\n\n\ndef inject(fname, N):\n \"\"\"\n Simulate rotation periods for LSST targets and attempt to recover those\n rotation periods.\n Saves an array of injected periods (days), recovered periods (days), Teff,\n rmag, injected amplitudes (ppm) and noise (ppm).\n 'true_ps, periods, logamps, teffs, rmags, true_as, noises_ppm'\n params:\n ------\n fname: (str)\n The coordinates of the field, e.g. \"l45b-10\".\n N: (int)\n The number of simulations.\n \"\"\"\n\n print(\"Loading TRILEGAL output file...\")\n # Randomly select targets from a TRILEGAL output.\n logAges, bvs, logTeff, rmag = random_stars(\"{0}.dat\".format(fname), N)\n teff = 10**logTeff\n\n # Calculate periods from ages and colours for cool stars\n m = bvs > .4 # select only cool stars\n cool_ages = 10**logAges[m] * 1e-9\n cool_ps = sg.period(cool_ages, bvs[m])\n cool_teffs = teff[m]\n cool_rmags = rmag[m]\n\n # Draw from a sum of two Gaussians (modelled in another notebook) that\n # describes the period distribution for hot stars. Approximations:\n # I have lumped all stars with colour < 0.4 in together AND I actually\n # used teff = 6250, not B-V = 0.4 in the other notebook.\n hot_ages = 10**logAges[~m] * 1e-9 # select hot stars\n hot_teffs = teff[~m]\n hot_rmags = rmag[~m]\n\n # copy parameters for two Gaussians from hot_stars ipython notebook\n A1, A2, mu1, mu2, sig1, sig2 = 254.11651209, 49.8149765, 3.00751724, \\\n 3.73399554, 2.26525979, 8.31739725\n\n hot_ps = np.zeros_like(hot_ages)\n hot_ps1 = np.random.randn(int(len(hot_ages)*(1 - A2/A1)))*sig1 + mu1\n hot_ps2 = np.random.randn(int(len(hot_ages)*(A2/A1)))*sig2 + mu2\n hot_ps[:len(hot_ps1)] = hot_ps1\n hot_ps[len(hot_ps1):len(hot_ps1) + len(hot_ps2)] = hot_ps2\n tot = len(hot_ps1) + len(hot_ps2)\n hot_ps[tot:] = np.random.randn(len(hot_ps)-tot)*sig2 + mu2\n\n # combine the modes\n # age = np.concatenate((cool_ages, hot_ages))\n ps = np.concatenate((cool_ps, hot_ps))\n teff = np.concatenate((cool_teffs, hot_teffs))\n rmag = np.concatenate((cool_rmags, hot_rmags))\n\n print(\"Calculating amplitudes...\")\n # Use Derek's results to calculate amplitudes\n # Column headings: log10P, log10R, stdR, Nbin\n d35 = pd.read_csv(os.path.join(DATA_DIR, \"rot_v_act3500.txt\"))\n d40 = pd.read_csv(os.path.join(DATA_DIR, \"rot_v_act4000.txt\"))\n d45 = pd.read_csv(os.path.join(DATA_DIR, \"rot_v_act4500.txt\"))\n d50 = pd.read_csv(os.path.join(DATA_DIR, \"rot_v_act5000.txt\"))\n d55 = pd.read_csv(os.path.join(DATA_DIR, \"rot_v_act5500.txt\"))\n d60 = pd.read_csv(os.path.join(DATA_DIR, \"rot_v_act6000.txt\"))\n\n # Assign amplitudes\n pers, logamps, teffs, rmags = \\\n np.concatenate((make_arrays(d35, 3500, ps, teff, rmag),\n make_arrays(d40, 4000, ps, teff, rmag),\n make_arrays(d45, 4500, ps, teff, rmag),\n make_arrays(d50, 5000, ps, teff, rmag),\n make_arrays(d55, 5500, ps, teff, rmag),\n make_arrays(d60, 6000, ps, teff, rmag)),\n axis=1)\n amps = 10**logamps # parts per million\n noises_mag = np.array([LSST_sig(mag) for mag in rmags])\n noises_ppm = (1 - 10**(-noises_mag/2.5)) * 1e6\n\n # Simulate light curves\n print(\"Simulating light curves...\")\n if not os.path.exists(fname):\n os.makedirs(fname)\n\n filters = [\"u\", \"g\", \"r\", \"i\", \"z\"]\n x, depth, filt = [], [], []\n for f in filters:\n path = os.path.join(DATA_DIR,\n \"{0}_{1}_cadence.txt\".format(fname, f))\n xf, depthf = np.genfromtxt(path).T\n x.append(xf)\n depth.append(depthf)\n fs = np.zeros(len(xf), dtype=\"str\")\n for i, _ in enumerate(fs):\n fs[i] = f\n filt.append(fs)\n array = lambda arr: np.array([i for j in arr for i in j])\n x, depth, filt = array(x), array(depth), array(filt)\n inds = np.argsort(x)\n x, depth, filt = x[inds], depth[inds], filt[inds]\n\n print(len(pers), \"stars to simulate\")\n [simulate_LSST(x, depth, filt, i, pers[i], amps[i], SIM_DIR,\n noises_ppm[i], plot=True) for i in range(len(pers))]\n\n # save the true values\n ids = np.arange(len(pers))\n data = np.vstack((ids, pers, amps))\n np.savetxt(os.path.join(path, \"truth.txt\", data.T))\n\n print(\"Saving results\")\n data = np.vstack((pers, amps, teffs, rmags, noises_ppm))\n np.savetxt(os.path.join(RESULTS_DIR, \"parameters_{0}.txt\".format(fname),\n data.T))\n return pers, amps, teffs, rmags, noises_ppm\n\n\nif __name__ == \"__main__\":\n path = \"/Users/ruthangus/projects/LSST-max/code/\"\n DATA_DIR = os.path.join(path, \"data\")\n RESULTS_DIR = os.path.join(path, \"results\")\n SIM_DIR = os.path.join(path, \"simulations\")\n fname = \"l{0}b{1}\".format(sys.argv[1], sys.argv[2])\n\n print(\"Simulating light curves...\")\n N = 2000\n pers, amps, teffs, rmags, noises_ppm = inject(\"{0}\".format(fname), N)\n\n print(\"Recovering periods...\")\n pers, amps, teffs, rmags, noises_ppm = \\\n np.genfromtxt(\"parameters_{0}.txt\".format(fname)).T\n N = len(pers)\n years = [1, 5, 10]\n for year in years:\n periods = pgram(N, year, fname)\n data = np.vstack((pers, periods, np.log(amps), teffs, rmags, amps,\n noises_ppm))\n np.savetxt(\"results/{0}yr_results{1}.txt\".format(year, fname),\n data.T)\n compare_pgram(fname, year)\n" ]
[ [ "numpy.log", "numpy.abs", "numpy.linspace", "numpy.arange", "numpy.genfromtxt", "numpy.concatenate", "numpy.zeros_like", "numpy.savetxt", "numpy.argsort", "numpy.array", "numpy.vstack" ] ]
dpfried/ImageCaptioning.pytorch
[ "a2330f1e1e16c334ddb3228a4db9fdde6194d9cd" ]
[ "captioning/utils/eval_multi.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport torch\nimport torch.nn as nn\n\nimport numpy as np\nimport json\nfrom json import encoder\nimport random\nimport string\nimport time\nimport os\nimport sys\nfrom . import misc as utils\nfrom .eval_utils import getCOCO\n\nfrom .div_utils import compute_div_n, compute_global_div_n\n\nSPICE_THREADS=4\n\nimport sys\ntry:\n sys.path.append(\"coco-caption\")\n annFile = 'coco-caption/annotations/captions_val2014.json'\n from pycocotools.coco import COCO\n from pycocoevalcap.eval import COCOEvalCap\n from pycocoevalcap.eval_spice import COCOEvalCapSpice\n from pycocoevalcap.tokenizer.ptbtokenizer import PTBTokenizer\n from pycocoevalcap.bleu.bleu import Bleu\n sys.path.append(\"cider\")\n from pyciderevalcap.cider.cider import Cider\nexcept:\n print('Warning: requirements for eval_multi not satisfied')\n\n\ndef eval_allspice(dataset, preds_n, model_id, split):\n coco = getCOCO(dataset)\n valids = coco.getImgIds()\n \n capsById = {}\n for d in preds_n:\n capsById[d['image_id']] = capsById.get(d['image_id'], []) + [d]\n\n # filter results to only those in MSCOCO validation set (will be about a third)\n preds_filt_n = [p for p in preds_n if p['image_id'] in valids]\n print('using %d/%d predictions_n' % (len(preds_filt_n), len(preds_n)))\n cache_path_n = os.path.join('eval_results/', model_id + '_' + split + '_n.json')\n json.dump(preds_filt_n, open(cache_path_n, 'w')) # serialize to temporary json file. Sigh, COCO API...\n\n # Eval AllSPICE\n cocoRes_n = coco.loadRes(cache_path_n)\n cocoEvalAllSPICE = COCOEvalCapSpice(coco, cocoRes_n)\n cocoEvalAllSPICE.params['image_id'] = cocoRes_n.getImgIds()\n cocoEvalAllSPICE.evaluate()\n\n out = {}\n for metric, score in cocoEvalAllSPICE.eval.items():\n out['All'+metric] = score\n\n imgToEvalAllSPICE = cocoEvalAllSPICE.imgToEval\n # collect SPICE_sub_score\n for k in list(imgToEvalAllSPICE.values())[0]['SPICE'].keys():\n if k != 'All':\n out['AllSPICE_'+k] = np.array([v['SPICE'][k]['f'] for v in imgToEvalAllSPICE.values()])\n out['AllSPICE_'+k] = (out['AllSPICE_'+k][out['AllSPICE_'+k]==out['AllSPICE_'+k]]).mean()\n for p in preds_filt_n:\n image_id, caption = p['image_id'], p['caption']\n imgToEvalAllSPICE[image_id]['caption'] = capsById[image_id]\n return {'overall': out, 'imgToEvalAllSPICE': imgToEvalAllSPICE}\n\ndef eval_oracle(dataset, preds_n, model_id, split):\n cache_path = os.path.join('eval_results/', model_id + '_' + split + '_n.json')\n\n coco = getCOCO(dataset)\n valids = coco.getImgIds()\n\n capsById = {}\n for d in preds_n:\n capsById[d['image_id']] = capsById.get(d['image_id'], []) + [d]\n \n sample_n = capsById[list(capsById.keys())[0]]\n for i in range(len(capsById[list(capsById.keys())[0]])):\n preds = [_[i] for _ in capsById.values()]\n\n json.dump(preds, open(cache_path, 'w')) # serialize to temporary json file. Sigh, COCO API...\n\n cocoRes = coco.loadRes(cache_path)\n cocoEval = COCOEvalCap(coco, cocoRes, spice_threads=SPICE_THREADS)\n cocoEval.params['image_id'] = cocoRes.getImgIds()\n cocoEval.evaluate()\n\n imgToEval = cocoEval.imgToEval\n for img_id in capsById.keys():\n tmp = imgToEval[img_id]\n for k in tmp['SPICE'].keys():\n if k != 'All':\n tmp['SPICE_'+k] = tmp['SPICE'][k]['f']\n if tmp['SPICE_'+k] != tmp['SPICE_'+k]: # nan\n tmp['SPICE_'+k] = -100\n tmp['SPICE'] = tmp['SPICE']['All']['f']\n if tmp['SPICE'] != tmp['SPICE']: tmp['SPICE'] = -100\n capsById[img_id][i]['scores'] = imgToEval[img_id]\n\n out = {'overall': {}, 'ImgToEval': {}}\n for img_id in capsById.keys():\n out['ImgToEval'][img_id] = {}\n for metric in capsById[img_id][0]['scores'].keys():\n if metric == 'image_id': continue\n out['ImgToEval'][img_id]['oracle_'+metric] = max([_['scores'][metric] for _ in capsById[img_id]])\n out['ImgToEval'][img_id]['avg_'+metric] = sum([_['scores'][metric] for _ in capsById[img_id]]) / len(capsById[img_id])\n out['ImgToEval'][img_id]['captions'] = capsById[img_id]\n for metric in list(out['ImgToEval'].values())[0].keys():\n if metric == 'captions':\n continue\n tmp = np.array([_[metric] for _ in out['ImgToEval'].values()])\n tmp = tmp[tmp!=-100]\n out['overall'][metric] = tmp.mean()\n \n return out\n\ndef eval_div_stats(dataset, preds_n, model_id, split):\n tokenizer = PTBTokenizer()\n\n capsById = {}\n for i, d in enumerate(preds_n):\n d['id'] = i\n capsById[d['image_id']] = capsById.get(d['image_id'], []) + [d]\n\n n_caps_perimg = len(capsById[list(capsById.keys())[0]])\n print(n_caps_perimg)\n _capsById = capsById # save the untokenized version\n capsById = tokenizer.tokenize(capsById)\n\n div_1, adiv_1 = compute_div_n(capsById,1)\n div_2, adiv_2 = compute_div_n(capsById,2)\n\n globdiv_1, _= compute_global_div_n(capsById,1)\n\n print('Diversity Statistics are as follows: \\n Div1: %.2f, Div2: %.2f, gDiv1: %d\\n'%(div_1,div_2, globdiv_1))\n\n # compute mbleu\n scorer = Bleu(4)\n all_scrs = []\n scrperimg = np.zeros((n_caps_perimg, len(capsById)))\n\n for i in range(n_caps_perimg):\n tempRefsById = {}\n candsById = {}\n for k in capsById:\n tempRefsById[k] = capsById[k][:i] + capsById[k][i+1:]\n candsById[k] = [capsById[k][i]]\n\n score, scores = scorer.compute_score(tempRefsById, candsById)\n all_scrs.append(score)\n scrperimg[i,:] = scores[1]\n\n all_scrs = np.array(all_scrs)\n \n out = {}\n out['overall'] = {'Div1': div_1, 'Div2': div_2, 'gDiv1': globdiv_1}\n for k, score in zip(range(4), all_scrs.mean(axis=0).tolist()):\n out['overall'].update({'mBLeu_%d'%(k+1): score})\n imgToEval = {}\n for i,imgid in enumerate(capsById.keys()):\n imgToEval[imgid] = {'mBleu_2' : scrperimg[:,i].mean()}\n imgToEval[imgid]['individuals'] = []\n for j, d in enumerate(_capsById[imgid]):\n imgToEval[imgid]['individuals'].append(preds_n[d['id']])\n imgToEval[imgid]['individuals'][-1]['mBleu_2'] = scrperimg[j,i]\n out['ImgToEval'] = imgToEval\n\n print('Mean mutual Bleu scores on this set is:\\nmBLeu_1, mBLeu_2, mBLeu_3, mBLeu_4')\n print(all_scrs.mean(axis=0))\n\n return out\n\ndef eval_self_cider(dataset, preds_n, model_id, split):\n cache_path = os.path.join('eval_results/', model_id + '_' + split + '_n.json')\n\n coco = getCOCO(dataset)\n valids = coco.getImgIds()\n \n # Get Cider_scorer\n Cider_scorer = Cider(df='corpus')\n\n tokenizer = PTBTokenizer()\n gts = {}\n for imgId in valids:\n gts[imgId] = coco.imgToAnns[imgId]\n gts = tokenizer.tokenize(gts)\n\n for imgId in valids:\n Cider_scorer.cider_scorer += (None, gts[imgId])\n Cider_scorer.cider_scorer.compute_doc_freq()\n Cider_scorer.cider_scorer.ref_len = np.log(float(len(Cider_scorer.cider_scorer.crefs)))\n\n # Prepare captions\n capsById = {}\n for d in preds_n:\n capsById[d['image_id']] = capsById.get(d['image_id'], []) + [d]\n\n capsById = tokenizer.tokenize(capsById)\n imgIds = list(capsById.keys())\n scores = Cider_scorer.my_self_cider([capsById[_] for _ in imgIds])\n\n def get_div(eigvals):\n eigvals = np.clip(eigvals, 0, None)\n return -np.log(np.sqrt(eigvals[-1]) / (np.sqrt(eigvals).sum())) / np.log(len(eigvals))\n sc_scores = [get_div(np.linalg.eigvalsh(_/10)) for _ in scores]\n score = np.mean(np.array(sc_scores))\n \n imgToEval = {}\n for i, image_id in enumerate(imgIds):\n imgToEval[image_id] = {'self_cider': sc_scores[i], 'self_cider_mat': scores[i].tolist()}\n return {'overall': {'self_cider': score}, 'imgToEval': imgToEval}\n\n\n return score\n" ]
[ [ "numpy.linalg.eigvalsh", "numpy.array", "numpy.sqrt", "numpy.clip" ] ]
ebezzam/pyFFS
[ "29eac7a3305dcefe40b4cdc03f730fc9bd868eab" ]
[ "profile/bandlimited_interp1d_vary_width.py" ]
[ "import numpy as np\nimport pathlib as plib\nfrom pyffs import ffs_sample, ffs, fs_interp\nfrom pyffs.func import dirichlet\nimport matplotlib.pyplot as plt\nimport click\nfrom scipy.signal import resample\nfrom util import comparison_plot, plotting_setup\nimport time\n\n\[email protected]()\[email protected](\"--n_samples\", type=int, default=128)\[email protected](\"--n_trials\", type=int, default=10)\[email protected](\"--n_interp\", type=int, default=10000)\ndef profile_fs_interp(n_trials, n_samples, n_interp):\n fig_path = plotting_setup(linewidth=3, font_size=20)\n print(f\"\\nCOMPARING FFS AND FFT INTERP WITH {n_trials} TRIALS\")\n n_std = 0.5\n\n M = n_interp\n width_vals = np.logspace(-3, 0, 10)\n\n T, T_c = 1, 0\n N_FS = n_samples - 1\n sample_points, _ = ffs_sample(T, N_FS, T_c, n_samples, mod=np)\n diric_samples = dirichlet(sample_points, T, T_c, N_FS)\n t_ord = np.sort(sample_points)\n diric_samples_ord = dirichlet(t_ord, T, T_c, N_FS)\n\n proc_time = dict()\n proc_time_std = dict()\n for val in width_vals:\n\n width = val * T\n start = T_c - width / 2\n stop = T_c + width / 2\n\n # interpolation points\n points = np.linspace(start, stop, M, endpoint=True)\n dt = points[1] - points[0]\n N_target = int(np.ceil(T / dt))\n if dt > sample_points[1] - sample_points[0]:\n print(\"Interpolation coarser than original sampling, skipping...\")\n continue\n\n print(\"\\nPeriod percentage : {}\".format(val))\n proc_time[val] = dict()\n proc_time_std[val] = dict()\n\n # FFS\n _key = \"pyffs.fs_interp\"\n timings = []\n for _ in range(n_trials):\n start_time = time.time()\n diric_FS = ffs(diric_samples, T, T_c, N_FS)[:N_FS]\n fs_interp(diric_FS, T=T, a=start, b=stop, M=M, real_x=False)\n timings.append(time.time() - start_time)\n proc_time[val][_key] = np.mean(timings)\n proc_time_std[val][_key] = np.std(timings)\n print(\"-- {} : {} seconds\".format(_key, proc_time[val][_key]))\n\n # resample through zero padding\n _key = \"scipy.signal.resample\"\n timings = []\n for _ in range(n_trials):\n start_time = time.time()\n resample(diric_samples_ord, N_target, t=np.sort(sample_points))\n\n timings.append(time.time() - start_time)\n proc_time[val][_key] = np.mean(timings)\n proc_time_std[val][_key] = np.std(timings)\n print(\"-- {} : {} seconds\".format(_key, proc_time[val][_key]))\n\n # plot results\n fig, ax = plt.subplots()\n comparison_plot(proc_time, proc_time_std, n_std, ax)\n ax.legend(loc=\"upper right\")\n ax.set_title(f\"{n_samples} samples, {M} interpolation points\")\n ax.set_xlabel(\"Percentage of period\")\n fig.tight_layout()\n fig.savefig(plib.Path(fig_path) / \"bandlimited_interp1d_vary_width.png\")\n\n plt.show()\n\n\nif __name__ == \"__main__\":\n profile_fs_interp()\n" ]
[ [ "numpy.linspace", "numpy.logspace", "matplotlib.pyplot.subplots", "numpy.sort", "numpy.ceil", "numpy.std", "numpy.mean", "matplotlib.pyplot.show" ] ]
sujaylokesh/proj3
[ "de86aec64b1ee142c073fb3096f50bd0310ebd88" ]
[ "src/encoders/cbow_seq_encoder.py" ]
[ "from typing import Dict, Any\n\nimport tensorflow as tf\n\nfrom .masked_seq_encoder import MaskedSeqEncoder\nfrom utils.tfutils import pool_sequence_embedding\n\n\nclass CBoWEncoder(MaskedSeqEncoder):\n @classmethod\n def get_default_hyperparameters(cls) -> Dict[str, Any]:\n encoder_hypers = { 'cbow_pool_mode': 'weighted_mean',\n }\n hypers = super().get_default_hyperparameters()\n hypers.update(encoder_hypers)\n return hypers\n\n def __init__(self, label: str, hyperparameters: Dict[str, Any], metadata: Dict[str, Any]):\n super().__init__(label, hyperparameters, metadata)\n\n def make_model(self, is_train: bool=False) -> tf.Tensor:\n with tf.variable_scope(\"cbow_encoder\"):\n self._make_placeholders()\n\n self.seq_tokens_embeddings = self.embedding_layer(self.placeholders['tokens']) # batch size x max seq len x emb dim\n seq_token_mask = self.placeholders['tokens_mask']\n seq_token_lengths = tf.reduce_sum(seq_token_mask, axis=1) # B\n\n batch_seq_len = self.seq_tokens_embeddings.get_shape().dims[1].value\n\n # pad seqs \n paddings = tf.constant([[0, 0], [2, 2], [0, 0]])\n self.seq_tokens_embeddings = tf.pad(self.seq_tokens_embeddings, paddings, \"CONSTANT\")\n\n self.seq_tokens_embeddings = tf.map_fn(self.token_sums, tf.range(0, batch_seq_len, 1), parallel_iterations=1, dtype=(tf.float32)) # max seq len x batch size x emb dim\n\n # perm dims\n self.seq_tokens_embeddings = tf.transpose(self.seq_tokens_embeddings, perm=[1, 0, 2]) # batch size x max seq len x emb dim\n\n return pool_sequence_embedding(self.get_hyper('cbow_pool_mode').lower(),\n sequence_token_embeddings=self.seq_tokens_embeddings,\n sequence_lengths=seq_token_lengths,\n sequence_token_masks=seq_token_mask,\n is_train=is_train)\n\n def token_sums(self, t):\n x = self.seq_tokens_embeddings\n\n context = tf.concat( [ x[:, t:t+2, :], x[:, t+3:t+5, :] ], axis=1) # batch size x 4 x emb dim\n\n return tf.reduce_sum(context, 1) # batch size x emb dim" ]
[ [ "tensorflow.concat", "tensorflow.constant", "tensorflow.transpose", "tensorflow.range", "tensorflow.reduce_sum", "tensorflow.pad", "tensorflow.variable_scope" ] ]
Saraharas/ParlAI
[ "9cb89024a5852e68c81466a70f16f692de8cff97", "9cb89024a5852e68c81466a70f16f692de8cff97" ]
[ "projects/anti_scaling/distillation.py", "tests/nightly/gpu/test_gpt2.py" ]
[ "#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\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\"\"\"\nCode for distilling a transformer/generator model.\n\"\"\"\n\nimport os\nfrom abc import ABC, abstractmethod\nfrom typing import Any, Dict, List, Tuple, Type, Union\n\nimport torch\nfrom torch import nn as nn\nfrom torch.nn import functional as F\n\nfrom parlai.agents.bart.bart import BartAgent\nfrom parlai.agents.transformer.modules import (\n MultiHeadAttention,\n TransformerDecoderLayer,\n TransformerEncoderLayer,\n)\nfrom parlai.agents.transformer.transformer import TransformerGeneratorAgent\nfrom parlai.core.agents import create_agent_from_model_file\nfrom parlai.core.metrics import AverageMetric\nfrom parlai.core.opt import Opt\nfrom parlai.core.torch_agent import Batch\nfrom parlai.core.torch_generator_agent import PPLMetric, TorchGeneratorAgent\nfrom parlai.utils.misc import AttrDict\nfrom parlai.utils.torch import NEAR_INF_FP16\nfrom parlai.utils.typing import TShared\n\n\nclass OutputRecorder:\n \"\"\"\n Saves all outputs from modules that it is registered to.\n \"\"\"\n\n def __init__(self):\n self.outputs = []\n\n def __call__(self, module: nn.Module, module_in: Any, module_out: Any):\n self.outputs.append(module_out)\n\n def clear(self):\n self.outputs = []\n\n\nclass ForwardPassOutputs(AttrDict):\n \"\"\"\n Provides dot access to all outputs of the forward passes of the encoder and decoder.\n \"\"\"\n\n mask: torch.BoolTensor\n tokens_per_example: torch.Tensor\n num_tokens: torch.Tensor\n context_mask: torch.BoolTensor\n context_tokens_per_example: torch.Tensor\n num_context_tokens: torch.Tensor\n task_loss: torch.Tensor\n teacher_scores: torch.Tensor\n teacher_enc_output: torch.Tensor\n teacher_embedding_outputs: Dict[str, torch.Tensor]\n teacher_hidden_states: Dict[str, List[torch.Tensor]]\n teacher_attention_matrices: Dict[str, List[Dict[str, torch.Tensor]]]\n student_output: tuple\n student_scores: torch.Tensor\n student_enc_output: torch.Tensor\n student_embedding_outputs: Dict[str, torch.Tensor]\n student_hidden_states: Dict[str, List[torch.Tensor]]\n student_attention_matrices: Dict[str, List[Dict[str, torch.Tensor]]]\n\n def __init__(\n self,\n mask,\n tokens_per_example,\n num_tokens,\n context_mask,\n context_tokens_per_example,\n num_context_tokens,\n task_loss,\n teacher_scores,\n teacher_enc_output,\n teacher_embedding_outputs,\n teacher_hidden_states,\n teacher_attention_matrices,\n student_output,\n student_scores,\n student_enc_output,\n student_embedding_outputs,\n student_hidden_states,\n student_attention_matrices,\n ):\n super().__init__(\n mask=mask,\n tokens_per_example=tokens_per_example,\n num_tokens=num_tokens,\n context_mask=context_mask,\n context_tokens_per_example=context_tokens_per_example,\n num_context_tokens=num_context_tokens,\n task_loss=task_loss,\n teacher_scores=teacher_scores,\n teacher_enc_output=teacher_enc_output,\n teacher_embedding_outputs=teacher_embedding_outputs,\n teacher_hidden_states=teacher_hidden_states,\n teacher_attention_matrices=teacher_attention_matrices,\n student_output=student_output,\n student_scores=student_scores,\n student_enc_output=student_enc_output,\n student_embedding_outputs=student_embedding_outputs,\n student_hidden_states=student_hidden_states,\n student_attention_matrices=student_attention_matrices,\n )\n\n\nclass AbstractDistillTransformerAgentMixin(ABC):\n @classmethod\n def add_cmdline_args(cls, argparser):\n agent = argparser.add_argument_group('AbstractDistillTransformer arguments')\n agent.add_argument('--teacher-model', help='The teacher model file')\n agent.add_argument(\n '--task-loss-coeff',\n type=float,\n default=1,\n help='Coefficient on MLE loss on task',\n )\n agent.add_argument(\n '--encoder-loss-coeff',\n type=float,\n default=0,\n help='Coefficient on teacher loss on encoder output',\n )\n agent.add_argument(\n '--hidden-loss-coeff',\n type=float,\n default=0,\n help='Coefficient on teacher loss on encoder/decoder hidden layers',\n )\n agent.add_argument(\n '--pred-loss-coeff',\n type=float,\n default=0,\n help='Coefficient on KL teacher loss on prediction layer',\n )\n return agent\n\n def __init__(self, opt, shared=None):\n\n # Define coefficients\n self.task_loss_coeff = opt['task_loss_coeff']\n self.encoder_loss_coeff = opt['encoder_loss_coeff']\n self.hidden_loss_coeff = opt['hidden_loss_coeff']\n self.pred_loss_coeff = opt['pred_loss_coeff']\n\n assert (\n opt.get('model_parallel', False) is False\n ), 'model_parallel is not currently supported for distillation!'\n\n # Create teacher model\n if shared is None:\n to_copy = {'no_cuda', 'model_parallel', 'fp16', 'fp16_impl', 'gpu'}\n override = {k: opt[k] for k in to_copy}\n override['datatype'] = 'train:evalmode' # Don't initialize the optimizer\n teacher_agent = create_agent_from_model_file(opt['teacher_model'], override)\n self.teacher_model = teacher_agent.model\n assert teacher_agent.opt['n_heads'] == opt['n_heads']\n self.teacher_model.eval()\n\n super().__init__(opt, shared)\n\n def build_model(self):\n\n student_model = super().build_model()\n\n teacher_model = self._get_teacher_model()\n\n # Define the mapping between teacher and student encoder layers\n self.student_num_enc_layers = len(student_model.encoder.layers)\n self.teacher_num_enc_layers = len(teacher_model.encoder.layers)\n self.enc_layer_ratio = self.teacher_num_enc_layers / self.student_num_enc_layers\n self.mapped_enc_layers = []\n for i in range(self.student_num_enc_layers):\n j = int((i + 1) * self.enc_layer_ratio) - 1\n self.mapped_enc_layers.append(j)\n\n # Define the mapping between teacher and student decoder layers\n self.student_num_dec_layers = len(student_model.decoder.layers)\n self.teacher_num_dec_layers = len(teacher_model.decoder.layers)\n self.dec_layer_ratio = self.teacher_num_dec_layers / self.student_num_dec_layers\n self.mapped_dec_layers = []\n for i in range(self.student_num_dec_layers):\n j = int((i + 1) * self.dec_layer_ratio) - 1\n self.mapped_dec_layers.append(j)\n\n # Register hooks to record outputs\n encoder_module_map = {\n 'layers': TransformerEncoderLayer,\n 'attentions': MultiHeadAttention,\n }\n decoder_module_map = {\n 'layers': TransformerDecoderLayer,\n 'attentions': MultiHeadAttention,\n }\n self.hooks = {\n 'teacher': {\n 'encoder': self._register_series_of_hooks(\n model=teacher_model.encoder, module_map=encoder_module_map\n ),\n 'decoder': self._register_series_of_hooks(\n model=teacher_model.decoder, module_map=decoder_module_map\n ),\n },\n 'student': {\n 'encoder': self._register_series_of_hooks(\n model=student_model.encoder, module_map=encoder_module_map\n ),\n 'decoder': self._register_series_of_hooks(\n model=student_model.decoder, module_map=decoder_module_map\n ),\n },\n }\n\n # Separately register hooks for the token embeddings, which are the same for\n # the encoder and decoder\n self.hooks['teacher']['embeddings'] = OutputRecorder()\n teacher_model.embeddings.register_forward_hook(\n self.hooks['teacher']['embeddings']\n )\n self.hooks['student']['embeddings'] = OutputRecorder()\n student_model.embeddings.register_forward_hook(\n self.hooks['student']['embeddings']\n )\n\n return student_model\n\n def _get_teacher_model(self) -> nn.Module:\n \"\"\"\n Return the teacher model.\n\n This logic is needed because the teacher model may be wrapped by\n torch.nn.parallel.DistributedDataParallel.\n \"\"\"\n if hasattr(self.teacher_model, 'module'):\n return self.teacher_model.module\n else:\n return self.teacher_model\n\n def _register_series_of_hooks(\n self, model: nn.Module, module_map: Dict[str, Type[nn.Module]]\n ) -> Dict[str, OutputRecorder]:\n \"\"\"\n Register hooks in modules of the model, given the mapping of module types.\n\n `module_map` is a dict whose keys are module-type names and whose values are\n module types. For each module type, during each forward pass of `model`, all\n outputs of modules of that type will be saved to `hooks[module_type].outputs`.\n \"\"\"\n hooks = {}\n for module_name, module_type in module_map.items():\n hooks[module_name] = OutputRecorder()\n for module in model.modules():\n if isinstance(module, module_type):\n module.register_forward_hook(hooks[module_name])\n return hooks\n\n @abstractmethod\n def compute_loss(self, batch, return_output=False):\n \"\"\"\n Return the loss.\n\n This will likely call self._perform_forward_passes().\n \"\"\"\n\n def _perform_forward_passes(self, batch: Batch) -> ForwardPassOutputs:\n \"\"\"\n Perform forward passes through the student and teacher and pass back outputs.\n \"\"\"\n\n assert isinstance(self, TorchGeneratorAgent)\n # Code relies on methods\n\n mask = batch.label_vec != self.NULL_IDX\n\n self._clear_hook_outputs(self.hooks)\n\n # Forward pass through teacher model\n with torch.no_grad():\n teacher_scores, teacher_preds, teacher_enc_states = self.teacher_model(\n *self._model_input(batch), ys=batch.label_vec\n )\n teacher_enc_output, context_mask = teacher_enc_states\n\n # Forward pass through student model\n task_loss, student_output = super().compute_loss(batch, return_output=True)\n student_scores, student_preds, student_enc_states = student_output\n student_enc_output, _ = student_enc_states\n\n # Compile all outputs given the hooks\n teacher_embedding_outputs = self._extract_embedding_outputs(\n hooks=self.hooks['teacher']\n )\n student_embedding_outputs = self._extract_embedding_outputs(\n hooks=self.hooks['student']\n )\n teacher_hidden_states = self._extract_hidden_states(\n hooks=self.hooks['teacher'],\n num_enc_layers=self.teacher_num_enc_layers,\n num_dec_layers=self.teacher_num_dec_layers,\n )\n student_hidden_states = self._extract_hidden_states(\n hooks=self.hooks['student'],\n num_enc_layers=self.student_num_enc_layers,\n num_dec_layers=self.student_num_dec_layers,\n )\n teacher_attention_matrices = self._extract_attention_matrices(\n hooks=self.hooks['teacher'],\n num_enc_layers=self.teacher_num_enc_layers,\n num_dec_layers=self.teacher_num_dec_layers,\n )\n student_attention_matrices = self._extract_attention_matrices(\n hooks=self.hooks['student'],\n num_enc_layers=self.student_num_enc_layers,\n num_dec_layers=self.student_num_dec_layers,\n )\n self._clear_hook_outputs(self.hooks)\n\n tokens_per_example = mask.sum(dim=-1)\n num_tokens = mask.sum()\n context_tokens_per_example = context_mask.sum(dim=-1)\n num_context_tokens = context_mask.sum()\n\n # If needed, perform further manipulation of the mask tensor\n mask = self._manipulate_mask(\n mask=mask, student_scores=student_scores, batch=batch\n )\n\n # Record teacher accuracy\n teacher_acc = ((student_preds == teacher_preds) * mask).sum(dim=-1)\n self.record_local_metric(\n 'teacher_acc', AverageMetric.many(teacher_acc, tokens_per_example)\n )\n\n return ForwardPassOutputs(\n mask=mask,\n tokens_per_example=tokens_per_example,\n num_tokens=num_tokens,\n context_mask=context_mask,\n context_tokens_per_example=context_tokens_per_example,\n num_context_tokens=num_context_tokens,\n task_loss=task_loss,\n teacher_scores=teacher_scores,\n teacher_enc_output=teacher_enc_output,\n teacher_embedding_outputs=teacher_embedding_outputs,\n teacher_hidden_states=teacher_hidden_states,\n teacher_attention_matrices=teacher_attention_matrices,\n student_output=student_output,\n student_scores=student_scores,\n student_enc_output=student_enc_output,\n student_embedding_outputs=student_embedding_outputs,\n student_hidden_states=student_hidden_states,\n student_attention_matrices=student_attention_matrices,\n )\n\n def _manipulate_mask(\n self, mask: torch.BoolTensor, student_scores: torch.Tensor, batch: Batch\n ) -> torch.BoolTensor:\n \"\"\"\n If necessary, perform further manipulations of the mask.\n\n Needed for BART-based student models to add in an extra start token.\n \"\"\"\n if hasattr(super(), '_manipulate_mask'):\n # Defer to any agent-specific method for manipulating the mask\n return super()._manipulate_mask(\n mask=mask, student_scores=student_scores, batch=batch\n )\n else:\n return mask\n\n def _extract_embedding_outputs(\n self, hooks: Dict[str, Dict[str, OutputRecorder]]\n ) -> Dict[str, torch.Tensor]:\n \"\"\"\n Extract out the encoder and decoder embedding outputs.\n \"\"\"\n assert len(hooks['embeddings'].outputs) == 2\n return {\n 'encoder': hooks['embeddings'].outputs[0],\n 'decoder': hooks['embeddings'].outputs[1],\n }\n\n def _extract_hidden_states(\n self,\n hooks: Dict[str, Dict[str, OutputRecorder]],\n num_enc_layers: int,\n num_dec_layers: int,\n ) -> Dict[str, List[torch.Tensor]]:\n \"\"\"\n Extract out encoder/decoder hidden states per layer.\n \"\"\"\n assert len(hooks['encoder']['layers'].outputs) == num_enc_layers\n assert len(hooks['decoder']['layers'].outputs) == num_dec_layers\n return {\n 'encoder': hooks['encoder']['layers'].outputs,\n 'decoder': [out_[0] for out_ in hooks['decoder']['layers'].outputs],\n }\n\n def _extract_attention_matrices(\n self,\n hooks: Dict[str, Dict[str, OutputRecorder]],\n num_enc_layers: int,\n num_dec_layers: int,\n ) -> Dict[str, List[Dict[str, torch.Tensor]]]:\n \"\"\"\n Extract out encoder/decoder attention matrices per layer and attention type.\n \"\"\"\n assert len(hooks['encoder']['attentions'].outputs) == num_enc_layers\n assert len(hooks['decoder']['attentions'].outputs) == 2 * num_dec_layers\n output_idx = 2 # The position of the attention matrix among the outputs\n return {\n 'encoder': [\n {\n 'self_attn': hooks['encoder']['attentions'].outputs[layer_idx][\n output_idx\n ]\n }\n for layer_idx in range(num_enc_layers)\n ],\n 'decoder': [\n {\n 'self_attn': hooks['decoder']['attentions'].outputs[2 * layer_idx][\n output_idx\n ],\n 'encoder_attn': hooks['decoder']['attentions'].outputs[\n 2 * layer_idx + 1\n ][output_idx],\n }\n for layer_idx in range(num_dec_layers)\n ],\n }\n\n def _clear_hook_outputs(self, hooks: Union[Dict[str, Any], OutputRecorder]):\n \"\"\"\n Recursively clear outputs from all hooks.\n \"\"\"\n if isinstance(hooks, dict):\n for subhooks in hooks.values():\n self._clear_hook_outputs(subhooks)\n else:\n # `hooks` is an OutputRecorder\n hooks.clear()\n\n def _get_encoder_loss(self, fwd_pass: ForwardPassOutputs) -> torch.Tensor:\n \"\"\"\n Return the loss on the encoder's output layer.\n \"\"\"\n assert isinstance(self, TorchGeneratorAgent)\n # Code relies on methods\n encoder_loss = F.mse_loss(\n input=fwd_pass.student_enc_output,\n target=fwd_pass.teacher_enc_output,\n reduction='none',\n )\n encoder_loss = encoder_loss.mean(dim=-1) * fwd_pass.context_mask\n # Avg over embedding dim\n self.record_local_metric(\n 'enc_loss',\n AverageMetric.many(\n encoder_loss.sum(dim=-1), fwd_pass.context_tokens_per_example\n ),\n ) # Sum over token dim\n encoder_loss = encoder_loss.div(fwd_pass.num_context_tokens).sum()\n # Divide before summing over examples so that values don't get too large\n return encoder_loss\n\n def _get_embedding_losses(\n self, fwd_pass: ForwardPassOutputs\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Return the encoder and decoder embedding losses.\n \"\"\"\n assert isinstance(self, TorchGeneratorAgent)\n # Code relies on methods\n enc_emb_loss, enc_emb_loss_per_example = self._get_component_embedding_loss(\n student_emb_output=fwd_pass.student_embedding_outputs['encoder'],\n teacher_emb_output=fwd_pass.teacher_embedding_outputs['encoder'],\n mask=fwd_pass.context_mask,\n num_tokens=fwd_pass.num_context_tokens,\n )\n self.record_local_metric(\n 'enc_emb_loss',\n AverageMetric.many(\n enc_emb_loss_per_example, fwd_pass.context_tokens_per_example\n ),\n )\n dec_emb_loss, dec_emb_loss_per_example = self._get_component_embedding_loss(\n student_emb_output=fwd_pass.student_embedding_outputs['decoder'],\n teacher_emb_output=fwd_pass.teacher_embedding_outputs['decoder'],\n mask=fwd_pass.mask,\n num_tokens=fwd_pass.num_tokens,\n )\n self.record_local_metric(\n 'dec_emb_loss',\n AverageMetric.many(dec_emb_loss_per_example, fwd_pass.tokens_per_example),\n )\n return enc_emb_loss, dec_emb_loss\n\n def _get_component_embedding_loss(\n self,\n student_emb_output: torch.Tensor,\n teacher_emb_output: torch.Tensor,\n mask: torch.BoolTensor,\n num_tokens: torch.Tensor,\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Compute the embedding loss for either the encoder or the decoder.\n \"\"\"\n assert isinstance(self, TorchGeneratorAgent)\n # Code relies on methods\n raw_loss = F.mse_loss(\n input=student_emb_output, target=teacher_emb_output, reduction='none'\n )\n clamped_loss = torch.clamp(raw_loss, min=0, max=NEAR_INF_FP16)\n # Prevent infs from appearing in the loss term. Especially important with fp16\n masked_loss = clamped_loss.sum(dim=-1) * mask\n # Sum over embedding dim\n embedding_loss_per_example = masked_loss.sum(dim=-1) # Sum over token dim\n embedding_loss = masked_loss.div(num_tokens).sum()\n # Divide before summing over examples so that values don't get too large\n return embedding_loss, embedding_loss_per_example\n\n def _get_hidden_losses(\n self, fwd_pass: ForwardPassOutputs\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Return the encoder and decoder hidden losses.\n \"\"\"\n assert isinstance(self, TorchGeneratorAgent)\n # Code relies on methods\n enc_hidden_loss, enc_hidden_loss_per_example = self._get_component_hidden_loss(\n student_hidden_states=fwd_pass.student_hidden_states['encoder'],\n teacher_hidden_states=fwd_pass.teacher_hidden_states['encoder'],\n mask=fwd_pass.context_mask,\n num_tokens=fwd_pass.num_context_tokens,\n mapped_layers=self.mapped_enc_layers,\n )\n self.record_local_metric(\n 'enc_hid_loss',\n AverageMetric.many(\n enc_hidden_loss_per_example, fwd_pass.context_tokens_per_example\n ),\n )\n dec_hidden_loss, dec_hidden_loss_per_example = self._get_component_hidden_loss(\n student_hidden_states=fwd_pass.student_hidden_states['decoder'],\n teacher_hidden_states=fwd_pass.teacher_hidden_states['decoder'],\n mask=fwd_pass.mask,\n num_tokens=fwd_pass.num_tokens,\n mapped_layers=self.mapped_dec_layers,\n )\n self.record_local_metric(\n 'dec_hid_loss',\n AverageMetric.many(\n dec_hidden_loss_per_example, fwd_pass.tokens_per_example\n ),\n )\n return enc_hidden_loss, dec_hidden_loss\n\n def _get_component_hidden_loss(\n self,\n student_hidden_states: List[torch.Tensor],\n teacher_hidden_states: List[torch.Tensor],\n mask: torch.BoolTensor,\n num_tokens: torch.Tensor,\n mapped_layers: List[int],\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Compute the loss across all hidden layers for either the encoder or the decoder.\n\n (The loss is averaged across all hidden layers and over the embedding dimension\n so that it doesn't get too high for fp16 tensors.)\n \"\"\"\n per_layer_losses = []\n per_layer_per_example_losses = []\n for student_layer_idx, teacher_layer_idx in enumerate(mapped_layers):\n raw_layer_loss = F.mse_loss(\n input=student_hidden_states[student_layer_idx],\n target=teacher_hidden_states[teacher_layer_idx],\n reduction='none',\n )\n clamped_layer_loss = torch.clamp(raw_layer_loss, min=0, max=NEAR_INF_FP16)\n # Prevent infs from appearing in the loss term. Especially important with\n # fp16\n masked_layer_loss = clamped_layer_loss.mean(dim=-1) * mask\n # Avg over embedding dim\n layer_loss_per_example = masked_layer_loss.sum(dim=-1) # Sum over token dim\n layer_loss = masked_layer_loss.div(num_tokens).sum()\n # Divide before summing over examples so that values don't get too large\n per_layer_losses.append(layer_loss)\n per_layer_per_example_losses.append(layer_loss_per_example)\n hidden_loss = torch.stack(per_layer_losses).mean()\n hidden_loss_per_example = torch.stack(per_layer_per_example_losses, dim=1).mean(\n dim=1\n )\n return hidden_loss, hidden_loss_per_example\n\n def _get_attention_losses(\n self, fwd_pass: ForwardPassOutputs\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n \"\"\"\n Return attention losses.\n\n Compute and return losses on encoder and decoder self-attention and decoder\n enc/dec attention.\n \"\"\"\n enc_self_attn_loss = self._get_and_record_component_attention_loss(\n student_attention_matrices=fwd_pass.student_attention_matrices['encoder'],\n teacher_attention_matrices=fwd_pass.teacher_attention_matrices['encoder'],\n mask=fwd_pass.context_mask,\n tokens_per_example=fwd_pass.context_tokens_per_example,\n num_tokens=fwd_pass.num_context_tokens,\n mapped_layers=self.mapped_enc_layers,\n attn_type='self_attn',\n metric_name='enc_self_attn_loss',\n )\n dec_self_attn_loss = self._get_and_record_component_attention_loss(\n student_attention_matrices=fwd_pass.student_attention_matrices['decoder'],\n teacher_attention_matrices=fwd_pass.teacher_attention_matrices['decoder'],\n mask=fwd_pass.mask,\n tokens_per_example=fwd_pass.tokens_per_example,\n num_tokens=fwd_pass.num_tokens,\n mapped_layers=self.mapped_dec_layers,\n attn_type='self_attn',\n metric_name='dec_self_attn_loss',\n )\n enc_dec_attn_loss = self._get_and_record_component_attention_loss(\n student_attention_matrices=fwd_pass.student_attention_matrices['decoder'],\n teacher_attention_matrices=fwd_pass.teacher_attention_matrices['decoder'],\n mask=fwd_pass.mask,\n tokens_per_example=fwd_pass.tokens_per_example,\n num_tokens=fwd_pass.num_tokens,\n mapped_layers=self.mapped_dec_layers,\n attn_type='encoder_attn',\n metric_name='enc_dec_attn_loss',\n )\n return enc_self_attn_loss, dec_self_attn_loss, enc_dec_attn_loss\n\n def _get_and_record_component_attention_loss(\n self,\n teacher_attention_matrices: List[Dict[str, torch.Tensor]],\n student_attention_matrices: List[Dict[str, torch.Tensor]],\n mask: torch.BoolTensor,\n tokens_per_example: torch.Tensor,\n num_tokens: torch.Tensor,\n mapped_layers: List[int],\n attn_type: str,\n metric_name: str,\n ) -> torch.Tensor:\n \"\"\"\n Calculate the given attention loss and register it as the given metric name.\n \"\"\"\n\n assert isinstance(self, TorchGeneratorAgent)\n # Code relies on methods\n\n # Select the right attention matrices\n selected_student_attn_matrices = [\n layer_matrices[attn_type] for layer_matrices in student_attention_matrices\n ]\n selected_teacher_attn_matrices = [\n layer_matrices[attn_type] for layer_matrices in teacher_attention_matrices\n ]\n\n batch_size = mask.size(0)\n per_layer_losses = []\n per_layer_per_example_losses = []\n for student_layer_idx, teacher_layer_idx in enumerate(mapped_layers):\n raw_layer_loss = F.mse_loss(\n input=selected_student_attn_matrices[student_layer_idx],\n target=selected_teacher_attn_matrices[teacher_layer_idx],\n reduction='none',\n )\n clamped_layer_loss = torch.clamp(raw_layer_loss, min=0, max=NEAR_INF_FP16)\n # Prevent infs from appearing in the loss term. Especially important with\n # fp16\n reshaped_layer_loss = clamped_layer_loss.view(\n batch_size, -1, clamped_layer_loss.size(-2), clamped_layer_loss.size(-1)\n )\n # [batch size, n heads, query length, key length]\n mean_layer_loss = reshaped_layer_loss.mean(dim=(1, 3))\n # Take the mean over the attention heads and the key length\n assert mean_layer_loss.shape == mask.shape\n masked_layer_loss = mean_layer_loss * mask\n layer_loss_per_example = masked_layer_loss.sum(dim=-1) # Sum over token dim\n layer_loss = masked_layer_loss.div(num_tokens).sum()\n # Divide before summing over examples so that values don't get too large\n per_layer_losses.append(layer_loss)\n per_layer_per_example_losses.append(layer_loss_per_example)\n attn_loss = torch.stack(per_layer_losses).mean()\n attn_loss_per_example = torch.stack(per_layer_per_example_losses, dim=1).mean(\n dim=1\n )\n\n # Record metric\n self.record_local_metric(\n metric_name, AverageMetric.many(attn_loss_per_example, tokens_per_example)\n )\n\n return attn_loss\n\n def _get_prediction_loss(self, fwd_pass: ForwardPassOutputs) -> torch.Tensor:\n \"\"\"\n Calculate and return the KL loss on the teacher's prediction layer.\n\n Also record prediction-loss metrics.\n \"\"\"\n assert isinstance(self, TorchGeneratorAgent)\n # Code relies on methods\n pred_loss = F.kl_div(\n F.log_softmax(fwd_pass.student_scores, dim=-1, dtype=torch.float),\n F.softmax(fwd_pass.teacher_scores, dim=-1, dtype=torch.float),\n reduction='none',\n ).type_as(fwd_pass.student_scores)\n pred_loss = pred_loss.sum(dim=-1) * fwd_pass.mask\n self.record_local_metric(\n 'pred_ppl',\n PPLMetric.many(pred_loss.sum(dim=-1), fwd_pass.tokens_per_example),\n )\n self.record_local_metric(\n 'pred_loss',\n AverageMetric.many(pred_loss.sum(dim=-1), fwd_pass.tokens_per_example),\n )\n pred_loss = pred_loss.sum() / fwd_pass.num_tokens\n return pred_loss\n\n\nclass DistillTransformerAgentMixin(AbstractDistillTransformerAgentMixin):\n @classmethod\n def add_cmdline_args(cls, argparser):\n super().add_cmdline_args(argparser)\n agent = argparser.add_argument_group('DistillTransformer arguments')\n agent.add_argument(\n '--copy-teacher-weights',\n type='bool',\n default=True,\n help='Copy weights from the teacher model to the student model',\n )\n return agent\n\n def __init__(self, opt, shared=None):\n self.copy_teacher_weights = opt['copy_teacher_weights']\n if (\n opt.get('init_model')\n and os.path.isfile(opt['init_model'])\n and self.copy_teacher_weights\n ):\n raise Exception(\n \"If --copy-teacher-weights is true, we cannot also copy over weights \"\n \"with --init-model!\"\n )\n super().__init__(opt, shared)\n\n def build_model(self):\n\n student_model = super().build_model()\n\n if self.copy_teacher_weights:\n\n teacher_model = self._get_teacher_model()\n\n # Initialize the embeddings\n student_model.encoder.embeddings.load_state_dict(\n teacher_model.encoder.embeddings.state_dict()\n )\n student_model.encoder.position_embeddings.load_state_dict(\n teacher_model.encoder.position_embeddings.state_dict()\n )\n student_model.decoder.embeddings.load_state_dict(\n teacher_model.decoder.embeddings.state_dict()\n )\n student_model.decoder.position_embeddings.load_state_dict(\n teacher_model.decoder.position_embeddings.state_dict()\n )\n\n # Initialize the encoder and decoder layers\n for student_idx, teacher_idx in enumerate(self.mapped_enc_layers):\n student_model.encoder.layers[student_idx].load_state_dict(\n teacher_model.encoder.layers[teacher_idx].state_dict()\n )\n for student_idx, teacher_idx in enumerate(self.mapped_dec_layers):\n student_model.decoder.layers[student_idx].load_state_dict(\n teacher_model.decoder.layers[teacher_idx].state_dict()\n )\n\n return student_model\n\n def compute_loss(self, batch, return_output=False):\n\n fwd_pass = self._perform_forward_passes(batch)\n\n # Calculate the loss on the encoder's output layer\n encoder_loss = self._get_encoder_loss(fwd_pass)\n\n # Calculate the loss on the encoder and decoder's hidden states\n enc_hidden_loss, dec_hidden_loss = self._get_hidden_losses(fwd_pass)\n\n # Calculate the KL loss on the teacher's prediction layer\n pred_loss = self._get_prediction_loss(fwd_pass)\n\n loss = (\n self.task_loss_coeff * fwd_pass.task_loss\n + self.encoder_loss_coeff * encoder_loss\n + self.hidden_loss_coeff * (enc_hidden_loss + dec_hidden_loss)\n + self.pred_loss_coeff * pred_loss\n )\n\n if return_output:\n return loss, fwd_pass.student_output\n else:\n return loss\n\n\nclass DistillNarrowTransformerAgentMixin(AbstractDistillTransformerAgentMixin):\n @classmethod\n def add_cmdline_args(cls, argparser):\n super().add_cmdline_args(argparser)\n agent = argparser.add_argument_group('DistillNarrowTransformer arguments')\n agent.add_argument(\n '--embedding-loss-coeff',\n type=float,\n default=0,\n help='Coefficient on teacher loss on embedding-layer output',\n )\n agent.add_argument(\n '--self-attn-loss-coeff',\n type=float,\n default=0,\n help='Coefficient on teacher loss on self-attention matrices',\n )\n agent.add_argument(\n '--enc-dec-attn-loss-coeff',\n type=float,\n default=0,\n help='Coefficient on teacher loss on enc/dec attention matrices',\n )\n return agent\n\n def __init__(self, opt, shared=None):\n self.embedding_loss_coeff = opt['embedding_loss_coeff']\n self.self_attn_loss_coeff = opt['self_attn_loss_coeff']\n self.enc_dec_attn_loss_coeff = opt['enc_dec_attn_loss_coeff']\n super().__init__(opt, shared)\n\n def build_model(self):\n student_model = super().build_model()\n\n # Build projection layers from the student to teacher hidden dim\n student_model.encoder_proj_layer = self._get_projection_layer(student_model)\n student_model.embedding_proj_layers = nn.ModuleDict(\n {\n 'encoder': self._get_projection_layer(student_model),\n 'decoder': self._get_projection_layer(student_model),\n }\n )\n student_model.hidden_proj_layers = nn.ModuleDict(\n {\n 'encoder': nn.ModuleList(\n [\n self._get_projection_layer(student_model)\n for _ in student_model.encoder.layers\n ]\n ),\n 'decoder': nn.ModuleList(\n [\n self._get_projection_layer(student_model)\n for _ in student_model.decoder.layers\n ]\n ),\n }\n )\n\n return student_model\n\n def _get_projection_layer(self, student_model):\n \"\"\"\n Return a projection layer from the student hidden dim to the teacher hidden dim.\n \"\"\"\n\n teacher_model = self._get_teacher_model()\n\n student_hidden_dim = student_model.encoder.dim\n teacher_hidden_dim = teacher_model.encoder.dim\n assert (\n student_hidden_dim == student_model.decoder.dim\n and teacher_hidden_dim == teacher_model.decoder.dim\n )\n\n layer = nn.Linear(student_hidden_dim, teacher_hidden_dim)\n\n # From TinyBERT's BertPreTrainedModel.init_bert_weights() method at\n # https://github.com/huawei-noah/Pretrained-Language-Model/blob/master/TinyBERT/transformer/modeling.py#L628\n layer.weight.data.normal_(mean=0.0, std=0.02)\n layer.bias.data.zero_()\n\n return layer\n\n def compute_loss(self, batch, return_output=False):\n\n fwd_pass = self._perform_forward_passes(batch)\n\n # Access the student model, which may be wrapped by\n # `torch.nn.parallel.DistributedDataParallel`\n if hasattr(self.model, 'module'):\n student_model = self.model.module\n else:\n student_model = self.model\n\n # Calculate the loss on the encoder's output layer\n fwd_pass.student_enc_output = student_model.encoder_proj_layer(\n fwd_pass.student_enc_output\n )\n # Pass encoder output through the corresponding projection layer\n encoder_loss = self._get_encoder_loss(fwd_pass)\n\n # Calculate the loss on the embedding layers\n for module, embedding_output in fwd_pass.student_embedding_outputs.items():\n # Loop over the encoder and the decoder\n fwd_pass.student_embedding_outputs[\n module\n ] = student_model.embedding_proj_layers[module](embedding_output)\n # Pass embedding output through the corresponding projection layer\n enc_emb_loss, dec_emb_loss = self._get_embedding_losses(fwd_pass)\n\n # Calculate the loss on the encoder and decoder's hidden states\n for module, per_layer_states in fwd_pass.student_hidden_states.items():\n # Loop over the encoder and the decoder\n assert len(per_layer_states) == len(\n student_model.hidden_proj_layers[module]\n )\n for layer_idx, hidden_state in enumerate(per_layer_states):\n # Loop over Transformer layers\n fwd_pass.student_hidden_states[module][\n layer_idx\n ] = student_model.hidden_proj_layers[module][layer_idx](hidden_state)\n # Pass hidden state through the corresponding projection layer\n enc_hidden_loss, dec_hidden_loss = self._get_hidden_losses(fwd_pass)\n\n # Calculate the losses on the attention matrices\n (\n enc_self_attn_loss,\n dec_self_attn_loss,\n enc_dec_attn_loss,\n ) = self._get_attention_losses(fwd_pass)\n\n # Calculate the KL loss on the teacher's prediction layer\n pred_loss = self._get_prediction_loss(fwd_pass)\n\n loss = (\n self.task_loss_coeff * fwd_pass.task_loss\n + self.encoder_loss_coeff * encoder_loss\n + self.embedding_loss_coeff * (enc_emb_loss + dec_emb_loss)\n + self.hidden_loss_coeff * (enc_hidden_loss + dec_hidden_loss)\n + self.self_attn_loss_coeff * (enc_self_attn_loss + dec_self_attn_loss)\n + self.enc_dec_attn_loss_coeff * (enc_dec_attn_loss)\n + self.pred_loss_coeff * pred_loss\n )\n\n if return_output:\n return loss, fwd_pass.student_output\n else:\n return loss\n\n\nclass DistillTransformerAgent(DistillTransformerAgentMixin, TransformerGeneratorAgent):\n @classmethod\n def add_cmdline_args(cls, argparser):\n \"\"\"\n Add command-line arguments specifically for this agent.\n \"\"\"\n DistillTransformerAgentMixin.add_cmdline_args(argparser)\n TransformerGeneratorAgent.add_cmdline_args(argparser)\n return argparser\n\n\nclass DistillNarrowTransformerAgent(\n DistillNarrowTransformerAgentMixin, TransformerGeneratorAgent\n):\n @classmethod\n def add_cmdline_args(cls, argparser):\n \"\"\"\n Add command-line arguments specifically for this agent.\n \"\"\"\n DistillNarrowTransformerAgentMixin.add_cmdline_args(argparser)\n TransformerGeneratorAgent.add_cmdline_args(argparser)\n return argparser\n\n\nclass BartLikeAgent(BartAgent):\n \"\"\"\n Subclass of the BART agent that prevents loading model weights from bart_large.\n \"\"\"\n\n def __init__(self, opt: Opt, shared: TShared = None):\n # Just skip BartAgent._initialize_bart(opt)\n super(BartAgent, self).__init__(opt, shared)\n\n def _manipulate_mask(\n self, mask: torch.BoolTensor, student_scores: torch.Tensor, batch: Batch\n ) -> torch.BoolTensor:\n \"\"\"\n Add one extra (masked-out) token to the mask, for compatibility with BART.\n \"\"\"\n assert student_scores.size(1) == batch.label_vec.size(1) + 1\n mask = torch.cat([mask.new_zeros([mask.size(0), 1]), mask], dim=1)\n return mask\n\n\nclass DistillBartAgent(DistillTransformerAgentMixin, BartLikeAgent):\n @classmethod\n def add_cmdline_args(cls, argparser):\n \"\"\"\n Add command-line arguments specifically for this agent.\n \"\"\"\n DistillTransformerAgentMixin.add_cmdline_args(argparser)\n BartLikeAgent.add_cmdline_args(argparser)\n return argparser\n\n\nclass DistillNarrowBartAgent(DistillNarrowTransformerAgentMixin, BartLikeAgent):\n @classmethod\n def add_cmdline_args(cls, argparser):\n \"\"\"\n Add command-line arguments specifically for this agent.\n \"\"\"\n DistillNarrowTransformerAgentMixin.add_cmdline_args(argparser)\n BartLikeAgent.add_cmdline_args(argparser)\n return argparser\n", "#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates.\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\nimport unittest\nfrom parlai.core.agents import create_agent\nimport torch.distributed as dist\nimport parlai.utils.testing as testing_utils\nimport parlai.scripts.multiprocessing_train as mp_train\nimport parlai.scripts.build_dict as build_dict\nimport os\nimport copy\n\n\nclass TestHuggingFaceDict(unittest.TestCase):\n def test_custom_special_tokens(self):\n from parlai.agents.hugging_face.dict import Gpt2DictionaryAgent\n from parlai.core.params import ParlaiParser\n\n parser = ParlaiParser(False, False)\n parser.set_defaults(gpt2_size=\"small\", add_special_tokens=True)\n Gpt2DictionaryAgent.add_cmdline_args(parser)\n with testing_utils.tempdir() as tmpdir:\n opt = parser.parse_kwargs(dict_file=os.path.join(tmpdir, 'dict'))\n dict_agent = Gpt2DictionaryAgent(opt)\n oldtokens = dict_agent.txt2vec(\"Hi VOLDEMORT\")\n prevlen = len(dict_agent)\n dict_agent.add_additional_special_tokens([\"VOLDEMORT\"])\n newlen = len(dict_agent)\n assert newlen == prevlen + 1\n tokens = dict_agent.txt2vec(\"Hi VOLDEMORT\")\n assert tokens != oldtokens\n assert len(tokens) < len(oldtokens)\n\n\nclass TestGpt2(unittest.TestCase):\n # Did you implement a test for DialoGPT too if your changes affect it?\n\n def _test_batchsize(self, batchsize, add_start_token):\n utterances = [\n 'Just keep swimming -',\n 'I wish I knew how to quit you. -',\n \"I'm going to make him an offer he can't refuse. -\",\n \"Toto, I've got a feeling we're not in Kansas anymore. -\",\n ]\n opt = {\n 'model': 'hugging_face/gpt2',\n 'gpt2_size': 'small',\n 'text_truncate': 16,\n 'label_truncate': 8,\n 'beam_min_length': 8,\n 'inference': 'beam',\n 'beam_size': 1,\n 'add_special_tokens': True,\n 'batchsize': batchsize,\n 'add_start_token': add_start_token,\n }\n gpt2 = create_agent(opt)\n\n results_single = []\n agents = [gpt2.clone() for _ in utterances]\n for u, a in zip(utterances, agents):\n a.observe({'text': u, 'episode_done': True})\n generation = a.act()['text']\n results_single.append(generation)\n\n results_batched = []\n for idx in range(len(utterances) // batchsize):\n agents = [gpt2.clone() for _ in range(batchsize)]\n batch = utterances[idx * batchsize : (idx + 1) * batchsize]\n obs = []\n for i, a in enumerate(agents):\n obs.append(a.observe({'text': batch[i], 'episode_done': True}))\n generations = [x['text'] for x in gpt2.batch_act(obs)]\n results_batched += generations\n\n assert results_single == results_batched\n\n def test_start_token(self):\n with self.assertRaises(RuntimeError):\n create_agent(\n {\n 'model': 'hugging_face/gpt2',\n 'add_special_tokens': False,\n 'add_start_token': True,\n }\n )\n\n def test_batchsize(self):\n \"\"\"\n Ensures gpt2 provides the same generation results regardless of batchsize.\n \"\"\"\n for add_start_token in [True, False]:\n for batchsize in [1, 2, 4]:\n with self.subTest(\n f'test_batchsize with bs={batchsize} and ast={add_start_token}'\n ):\n self._test_batchsize(batchsize, add_start_token)\n\n def test_nospecialtok(self):\n with self.assertRaises(RuntimeError):\n create_agent(\n {\n 'model': 'hugging_face/gpt2',\n 'add_special_tokens': False,\n 'batchsize': 2,\n }\n )\n\n opt = {\n 'model': 'hugging_face/gpt2',\n 'gpt2_size': 'small',\n 'text_truncate': 16,\n 'label_truncate': 8,\n 'beam_min_length': 8,\n 'inference': 'beam',\n 'beam_size': 1,\n 'batchsize': 1,\n 'add_special_tokens': False,\n }\n gpt2 = create_agent(opt)\n gpt2.observe({'text': 'My name is', 'episode_done': True})\n response = gpt2.act()\n assert response['text'] == \" John. I'm a man of\"\n\n\n@testing_utils.skipUnlessGPU\nclass TestDistributed(unittest.TestCase):\n _base_config = {\n 'task': 'integration_tests:overfit',\n 'model': 'hugging_face/gpt2',\n 'gpt2_size': 'small',\n 'text_truncate': 16,\n 'label_truncate': 8,\n 'beam_min_length': 8,\n 'inference': 'beam',\n 'beam_size': 1,\n 'batchsize': 4,\n 'add_special_tokens': True,\n 'validation_metric': 'ppl',\n }\n\n def setUp(self):\n print(f'[Setting up test {self._testMethodName}]')\n\n def _forced_parse(self, parser, opt):\n # TODO: Kill this after dictionaries build correctly\n parser.set_params(**opt)\n parser.set_params(log_every_n_sec=10)\n popt = parser.parse_args([])\n # in some rare cases, like for instance if the model class also\n # overrides its default params, the params override will not\n # be taken into account.\n for k, v in opt.items():\n popt[k] = v\n return popt\n\n def _distributed_train_model(self, opt):\n with testing_utils.tempdir() as tmpdir:\n if 'model_file' not in opt:\n opt['model_file'] = os.path.join(tmpdir, 'model')\n if 'dict_file' not in opt:\n opt['dict_file'] = os.path.join(tmpdir, 'model.dict')\n\n parser = mp_train.setup_args()\n # TODO: Kill this after dictionaries build correctly\n popt = self._forced_parse(parser, opt)\n\n # we need a prebuilt dictionary\n parser = build_dict.setup_args()\n build_dict.build_dict(popt)\n\n valid, test = mp_train.launch_and_train(popt, 31338)\n dist.destroy_process_group()\n\n return (valid, test)\n\n @testing_utils.retry()\n def test_distributed(self):\n config = copy.deepcopy(self._base_config)\n config['num_epochs'] = 50\n config['task'] = 'integration_tests:overfit'\n config['batchsize'] = 2\n config['dropout'] = 0.0\n config['attention_dropout'] = 0.0\n config['learningrate'] = 1.0\n config['momentum'] = 0.90\n config['skip_generation'] = True\n valid, test = self._distributed_train_model(config)\n\n self.assertLessEqual(valid['ppl'], 10)\n self.assertLessEqual(test['ppl'], 10)\n" ]
[ [ "torch.nn.functional.softmax", "torch.nn.functional.log_softmax", "torch.nn.Linear", "torch.nn.functional.mse_loss", "torch.no_grad", "torch.stack", "torch.clamp" ], [ "torch.distributed.destroy_process_group" ] ]
idaho777/creativeflow
[ "adf7a9e1cf70005560cfbf8064137fb1236bc574" ]
[ "creativeflow/blender/unpack_exr_main.py" ]
[ "#!/usr/bin/env python\n\"\"\"\nUNPACK FLOW, BACKFLOW, DEPTH FROM MULTILAYER EXR FILES OUTPUT BY BLENDER.\n\nBackground:\n------------------------------------------------------------------------------\nIn order to extract flow and depth from Blender rendering pipeline we write\nmultilayer EXR files (https://www.openexr.com/). This main extracts flow,\nbackflow and depth from these files and writes them to file, also writing\ncompressed versions, if requested. In addition, we compute occlusions\nin the same way as described in compute_occlusions_main.py.\n\nRequirements:\n------------------------------------------------------------------------------\nIMPORTANT! This was only tested for EXR files output using our scripted\npipeline and Blender 2.79 API.\n\"\"\"\nimport argparse\nimport glob\nimport numpy as np\nimport os\nimport re\nimport time\nfrom skimage.io import imsave\n\nimport exr_util\nimport flow_util\nimport io_util\nfrom misc_util import QuickTimer\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(\n description='Unpacks multilayer exr from blender to flow, depth.')\n parser.add_argument(\n '--input_dir', action='store', type=str, required=True,\n help='Input directory with exr files, one per frame.')\n\n parser.add_argument(\n '--flow_odir', action='store', type=str, default='',\n help='Output directory for flow files, if set will output in flo format.')\n parser.add_argument(\n '--back_flow_odir', action='store', type=str, default='',\n help='Output directory for back flow files, if set will output in flo format.')\n parser.add_argument(\n '--depth_odir', action='store', type=str, default='',\n help='Output directory for depth files, if set will output in numpy binary.')\n parser.add_argument(\n '--depth_range_ofile', action='store', type=str, default='',\n help='Output file for aggregate depth range.')\n parser.add_argument(\n '--occlusions_odir', action='store', type=str, default='',\n help='Output directory for occlusion files, if set will output in image format.')\n\n parser.add_argument(\n '--flow_zip', action='store', type=str, default='',\n help='If set, will compress flow into a special zip; only runs if also --flow_odir.')\n parser.add_argument(\n '--back_flow_zip', action='store', type=str, default='',\n help='If set, will compress back flow into a special zip; only runs if also --back_flow_odir.')\n parser.add_argument(\n '--depth_zip', action='store', type=str, default='',\n help='If set, will compress depth into a special zip; only runs if also --depth_odir.')\n\n args = parser.parse_args()\n\n qtimer = QuickTimer()\n\n fpattern = os.path.join(args.input_dir, '*')\n files = glob.glob(fpattern)\n files.sort()\n\n if len(files) == 0:\n raise RuntimeError('No files found matching %s' % fpattern)\n\n def _make_ofile(infile, odir, extension, desired_basename):\n bname = os.path.basename(infile)\n r = re.match('[a-z]+([0-9]+).exr', bname)\n if r is None:\n bname = bname.strip('.exr')\n else:\n bname = '%s%s.%s' % (desired_basename, r.group(1), extension)\n return os.path.join(odir, bname)\n\n qtimer.start('parse_exr')\n meta = exr_util.read_exr_metadata(files[0])\n qtimer.end()\n dshape = meta['depth'].shape\n depth_range = None\n for i in range(len(files) - 1):\n fname = files[i]\n qtimer.start('I/O')\n if len(args.flow_odir) > 0:\n io_util.write_flow(meta['flow'], _make_ofile(fname, args.flow_odir, 'flo', 'flow'))\n if len(args.back_flow_odir) > 0:\n io_util.write_flow(meta['back_flow'], _make_ofile(fname, args.back_flow_odir, 'flo', 'backflow'))\n if len(args.depth_odir) > 0:\n # Note: depth has 2 channels - Z, alpha\n meta['depth'].reshape([-1]).tofile(_make_ofile(fname, args.depth_odir, 'array', 'depth'))\n qtimer.end()\n\n qtimer.start('depth_compute')\n if len(args.depth_range_ofile) > 0:\n D = meta['depth'][:, :, 0] # depth\n A = meta['depth'][:, :, 1] # alpha\n nonzeroD = D[A > 0]\n if nonzeroD.size > 0:\n if depth_range is None:\n depth_range = [np.min(nonzeroD), np.max(nonzeroD)]\n else:\n depth_range[0] = min(depth_range[0], np.min(nonzeroD))\n depth_range[1] = max(depth_range[0], np.max(nonzeroD))\n qtimer.end()\n\n qtimer.start('parse_exr')\n meta2 = exr_util.read_exr_metadata(files[i+1])\n qtimer.end()\n if len(args.occlusions_odir) > 0:\n occ_fname = _make_ofile(fname, args.occlusions_odir, 'png', 'occlusions')\n qtimer.start('occlusions_compute')\n occ = flow_util.get_occlusions_vec(meta['flow'], meta2['back_flow'],\n pixel_threshold=0.5)\n qtimer.end()\n qtimer.start('I/O')\n imsave(occ_fname, occ)\n qtimer.end()\n meta = meta2\n\n if len(args.depth_range_ofile) > 0:\n if depth_range is None:\n raise RuntimeError(\n 'Depth range cannot be computed: no non-transparent depths in %s' %\n args.input_dir)\n with open(args.depth_range_ofile, 'w') as f:\n f.write('%0.6f %0.6f %s\\n' % (depth_range[0], depth_range[1],\n ' '.join([('%d' % x) for x in dshape])))\n\n qtimer.start('compression')\n if len(args.flow_zip) > 0:\n if len(args.flow_odir) == 0:\n raise RuntimeError('Sorry; --flow_zip is only written if --flow_odir is set.')\n else:\n io_util.compress_flows(args.flow_odir, args.flow_zip)\n\n if len(args.back_flow_zip) > 0:\n if len(args.back_flow_odir) == 0:\n raise RuntimeError('Sorry; --back_flow_zip is only written if --back_flow_odir is set.')\n else:\n io_util.compress_flows(args.back_flow_odir, args.back_flow_zip)\n\n if len(args.depth_zip) > 0:\n if len(args.depth_odir) == 0:\n raise RuntimeError('Sorry; --depth_zip is only written if --depth_odir is set.')\n else:\n io_util.compress_arrays(args.depth_odir, dshape, args.depth_zip)\n qtimer.end()\n\n print(qtimer.summary())\n" ]
[ [ "numpy.max", "numpy.min" ] ]
serend1p1ty/core-pytorch-utils
[ "626e4ec586656788204656779a80f374f888256b" ]
[ "tests/test_lr_scheduler.py" ]
[ "import mmcv\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom cpu.lr_scheduler import LRWarmupScheduler\nfrom fvcore.common.param_scheduler import (\n CompositeParamScheduler,\n ConstantParamScheduler,\n LinearParamScheduler,\n CosineParamScheduler,\n MultiStepParamScheduler\n)\nfrom mmcv.runner.hooks import HOOKS\nfrom timm.scheduler import (\n CosineLRScheduler,\n MultiStepLRScheduler,\n PlateauLRScheduler,\n StepLRScheduler\n)\nfrom torch.optim.lr_scheduler import (\n CosineAnnealingLR,\n CosineAnnealingWarmRestarts,\n MultiStepLR,\n ReduceLROnPlateau,\n StepLR\n)\n\n\nclass WarmupParamScheduler(CompositeParamScheduler):\n def __init__(self, scheduler, warmup_factor, warmup_length, warmup_method=\"linear\"):\n end_value = scheduler(warmup_length) # the value to reach when warmup ends\n start_value = warmup_factor * scheduler(0.0)\n if warmup_method == \"constant\":\n warmup = ConstantParamScheduler(start_value)\n elif warmup_method == \"linear\":\n warmup = LinearParamScheduler(start_value, end_value)\n else:\n raise ValueError(\"Unknown warmup method: {}\".format(warmup_method))\n super().__init__(\n [warmup, scheduler],\n interval_scaling=[\"rescaled\", \"fixed\"],\n lengths=[warmup_length, 1 - warmup_length],\n )\n\n\nclass LRMultiplier(torch.optim.lr_scheduler._LRScheduler):\n def __init__(self, optimizer, multiplier, max_iter, last_iter=-1):\n self._multiplier = multiplier\n self._max_iter = max_iter\n super().__init__(optimizer, last_epoch=last_iter)\n\n def state_dict(self):\n return {\"base_lrs\": self.base_lrs, \"last_epoch\": self.last_epoch}\n\n def get_lr(self):\n multiplier = self._multiplier(self.last_epoch / self._max_iter)\n return [base_lr * multiplier for base_lr in self.base_lrs]\n\n\ndef get_lrs_d2(max_epochs, epoch_len, opt_config, lr_config):\n optimizer = _get_optimizer_from_config(opt_config)\n\n max_iters = max_epochs * epoch_len\n if lr_config[\"type\"] == \"multistep\":\n steps = lr_config[\"steps\"]\n sched = MultiStepParamScheduler(\n values=[0.1 ** k for k in range(len(steps) + 1)],\n milestones=steps,\n num_updates=max_iters,\n )\n elif lr_config[\"type\"] == \"cosine\":\n sched = CosineParamScheduler(1, 0)\n\n sched = WarmupParamScheduler(sched, lr_config[\"warmup_factor\"],\n min(lr_config[\"warmup_iters\"] / max_iters, 1.0), \"linear\")\n lr_scheduler = LRMultiplier(optimizer, multiplier=sched, max_iter=max_iters)\n\n lrs = []\n for _ in range(max_epochs):\n for _ in range(epoch_len):\n lrs.append(_get_optimizer_lr(optimizer))\n optimizer.step()\n lr_scheduler.step()\n return lrs\n\n\nclass MMCVRunner:\n def __init__(self, max_epochs, epoch_len, opt_config, lr_config):\n self.max_epochs = max_epochs\n self.epoch_len = epoch_len\n self.optimizer = _get_optimizer_from_config(opt_config)\n self.hooks = []\n self.register_hook_from_cfg(lr_config)\n\n def run(self):\n lrs = []\n self.iter = 0\n self.call_hook('before_run')\n for self.epoch in range(self.max_epochs):\n self.call_hook('before_train_epoch')\n for self.inner_iter in range(self.epoch_len):\n self.call_hook('before_train_iter')\n lr = []\n for param_group in self.optimizer.param_groups:\n lr.append(param_group[\"lr\"])\n lrs.append(lr)\n self.optimizer.step()\n self.call_hook('after_train_iter')\n self.iter += 1\n self.call_hook('after_train_epoch')\n self.call_hook('after_run')\n return lrs\n\n def register_hook_from_cfg(self, hook_cfg):\n hook = mmcv.build_from_cfg(hook_cfg, HOOKS)\n self.hooks.append(hook)\n\n def call_hook(self, fn_name):\n for hook in self.hooks:\n getattr(hook, fn_name)(self)\n\n\ndef _get_optimizer_from_config(opt_config):\n params = []\n for i in range(opt_config[\"num_pram_groups\"]):\n params.append({\"params\": nn.Parameter(torch.zeros(0)), \"lr\": opt_config[\"base_lr\"] * (i + 1)})\n optimizer = torch.optim.SGD(params)\n return optimizer\n\n\ndef _get_optimizer_lr(optimizer):\n lr = []\n for param_group in optimizer.param_groups:\n lr.append(param_group[\"lr\"])\n return lr\n\n\ndef get_lrs_timm(max_epochs, epoch_len, opt_config, lr_config, epoch_metircs=None):\n optimizer = _get_optimizer_from_config(opt_config)\n\n type = lr_config[\"type\"]\n if type == \"step\":\n lr_scheduler = StepLRScheduler(\n optimizer, decay_t=lr_config[\"decay_t\"], decay_rate=0.1,\n warmup_t=lr_config[\"warmup_t\"], warmup_lr_init=lr_config[\"warmup_lr_init\"],\n t_in_epochs=lr_config[\"t_in_epochs\"])\n elif type == \"multistep\":\n lr_scheduler = MultiStepLRScheduler(\n optimizer, decay_t=lr_config[\"decay_t\"], decay_rate=0.1,\n warmup_t=lr_config[\"warmup_t\"], warmup_lr_init=lr_config[\"warmup_lr_init\"],\n t_in_epochs=lr_config[\"t_in_epochs\"])\n elif type == \"cosine_restart\":\n lr_scheduler = CosineLRScheduler(\n optimizer, t_initial=lr_config[\"t_initial\"], warmup_t=lr_config[\"warmup_t\"],\n warmup_lr_init=lr_config[\"warmup_lr_init\"], t_in_epochs=lr_config[\"t_in_epochs\"],\n cycle_limit=lr_config[\"cycle_limit\"])\n elif type == \"plateau\":\n lr_scheduler = PlateauLRScheduler(\n optimizer, decay_rate=0.1, patience_t=lr_config[\"patience_t\"], mode=\"min\",\n warmup_t=lr_config[\"warmup_t\"], warmup_lr_init=lr_config[\"warmup_lr_init\"])\n\n if epoch_metircs:\n assert len(epoch_metircs) == max_epochs\n\n lrs = []\n for epoch in range(max_epochs):\n for step in range(epoch_len):\n lrs.append(_get_optimizer_lr(optimizer))\n optimizer.step()\n lr_scheduler.step_update(epoch * epoch_len + step + 1)\n if epoch_metircs:\n lr_scheduler.step(epoch + 1, epoch_metircs[epoch])\n else:\n lr_scheduler.step(epoch + 1)\n return lrs\n\n\ndef get_lrs_cpu(max_epochs, epoch_len, opt_config, lr_config, epoch_metircs=None):\n optimizer = _get_optimizer_from_config(opt_config)\n\n type = lr_config.pop(\"type\")\n if type == \"step\":\n torch_scheduler = StepLR(optimizer, step_size=lr_config.pop(\"step_size\"), gamma=0.1)\n elif type == \"multistep\":\n torch_scheduler = MultiStepLR(optimizer, milestones=lr_config.pop(\"milestones\"), gamma=0.1)\n elif type == \"cosine\":\n T_max = max_epochs if lr_config[\"by_epoch\"] else max_epochs * epoch_len\n torch_scheduler = CosineAnnealingLR(optimizer, T_max=T_max)\n elif type == \"cosine_restart\":\n torch_scheduler = CosineAnnealingWarmRestarts(optimizer, T_0=lr_config.pop(\"T_0\"))\n elif type == \"plateau\":\n torch_scheduler = ReduceLROnPlateau(optimizer, patience=lr_config.pop(\"patience\"))\n lr_scheduler = LRWarmupScheduler(torch_scheduler, **lr_config)\n\n if epoch_metircs:\n assert len(epoch_metircs) == max_epochs\n\n lrs = []\n for epoch in range(max_epochs):\n for _ in range(epoch_len):\n lrs.append(_get_optimizer_lr(optimizer))\n optimizer.step()\n lr_scheduler.iter_update()\n if epoch_metircs:\n lr_scheduler.epoch_update(epoch_metircs[epoch])\n else:\n lr_scheduler.epoch_update()\n return lrs\n\n\ndef get_lrs_torch(max_epochs, epoch_len, opt_config, lr_config, epoch_metircs=None):\n optimizer = _get_optimizer_from_config(opt_config)\n\n type = lr_config.pop(\"type\")\n if type == \"step\":\n lr_scheduler = StepLR(optimizer, step_size=lr_config.pop(\"step_size\"), gamma=0.1)\n elif type == \"multistep\":\n lr_scheduler = MultiStepLR(optimizer, milestones=lr_config.pop(\"milestones\"), gamma=0.1)\n elif type == \"cosine\":\n lr_scheduler = CosineAnnealingLR(optimizer, T_max=max_epochs)\n elif type == \"cosine_restart\":\n lr_scheduler = CosineAnnealingWarmRestarts(optimizer, T_0=lr_config[\"T_0\"])\n elif type == \"plateau\":\n lr_scheduler = ReduceLROnPlateau(optimizer, patience=lr_config[\"patience\"])\n\n if epoch_metircs:\n assert len(epoch_metircs) == max_epochs\n\n lrs = []\n for epoch in range(max_epochs):\n for _ in range(epoch_len):\n lrs.append(_get_optimizer_lr(optimizer))\n optimizer.step()\n if epoch_metircs:\n lr_scheduler.step(epoch_metircs[epoch])\n else:\n lr_scheduler.step()\n return lrs\n\n\ndef allclose(list1, list2):\n for a, b in zip(list1, list2):\n if not np.allclose(a, b):\n return False\n return True\n\n\ndef test_no_warmup():\n \"\"\"cpu vs torch\"\"\"\n max_epochs = 10\n epoch_len = 3\n base_lr = 5\n by_epoch = True\n\n for num_pram_groups in [1, 2]:\n opt_config = dict(num_pram_groups=num_pram_groups, base_lr=base_lr)\n\n #### StepLR\n lr_config = dict(type=\"step\", step_size=3, by_epoch=by_epoch, epoch_len=epoch_len)\n lrs_cpu = get_lrs_cpu(max_epochs, epoch_len, opt_config, lr_config)\n\n lr_config = dict(type=\"step\", step_size=3)\n lrs_torch = get_lrs_torch(max_epochs, epoch_len, opt_config, lr_config)\n assert allclose(lrs_cpu, lrs_torch)\n\n #### MultiStepLR\n lr_config = dict(type=\"multistep\", milestones=[4, 7], by_epoch=by_epoch, epoch_len=epoch_len)\n lrs_cpu = get_lrs_cpu(max_epochs, epoch_len, opt_config, lr_config)\n\n lr_config = dict(type=\"multistep\", milestones=[4, 7])\n lrs_torch = get_lrs_torch(max_epochs, epoch_len, opt_config, lr_config)\n assert allclose(lrs_cpu, lrs_torch)\n\n #### CosineAnnealingLR\n lr_config = dict(type=\"cosine\", by_epoch=by_epoch, epoch_len=epoch_len)\n lrs_cpu = get_lrs_cpu(max_epochs, epoch_len, opt_config, lr_config)\n\n lr_config = dict(type=\"cosine\")\n lrs_torch = get_lrs_torch(max_epochs, epoch_len, opt_config, lr_config)\n assert allclose(lrs_cpu, lrs_torch)\n\n #### ReduceLROnPlateau\n lr_config = dict(type=\"plateau\", patience=2, by_epoch=by_epoch, epoch_len=epoch_len)\n epoch_metrics = list(range(10, 0, -1))\n epoch_metrics[3:7] = [7, 7, 7, 7]\n lrs_cpu = get_lrs_cpu(max_epochs, epoch_len, opt_config, lr_config, epoch_metrics)\n\n lr_config = dict(type=\"plateau\", patience=2)\n lrs_torch = get_lrs_torch(max_epochs, epoch_len, opt_config, lr_config, epoch_metrics)\n assert allclose(lrs_cpu, lrs_torch)\n\n\ndef test_fix():\n \"\"\"cpu vs timm\"\"\"\n epoch = 20\n epoch_len = 3\n base_lr = 5\n for by_epoch in [True, False]:\n for num_pram_groups in [1, 2]:\n opt_config = dict(num_pram_groups=num_pram_groups, base_lr=base_lr)\n\n #### StepLR\n lr_config = dict(type=\"step\", step_size=3, by_epoch=by_epoch, epoch_len=epoch_len,\n warmup_t=5, warmup_by_epoch=by_epoch, warmup_mode=\"fix\", warmup_init_lr=0.005)\n lrs_cpu = get_lrs_cpu(epoch, epoch_len, opt_config, lr_config)\n\n lr_config = dict(type=\"step\", decay_t=3, decay_rate=0.1,\n warmup_t=5, warmup_lr_init=0.005, t_in_epochs=by_epoch)\n lrs_timm = get_lrs_timm(epoch, epoch_len, opt_config, lr_config)\n assert allclose(lrs_cpu, lrs_timm)\n\n #### MultiStepLR\n lr_config = dict(type=\"multistep\", milestones=[12, 16], by_epoch=by_epoch, epoch_len=epoch_len,\n warmup_t=5, warmup_by_epoch=by_epoch, warmup_mode=\"fix\", warmup_init_lr=0.005)\n lrs_cpu = get_lrs_cpu(epoch, epoch_len, opt_config, lr_config)\n\n lr_config = dict(type=\"multistep\", decay_t=[13, 17], decay_rate=0.1,\n warmup_t=5, warmup_lr_init=0.005, t_in_epochs=by_epoch)\n lrs_timm = get_lrs_timm(epoch, epoch_len, opt_config, lr_config)\n assert allclose(lrs_cpu, lrs_timm)\n\n #### CosineAnnealingRestarts\n lr_config = dict(type=\"cosine_restart\", T_0=10, by_epoch=by_epoch, epoch_len=epoch_len,\n warmup_t=5, warmup_by_epoch=by_epoch, warmup_mode=\"fix\", warmup_init_lr=0.005)\n lrs_cpu = get_lrs_cpu(epoch, epoch_len, opt_config, lr_config)\n\n lr_config = dict(type=\"cosine_restart\", t_initial=10, warmup_t=5, warmup_lr_init=0.005,\n t_in_epochs=by_epoch, cycle_limit=20)\n lrs_timm = get_lrs_timm(epoch, epoch_len, opt_config, lr_config)\n assert allclose(lrs_cpu, lrs_timm)\n\n if by_epoch:\n #### ReduceLROnPlateau - test 1\n lr_config = dict(type=\"plateau\", patience=2, by_epoch=by_epoch, epoch_len=epoch_len,\n warmup_t=5, warmup_by_epoch=by_epoch, warmup_mode=\"fix\", warmup_init_lr=0.005)\n epoch_metrics = list(range(20, 0, -1))\n epoch_metrics[7:11] = [13, 13, 13, 13]\n epoch_metrics[13:17] = [7, 7, 7, 7]\n lrs_cpu = get_lrs_cpu(epoch, epoch_len, opt_config, lr_config, epoch_metrics)\n\n lr_config = dict(type=\"plateau\", decay_rate=0.1, patience_t=2,\n mode=\"min\", warmup_t=5, warmup_lr_init=0.005)\n lrs_timm = get_lrs_timm(epoch, epoch_len, opt_config, lr_config, epoch_metrics)\n assert allclose(lrs_cpu, lrs_timm)\n\n #### ReduceLROnPlateau - test 2\n lr_config = dict(type=\"plateau\", patience=2, by_epoch=by_epoch, epoch_len=epoch_len,\n warmup_t=8, warmup_by_epoch=by_epoch, warmup_mode=\"fix\", warmup_init_lr=0.005)\n epoch_metrics = list(range(20, 0, -1))\n epoch_metrics[7:11] = [13, 13, 13, 13]\n epoch_metrics[13:17] = [7, 7, 7, 7]\n lrs_cpu = get_lrs_cpu(epoch, epoch_len, opt_config, lr_config, epoch_metrics)\n\n lr_config = dict(type=\"plateau\", decay_rate=0.1, patience_t=2,\n mode=\"min\", warmup_t=8, warmup_lr_init=0.005)\n lrs_timm = get_lrs_timm(epoch, epoch_len, opt_config, lr_config, epoch_metrics)\n assert allclose(lrs_cpu, lrs_timm)\n\n\ndef test_factor():\n max_epochs = 20\n epoch_len = 3\n base_lr = 5\n warmup_by_epoch = False\n for by_epoch in [True, False]:\n for num_pram_groups in [1, 2]:\n opt_config = dict(num_pram_groups=num_pram_groups, base_lr=base_lr)\n\n #### StepLR\n lr_config = dict(type=\"step\", step_size=3, by_epoch=by_epoch, epoch_len=epoch_len,\n warmup_t=5, warmup_by_epoch=warmup_by_epoch, warmup_mode=\"factor\", warmup_factor=0.001)\n lrs_cpu = get_lrs_cpu(max_epochs, epoch_len, opt_config, lr_config)\n\n lr_config = dict(type='StepLrUpdaterHook', warmup='linear', warmup_iters=5,\n warmup_ratio=0.001, step=3, by_epoch=by_epoch)\n runner = MMCVRunner(max_epochs, epoch_len, opt_config, lr_config)\n lrs_mmcv = runner.run()\n assert allclose(lrs_cpu, lrs_mmcv)\n\n #### MultiStepLR\n lr_config = dict(type=\"multistep\", milestones=[8, 11], by_epoch=by_epoch, epoch_len=epoch_len,\n warmup_t=5, warmup_by_epoch=warmup_by_epoch, warmup_mode=\"factor\", warmup_factor=0.001)\n lrs_cpu = get_lrs_cpu(max_epochs, epoch_len, opt_config, lr_config)\n\n lr_config = dict(type='StepLrUpdaterHook', warmup='linear', warmup_iters=5,\n warmup_ratio=0.001, step=[8, 11], by_epoch=by_epoch)\n runner = MMCVRunner(max_epochs, epoch_len, opt_config, lr_config)\n lrs_mmcv = runner.run()\n assert allclose(lrs_cpu, lrs_mmcv)\n\n #### CosineAnnealingRestarts\n lr_config = dict(type=\"cosine_restart\", T_0=10, by_epoch=by_epoch, epoch_len=epoch_len,\n warmup_t=5, warmup_by_epoch=warmup_by_epoch, warmup_mode=\"factor\", warmup_factor=0.001)\n lrs_cpu = get_lrs_cpu(max_epochs, epoch_len, opt_config, lr_config)\n\n lr_config = dict(type='CosineRestartLrUpdaterHook', warmup='linear', warmup_iters=5,\n warmup_ratio=0.001, periods=[10] * 2 if by_epoch else [10] * 6,\n restart_weights=[1] * 2 if by_epoch else [1] * 6,\n min_lr=0, by_epoch=by_epoch)\n runner = MMCVRunner(max_epochs, epoch_len, opt_config, lr_config)\n lrs_mmcv = runner.run()\n assert allclose(lrs_cpu, lrs_mmcv)\n\n\ndef test_auto():\n max_epochs = 20\n epoch_len = 3\n base_lr = 5\n by_epoch = False\n warmup_by_epoch = False\n for num_pram_groups in [1, 2]:\n opt_config = dict(num_pram_groups=num_pram_groups, base_lr=base_lr)\n\n #### MultiStepLR\n lr_config = dict(type=\"multistep\", milestones=[30, 50], by_epoch=by_epoch, epoch_len=epoch_len,\n warmup_t=10, warmup_by_epoch=warmup_by_epoch, warmup_mode=\"auto\", warmup_factor=0.001)\n lrs_cpu = get_lrs_cpu(max_epochs, epoch_len, opt_config, lr_config)\n\n lr_config = dict(type=\"multistep\", steps=[30, 50], warmup_factor=0.001, warmup_iters=10)\n lrs_d2 = get_lrs_d2(max_epochs, epoch_len, opt_config, lr_config)\n assert allclose(lrs_cpu, lrs_d2)\n\n #### CosineAnnealing\n lr_config = dict(type=\"cosine\", by_epoch=by_epoch, epoch_len=epoch_len,\n warmup_t=10, warmup_by_epoch=warmup_by_epoch, warmup_mode=\"auto\", warmup_factor=0.001)\n lrs_cpu = get_lrs_cpu(max_epochs, epoch_len, opt_config, lr_config)\n\n lr_config = dict(type=\"cosine\", warmup_factor=0.001, warmup_iters=10)\n lrs_d2 = get_lrs_d2(max_epochs, epoch_len, opt_config, lr_config)\n assert allclose(lrs_cpu, lrs_d2)\n\n\ndef test_other_cases():\n # from detectron2 test\n lr_config = dict(type=\"multistep\", milestones=[10, 15, 20], by_epoch=False,\n warmup_t=5, warmup_by_epoch=False, warmup_mode=\"fix\", warmup_init_lr=0.005)\n opt_config = dict(num_pram_groups=1, base_lr=5)\n lrs_cpu = get_lrs_cpu(30, 1, opt_config, lr_config)\n lrs_cpu = [lr[0] for lr in lrs_cpu]\n assert np.allclose(lrs_cpu[:5], [0.005, 1.004, 2.003, 3.002, 4.001])\n assert np.allclose(lrs_cpu[5:10], 5.0)\n assert np.allclose(lrs_cpu[10:15], 0.5)\n assert np.allclose(lrs_cpu[15:20], 0.05)\n assert np.allclose(lrs_cpu[20:], 0.005)\n\n # warmup_iters % epoch_len == 0\n max_epochs = 3\n epoch_len = 3\n opt_config = dict(num_pram_groups=1, base_lr=5)\n lr_config = dict(type=\"step\", step_size=1, by_epoch=True, epoch_len=epoch_len,\n warmup_t=3, warmup_by_epoch=False, warmup_mode=\"factor\", warmup_factor=0.001)\n lrs_cpu = get_lrs_cpu(max_epochs, epoch_len, opt_config, lr_config)\n\n lr_config = dict(type='StepLrUpdaterHook', warmup='linear', warmup_iters=3,\n warmup_ratio=0.001, step=1, by_epoch=True)\n runner = MMCVRunner(max_epochs, epoch_len, opt_config, lr_config)\n lrs_mmcv = runner.run()\n assert allclose(lrs_cpu, lrs_mmcv)\n" ]
[ [ "torch.optim.lr_scheduler.CosineAnnealingWarmRestarts", "torch.optim.lr_scheduler.ReduceLROnPlateau", "numpy.allclose", "torch.optim.lr_scheduler.CosineAnnealingLR", "torch.zeros", "torch.optim.SGD" ] ]
LandingEllipse/pds4_tools
[ "3d833575b1fe0e0ac35c6e4ecbda1630b884df55" ]
[ "pds4_tools/viewer/plot_view.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport os\nimport re\nimport copy\nimport platform\nimport functools\nimport itertools\nfrom fractions import Fraction\n\nimport numpy as np\nimport matplotlib as mpl\nfrom matplotlib.figure import Figure\n\nfrom . import label_view, cache\nfrom .core import DataViewWindow, MessageWindow, Window\nfrom .mpl import (FigureCanvas, MPLCompat, get_mpl_linestyles, get_mpl_markerstyles,\n mpl_color_to_hex, mpl_color_to_inverted_rgb)\nfrom .widgets.notebook import TabBar, Tab\n\nfrom ..reader.data_types import is_pds_integer_data, data_type_convert_dates\nfrom ..reader.table_objects import Meta_Field\n\nfrom ..utils.compat import OrderedDict\n\nfrom ..extern import six\nfrom ..extern.six.moves import tkinter_colorchooser\nfrom ..extern.six.moves.tkinter import (Menu, Frame, Scrollbar, Listbox, Label, Entry, Button, Checkbutton,\n OptionMenu, DoubleVar, IntVar, BooleanVar, StringVar)\nfrom ..extern.six.moves.tkinter_tkfiledialog import asksaveasfilename\n\n#################################\n\n\nclass PlotViewWindow(DataViewWindow):\n \"\"\" Window that displays PDS4 data as plots.\n\n This window will display plots. After creating it, you should use the load_table() method to load\n the table that it needs to display.\n \"\"\"\n\n def __init__(self, viewer):\n\n # Create basic data view window\n super(PlotViewWindow, self).__init__(viewer)\n\n # Pack the display frame, which contains the scrollbars and the scrollable canvas\n self._display_frame.pack(side='left', anchor='nw', expand=1, fill='both')\n\n # Control variable for `freeze_display` and `thaw_display`. Image will not be updated on screen\n # when counter is greater than 1.\n self._freeze_display_counter = 0\n\n # Will be set to an instance of FigureCanvas (containing the main image/slice being displayed)\n self._figure_canvas = None\n\n # Will be set to an instance of MPL's Axes\n self._plot = None\n\n # Will be set to an instance of MPL's toolbar for TK\n self._toolbar = None\n\n # Will contain _Series objects, which describe each line/point series added to the plot\n self.series = []\n\n # Contains sub-widgets of the header\n self._header_widgets = {'x': None, 'y': None}\n\n # Menu option variables. These are TKinter type wrappers around standard Python variables. The\n # advantage is that you can use trace(func) on them, to automatically call func whenever one of\n # these variables is changed\n menu_options = [\n {'name': 'axis_limits', 'type': StringVar(), 'default': 'intelligent', 'trace': self._update_axis_limits},\n {'name': 'axis_scaling', 'type': StringVar(), 'default': 'linear-linear', 'trace': self._update_axis_scaling},\n {'name': 'show_title', 'type': BooleanVar(), 'default': False, 'trace': self._update_labels},\n {'name': 'show_labels', 'type': BooleanVar(), 'default': True, 'trace': self._update_labels},\n {'name': 'show_border', 'type': BooleanVar(), 'default': True, 'trace': self._update_border},\n {'name': 'tick_direction', 'type': StringVar(), 'default': 'in', 'trace': self._update_ticks},\n {'name': 'show_major_ticks', 'type': BooleanVar(), 'default': True, 'trace': self._update_ticks},\n {'name': 'show_minor_ticks', 'type': BooleanVar(), 'default': True, 'trace': self._update_ticks},\n {'name': 'show_tick_labels', 'type': StringVar(), 'default': 'both', 'trace': self._update_ticks},\n {'name': 'show_major_grid', 'type': BooleanVar(), 'default': False, 'trace': self._update_grid},\n {'name': 'show_minor_grid', 'type': BooleanVar(), 'default': False, 'trace': self._update_grid},\n {'name': 'grid_linestyle', 'type': StringVar(), 'default': 'dotted', 'trace': self._update_grid},\n {'name': 'invert_axis', 'type': StringVar(), 'default': 'none', 'trace': self._update_invert_axis},\n {'name': 'enlarge_level', 'type': DoubleVar(), 'default': 1, 'trace': self._update_enlarge_level},\n {'name': 'pan', 'type': BooleanVar(), 'default': False, 'trace': self._pan},\n {'name': 'axis_limits_to_rectangle', 'type': BooleanVar(), 'default': False, 'trace': self._axis_limits_to_rectangle}\n ]\n\n for option in menu_options:\n\n var = option['type']\n self._menu_options[option['name']] = var\n\n self._add_trace(var, 'w', option['trace'], option['default'])\n\n @property\n def settings(self):\n\n settings = super(PlotViewWindow, self).settings\n settings['labels'] = copy.deepcopy(settings['labels'])\n\n return settings\n\n # Loads the table structure into this window, displays a plot for the selected axes. axis_selections\n # is a list of field indexes in the table to use for the plot in the order x,y,x_err,y_err; to have one\n # of the indexes be row number, the string 'row' may be used for a field index. Set `lines` to have lines\n # connecting the data points; set `points` to have markers shown on data points. Set `mask_special` to\n # ignore special values (such as nulls and special constants) in plot.\n def load_table(self, table_structure, axis_selections, lines=True, points=False, mask_special=False):\n\n # Add series to storage\n series = _Series(table_structure, axis_selections)\n series_idx = len(self.series)\n self.series.append(series)\n\n # Add series to plot, do not continue with initialization if it has been done before\n if self._data_open:\n\n self._draw_series(series_idx, lines=lines, points=points, mask_special=mask_special)\n return\n\n # Set necessary instance variables for this DataViewWindow\n self._settings = {'title': None,\n 'labels': {'x': {'visible': self.menu_option('show_labels'), 'name': None},\n 'y': {'visible': self.menu_option('show_labels'), 'name': None}},\n 'pixel_init_dimensions': (0, 0), 'dpi': 80.}\n\n # Set a title for the window\n self.set_window_title(\"{0} - Plot from '{1}'\".format(self.get_window_title(), table_structure.id))\n\n # Create the header\n self._draw_header()\n\n # Add vertical scrollbar for the plot\n self._vert_scrollbar = Scrollbar(self._display_frame, orient='vertical', command=self._scrollable_canvas.yview)\n self._scrollable_canvas.config(yscrollcommand=self._vert_scrollbar.set)\n self._vert_scrollbar.pack(side='right', fill='y')\n\n # Add horizontal scrollbar for the plot\n self._horz_scrollbar = Scrollbar(self._display_frame, orient='horizontal', command=self._scrollable_canvas.xview)\n self._scrollable_canvas.config(xscrollcommand=self._horz_scrollbar.set)\n self._horz_scrollbar.pack(side='bottom', fill='x')\n\n # Pack the static canvas, which contains the scrollable canvas\n self._static_canvas.config(background='white')\n self._static_canvas.pack(side='left', anchor='nw', expand=1, fill='both')\n\n # Place the scrollable canvas, which contains the plot itself\n self._scrollable_canvas.config(background='white')\n self._scrollable_canvas.place(relx=0.5, rely=0.5, anchor='center')\n\n # Update idletasks such that the window takes on its real size\n self._widget.update_idletasks()\n\n # Draw plot / series to the screen\n self._draw_series(series_idx, lines=lines, points=points, mask_special=mask_special)\n\n # Add notify event for window resizing\n self._display_frame.bind('<Configure>', self._window_resize)\n\n # Add notify event for scroll wheel (used to change plot size via scroll wheel)\n self._bind_scroll_event(self._mousewheel_scroll)\n\n # Add notify event for mouse pointer exiting _scrollable_canvas (used to display locations\n # under the mouse pointer)\n self._figure_canvas.tk_widget.bind('<Leave>', self._update_mouse_pixel_value)\n\n # Add notify event for mouse motion (used to display pixel location under pointer)\n self._figure_canvas.mpl_canvas.mpl_connect('motion_notify_event', self._update_mouse_pixel_value)\n\n self._add_menus()\n self._data_open = True\n\n # Current enlarge level. E.g., a value of 2 means double the dimensions of the original plot.\n def get_enlarge_level(self):\n return self.menu_option('enlarge_level')\n\n # Current title. By default a string is returned; if mpl_text is True, an MPL text object for the title\n # label is returned instead. If the if_visible parameter is true, the title is returned only if it\n # is visible on the plot, otherwise None is returned.\n def get_title(self, mpl_text=False, if_visible=False):\n\n if if_visible and (not self.is_title_shown()):\n title = None\n\n elif mpl_text:\n title = self._plot.axes.title\n\n else:\n title = self._settings['title']\n\n return title\n\n # Current axis labels. Valid options for axis are x|y. By default a string is returned; if mpl_text is\n # True, an MPL text object for the axis label is returned instead. If the if_visible parameter is true,\n # the label is returned only if it is visible on the plot, otherwise None is returned.\n def get_axis_label(self, axis, mpl_text=False, if_visible=False):\n\n if axis not in ('x', 'y'):\n raise ValueError('Unknown label type: {0}'.format(axis))\n\n if if_visible and (not self.is_label_shown(axis)):\n axis_label = None\n\n elif mpl_text:\n\n ax = self._plot.axes\n axis = ax.xaxis if axis == 'x' else ax.yaxis\n\n axis_label = axis.get_label()\n\n else:\n axis_label = self._settings['labels'][axis]['name']\n\n return axis_label\n\n # Current tick labels. Valid options for axis are x|y, and for which are major|minor|both. By default a\n # string is returned; if mpl_text is True, an MPL text object for the axis label is returned instead. If\n # the if_visible parameter is true, the labels are returned only if visible on the plot, otherwise\n # None is returned.\n def get_tick_labels(self, axis, which='both', mpl_text=False, if_visible=False):\n\n # Ensure proper axis and which options specified\n if axis not in ('x', 'y'):\n raise ValueError('Unknown tick label type: {0}'.format(axis))\n\n elif which not in ('major', 'minor', 'both'):\n raise ValueError('Unknown tick label type: {0}'.format(which))\n\n # Gather proper tick labels\n tick_labels = []\n\n if (not if_visible) or self.is_tick_labels_shown(axis):\n\n ax = self._plot.axes\n axis = ax.xaxis if axis == 'x' else ax.yaxis\n tick_types = ['minor', 'major'] if which == 'both' else [which]\n\n for tick_type in tick_types:\n mpl_labels = axis.get_ticklabels(minor=(tick_type == 'minor'))\n\n if mpl_text:\n tick_labels += mpl_labels\n\n else:\n tick_labels += [label.get_text() for label in mpl_labels]\n\n return tick_labels\n\n # Current axis limits\n def get_axis_limits(self):\n\n ax = self._plot.axes\n return list(ax.get_xlim()), list(ax.get_ylim())\n\n # Current line options for the specified series\n def get_line_options(self, series):\n\n line = self.series[series].plot_line\n\n line_options = {\n 'visible': self.is_series_shown(series, which='line'),\n 'style': get_mpl_linestyles()[line.get_linestyle()],\n 'width': line.get_linewidth(),\n 'color': mpl_color_to_hex(line.get_color())\n }\n\n return line_options\n\n # Current point options for the specified series\n def get_point_options(self, series):\n\n line = self.series[series].plot_line\n\n point_options = {\n 'visible': self.is_series_shown(series, which='points'),\n 'style': get_mpl_markerstyles()[line.get_marker()],\n 'width': line.get_markersize(),\n 'color': mpl_color_to_hex(line.get_markerfacecolor()),\n 'frequency': line.get_markevery()\n }\n\n return point_options\n\n # Current error bar options for the specified series and direction (vertical or horizontal)\n def get_error_bar_options(self, series, which):\n\n if which not in ('vertical', 'horizontal'):\n raise ValueError('Unknown error bar type: {0}'.format(which))\n\n error_line = self.series[series].error_lines[which]\n error_caps = self.series[series].error_caps[which]\n\n if (error_line is None) or (not error_caps):\n return None\n\n # Calling MPL's `get_linestyle` on collections does not actually return the same value as passed in\n # when doing `set_linestyle`. E.g., it does not return 'solid', 'dashed', etc but rather a different\n # metric for the same thing. To obtain the name, we use two different methods below.\n try:\n # For MPL 1.x\n dash_dict = mpl.backend_bases.GraphicsContextBase.dashd\n\n except AttributeError:\n\n # For MPL 2.x\n from matplotlib.lines import _get_dash_pattern\n dash_dict = {}\n for key in ('solid', 'dashed', 'dotted', 'dashdot'):\n value = _get_dash_pattern(key)\n dash_dict[key] = value if not isinstance(value[1], (tuple, list)) else (value[0], list(value[1]))\n\n line_style = [key for key, value in six.iteritems(dash_dict)\n if error_line.get_linestyle()[0] == value]\n\n error_bar_options = {\n 'visible': self.is_error_bar_shown(series, which=which),\n 'style': line_style[0],\n 'width': error_line.get_linewidth()[0],\n 'color': mpl_color_to_hex(error_line.get_color()[0])\n }\n\n return error_bar_options\n\n # Get colors, as hex strings, of certain plot elements. Includes the plot and axes backgrounds,\n # the border, the ticks, the title and axis labels. All other colors can be obtained in other more\n # specific methods.\n def get_colors(self):\n\n colors = {}\n ax = self._plot.axes\n\n # Background color of middle portion of the plot (where the data lines are)\n try:\n colors['plot_background'] = ax.get_facecolor()\n except AttributeError:\n colors['plot_background'] = ax.get_axis_bgcolor()\n\n # Background color for outside portion of the plot (where axes are)\n colors['axes_background'] = self._figure_canvas.mpl_figure.get_facecolor()\n\n # Color of border\n colors['border'] = ax.spines['bottom'].get_edgecolor()\n\n # Color of ticks\n inverted_plot_bg = mpl_color_to_inverted_rgb(colors['plot_background'])\n ticks = ax.xaxis.get_ticklines()\n colors['ticks'] = ticks[0].get_color() if ticks else inverted_plot_bg\n\n # Color of tick labels\n inverted_axes_bg = mpl_color_to_inverted_rgb(colors['axes_background'])\n tick_labels = ax.xaxis.get_ticklabels()\n colors['tick_labels'] = tick_labels[0].get_color() if tick_labels else inverted_axes_bg\n\n # Color of title\n colors['title'] = ax.title.get_color()\n\n # Color of X-label\n colors['x_label'] = ax.xaxis.get_label().get_color()\n\n # Color of Y-label\n colors['y_label'] = ax.yaxis.get_label().get_color()\n\n # Convert to MPL colors to a hex string\n for name, mpl_color in six.iteritems(colors):\n\n colors[name] = mpl_color_to_hex(mpl_color)\n\n return colors\n\n # Current grid options for the specified grid lines, either major|minor\n def get_grid_options(self, which):\n\n if which not in ('major', 'minor'):\n raise ValueError('Unknown grid type: {0}'.format(which))\n\n axis = self._plot.axes.xaxis\n ticks = axis.majorTicks if which == 'major' else axis.minorTicks\n grid_line = ticks[0].gridline\n\n grid_options = {\n 'visible': self._menu_options['show_{0}_grid'.format(which)],\n 'style': get_mpl_linestyles()[grid_line.get_linestyle()],\n 'color': mpl_color_to_hex(grid_line.get_color())\n }\n\n return grid_options\n\n # Current tick options for the specified type of tick marks, either major|minor\n def get_tick_options(self, which):\n\n if which not in ('major', 'minor'):\n raise ValueError('Unknown tick type: {0}'.format(which))\n\n tick_options = {\n 'visible': self.menu_option('show_{0}_ticks'.format(which)),\n 'direction': self.menu_option('tick_direction'),\n 'labels': self._menu_options('show_tick_labels'),\n }\n\n return tick_options\n\n # Determine if the title is visible\n def is_title_shown(self):\n return self.menu_option('show_title')\n\n # Determine if the x and/or y axis labels are visible. Valid options for axis are x|y|both|any.\n def is_label_shown(self, axis):\n\n x_shown = self._settings['labels']['x']['visible']\n y_shown = self._settings['labels']['y']['visible']\n\n if axis == 'x':\n return x_shown\n\n elif axis == 'y':\n return y_shown\n\n elif axis == 'both':\n return x_shown and y_shown\n\n elif axis == 'any':\n return x_shown or y_shown\n\n else:\n raise ValueError('Unknown label type: {0}'.format(axis))\n\n # Determines if the tick labels are shown. Valid options for axis are x|y|both|any.\n def is_tick_labels_shown(self, axis):\n\n show_tick_labels = self.menu_option('show_tick_labels')\n\n if axis in ('x', 'y', 'both'):\n return show_tick_labels == axis\n\n elif axis == 'any':\n return show_tick_labels in ('x', 'y', 'both')\n\n else:\n raise ValueError('Unknown tick label type: {0}'.format(axis))\n\n # Determine if series is shown, as either line|points|both|any.\n def is_series_shown(self, series, which='any'):\n\n line = self.series[series].plot_line\n\n line_shown = get_mpl_linestyles()[line.get_linestyle()] != 'nothing'\n points_shown = get_mpl_markerstyles()[line.get_marker()] != 'nothing'\n\n if which == 'line':\n return line_shown\n\n elif which == 'points':\n return points_shown\n\n elif which == 'both':\n return line_shown and points_shown\n\n elif which == 'any':\n return line_shown or points_shown\n\n elif which not in('any', 'both', 'line', 'points'):\n raise ValueError('Unknown series type: {0}'.format(which))\n\n # Determine if error bars for a series are shown. Valid options for which are vertical|horizontal|both|any.\n # To determine whether error bars exist at all, set exist_only to True.\n def is_error_bar_shown(self, series, which='any', exist_only=False):\n\n vertical_error_lines = self.series[series].error_lines['vertical']\n horizontal_error_lines = self.series[series].error_lines['horizontal']\n vertical_shown = (vertical_error_lines is not None) and (exist_only or vertical_error_lines.get_visible())\n horizontal_shown = (horizontal_error_lines is not None) and (exist_only or horizontal_error_lines.get_visible())\n\n if (which == 'vertical') and vertical_shown:\n return True\n\n elif (which == 'horizontal') and horizontal_shown:\n return True\n\n elif (which == 'any') and (vertical_shown or horizontal_shown):\n return True\n\n elif (which == 'both') and (vertical_shown and horizontal_shown):\n return True\n\n elif which not in('vertical', 'horizontal', 'both', 'any'):\n raise ValueError('Unknown error bar type: {0}'.format(which))\n\n return False\n\n # Enlarges the initial plot dimensions by enlarge_level (e.g. enlarge_level of 2 will double the\n # dimensions of the original plot, a level of 0.5 will shrink it to half the original size.)\n def set_enlarge_level(self, enlarge_level):\n self._menu_options['enlarge_level'].set(enlarge_level)\n\n # Sets the axis title, and controls whether it is shown. If keyword is set to None, the current option\n # for that setting will be kept.\n def set_title(self, title=None, show=None, **kwargs):\n\n ax = self._plot.axes\n\n # Save the new title settings\n if title is not None:\n self._settings['title'] = title\n\n if show is not None:\n\n # We only adjust show_title in menu_options if it is not already set, otherwise there\n # is effectively an infinite loop since it calls this method again\n if self.is_title_shown() != show:\n self._menu_options['show_title'].set(show)\n\n # Set new title settings. We set an empty title if the title is not currently being shown\n # such that we can save font settings.\n if self.is_title_shown():\n title = self.get_title()\n\n else:\n title = ''\n\n # On set_title, MPL will override the below default_kwargs unless they are specified. To preserve\n # existing options, we obtain them and pass them on again unless they are overridden by *kwargs*.\n old_title = self.get_title(mpl_text=True)\n default_kwargs = {\n 'fontsize': old_title.get_fontsize(),\n 'fontweight': old_title.get_fontweight(),\n 'verticalalignment': old_title.get_verticalalignment(),\n 'horizontalalignment': old_title.get_horizontalalignment()}\n\n default_kwargs.update(kwargs)\n final_kwargs = default_kwargs\n\n ax.set_title(title, **final_kwargs)\n\n self._figure_canvas.draw()\n\n # Sets the axis labels, and controls whether they are shown. If keyword is set to None, the current option\n # for that setting will be kept.\n def set_axis_label(self, axis, label=None, show=None, **kwargs):\n\n ax = self._plot.axes\n\n if axis in ('x', 'y'):\n\n # Save new axis label settings\n settings = self._settings['labels'][axis]\n\n if label is not None:\n settings['name'] = label\n\n if show is not None:\n settings['visible'] = show\n\n # Set show_labels in current menu_options to True if at least one label is being shown,\n # We only adjust it if it does not already match, otherwise there is effectively an infinite\n # loop since it calls this method again\n any_label_shown = self.is_label_shown('any')\n show_labels = self._menu_options['show_labels']\n\n if any_label_shown != show_labels.get():\n show_labels.set(any_label_shown)\n\n # Set a new axis label if necessary. We set an empty label if the label is not currently\n # being shown such that we can save font settings.\n if self.is_label_shown(axis):\n label = self.get_axis_label(axis)\n\n else:\n label = ''\n\n if axis == 'x':\n ax.set_xlabel(label, **kwargs)\n\n else:\n ax.set_ylabel(label, **kwargs)\n\n else:\n raise ValueError('Unknown axis for axis labels: {0}'.format(axis))\n\n self._figure_canvas.draw()\n\n # Sets the axis limits. You may manually set axis limits, or use auto limits with the available options\n # being intelligent|auto|tight|manual. If set to None, the current axis limits will be kept.\n def set_axis_limits(self, x=None, y=None, auto=None):\n\n # Set auto limits\n if auto is not None:\n self._menu_options['axis_limits'].set(auto)\n\n # Set manual limits\n if (x is not None) or (y is not None):\n\n ax = self._plot.axes\n self._menu_options['axis_limits'].set('manual')\n\n if x is not None:\n ax.set_xlim(x)\n\n if y is not None:\n ax.set_ylim(y)\n\n self._figure_canvas.draw()\n\n # Sets axis scaling. Available options for each are linear|log|symlog. If set to None, the current axis\n # scaling will be kept for that axis.\n def set_axis_scaling(self, x=None, y=None):\n\n # Obtain the current axis scaling setting\n axis_scaling = self.menu_option('axis_scaling')\n x_scale, y_scale = axis_scaling.split('-')\n\n if x is None:\n x = x_scale\n\n if y is None:\n y = y_scale\n\n # Set new axis scaling\n axis_scaling = '{0}-{1}'.format(x, y)\n self._menu_options['axis_scaling'].set(axis_scaling)\n\n # Set plot and axes background colors, as well as colors of border and ticks. Other colors can be set\n # in other more specific methods. Each color must be an MPL acceptable color.\n def set_colors(self, plot_background=None, axes_background=None, border=None, ticks=None):\n\n ax = self._plot.axes\n\n # Set background color of middle portion of the plot (where the data lines are)\n MPLCompat.axis_set_facecolor(ax, plot_background)\n\n # Set background color for outside portion of the plot (where axes are)\n self._figure_canvas.mpl_figure.set_facecolor(axes_background)\n self._static_canvas.config(bg=mpl_color_to_hex(axes_background))\n\n # Set color of border\n for spine in ('top', 'bottom', 'left', 'right'):\n ax.spines[spine].set_color(border)\n\n # Set color of ticks\n tick_lines = (ax.xaxis.get_majorticklines() + ax.xaxis.get_minorticklines() +\n ax.yaxis.get_majorticklines() + ax.yaxis.get_minorticklines())\n\n for tick_line in tick_lines:\n tick_line.set_color(ticks)\n\n self._figure_canvas.draw()\n\n def invert_colors(self):\n\n # Freeze the plot display temporarily so it is not needlessly re-drawn multiple times\n self.freeze_display()\n\n colors = self.get_colors()\n\n # Set most colors\n kwargs = {}\n\n for option in ('plot_background', 'axes_background', 'border', 'ticks'):\n kwargs[option] = mpl_color_to_inverted_rgb(colors[option])\n\n self.set_colors(**kwargs)\n\n # Set grid color\n for grid_type in ('major', 'minor'):\n grid_color_hex = self.get_grid_options(grid_type)['color']\n grid_color = mpl_color_to_inverted_rgb(grid_color_hex)\n self.set_grid_options(grid_type, color=grid_color)\n\n # Set label and title colors\n title_color = mpl_color_to_inverted_rgb(colors['title'])\n x_label_color = mpl_color_to_inverted_rgb(colors['x_label'])\n y_label_color = mpl_color_to_inverted_rgb(colors['y_label'])\n tick_label_color = mpl_color_to_inverted_rgb(colors['tick_labels'])\n\n self.set_title(color=title_color)\n self.set_axis_label('x', color=x_label_color)\n self.set_axis_label('y', color=y_label_color)\n self.set_tick_label_options('both', which='both', color=tick_label_color)\n\n # Thaw the plot display since it was frozen above\n self.thaw_display()\n\n # Sets line options for each data series on the currently displayed plot. series specifies the index\n # for the data series on which the line options are to be adjusted. style is an MPL line style for the\n # error bar, color is an MPL color for the line, width is an integer controlling the width of the\n # line. The boolean show controls whether the line is visible on the plot.\n def set_line_options(self, series, style=None, width=None, color=None, show=None):\n\n line = self.series[series].plot_line\n\n # Show or hide line\n if (not show) or ((show is None) and (not self.is_series_shown(series, which='line'))):\n line.set_linestyle('none')\n\n elif style is not None:\n\n if style not in get_mpl_linestyles():\n style = get_mpl_linestyles(inverse=style)\n\n line.set_linestyle(style)\n\n # Set line options (can be set even if line is not shown)\n if width is not None:\n line.set_linewidth(width)\n\n if color is not None:\n line.set_color(color)\n\n self._figure_canvas.draw()\n\n # Sets point options for each data series on the currently displayed plot. series specifies the index\n # for the data series on which the point options are to be adjusted. style is an MPL marker name for the\n # error bar, color is an MPL color for the points, width is an integer controlling the width of the\n # points. The boolean show controls whether the points are visible on the plot.\n def set_point_options(self, series, style=None, width=None, color=None, frequency=None, show=None):\n\n line = self.series[series].plot_line\n\n # Show or hide points\n if (not show) or ((show is None) and (not self.is_series_shown(series, which='points'))):\n line.set_marker('None')\n\n elif style is not None:\n\n if style not in get_mpl_markerstyles():\n style = get_mpl_markerstyles(inverse=style)\n\n line.set_marker(style)\n\n # Set point options (can be set even if points are not shown)\n if width is not None:\n line.set_markersize(width)\n\n if frequency is not None:\n line.set_markevery(frequency)\n\n if color is not None:\n line.set_markerfacecolor(color)\n line.set_markeredgecolor(color)\n\n self._figure_canvas.draw()\n\n # Sets error bar options for each data series on the currently displayed plot. series specifies the index\n # for the data series on which the error bar options are to be adjusted. which can have values\n # vertical|horizontal|both, specifying for which error bar to set the selected options. style is an MPL\n # line style for the error bar, color is an MPL color for the error line, width is an integer controlling\n # the width of the error line. The boolean show controls whether the error bars are visible on the plot.\n def set_error_bar_options(self, series, which='both', style=None, width=None, color=None, show=None):\n\n _series = self.series[series]\n directions = ('vertical', 'horizontal') if which == 'both' else (which,)\n\n for which in directions:\n\n # Check if error bars exist for this direction prior to setting options\n if not self.is_error_bar_shown(series, which=which, exist_only=True):\n continue\n\n # Set error cap options\n for cap in _series.error_caps[which]:\n\n if show is not None:\n cap.set_visible(show)\n\n if color is not None:\n cap.set_markeredgecolor(color)\n\n # Error cap widths are set to preserve initial MPL proportions to error bar line width\n if width is not None:\n cap.set_markersize(4+width)\n cap.set_markeredgewidth(width/2)\n\n # Set error line options\n error_line = _series.error_lines[which]\n\n if show is not None:\n error_line.set_visible(show)\n\n if color is not None:\n error_line.set_color(color)\n\n if width is not None:\n error_line.set_linewidth(width)\n\n if style is not None:\n\n if style not in get_mpl_linestyles():\n style = get_mpl_linestyles(inverse=style)\n\n error_line.set_linestyle(style)\n\n self._figure_canvas.draw()\n\n # Sets grid options on the currently displayed plot. which can have values major|minor|both, specifying\n # to which grid lines the rest of the options apply. style is a MPL line style for the grid line,\n # color is an MPL line color and the show boolean specifies whether the grid lines will be visible. To\n # keep existing value for any variable use None.\n def set_grid_options(self, which='both', style=None, color=None, show=None):\n\n if which in ('major', 'minor', 'both'):\n\n # Show or hide grid\n if show is not None:\n\n if which in ('major', 'both'):\n self._menu_options['show_major_grid'].set(show)\n\n if which in ('minor', 'both'):\n self._menu_options['show_minor_grid'].set(show)\n\n # Set grid style\n if style is not None:\n self.menu_option('grid_linestyle').set(style)\n\n # Set grid color\n if color is not None:\n self._plot.axes.grid(which=which, color=color)\n\n # Setting the grid color above automatically displays grid even if it was not suppose to be\n # displayed. We run `_update_grid` to ensure it is hidden if it should be, while preserving\n # the linestyle and color changes.\n self._update_grid()\n\n else:\n raise ValueError('Unknown grid type: {0}'.format(which))\n\n self._figure_canvas.draw()\n\n # Sets tick options on the currently displayed plot. which can have values major|minor|both, specifying\n # which ticks to show or hide via the show boolean. direction can have values in|out, specifying in which\n # direction the ticks are facing in the plot if they are shown. To keep existing value for any variable\n # use None.\n def set_tick_options(self, which='both', direction=None, show=None):\n\n if which in ('major', 'minor', 'both'):\n\n # Show or hide ticks\n if show is not None:\n\n if which in ('major', 'both'):\n self._menu_options['show_major_ticks'].set(show)\n\n if which in ('minor', 'both'):\n self._menu_options['show_minor_ticks'].set(show)\n\n # Set tick direction\n if direction is not None:\n self._menu_options['tick_direction'].set(direction)\n\n else:\n raise ValueError('Unknown tick type: {0}'.format(which))\n\n # Set tick label options on the currently displayed plot. axis can have values x|y|both, and which\n # can have values major|minor|both, specifying which tick labels to adjust. show can have values\n # x|y|both|none, indicating which tick labels to show on the plot.\n def set_tick_label_options(self, axis, which='major', show=None, **kwargs):\n\n # Find the right axes to set tick labels\n if axis == 'both':\n axes = ('x', 'y')\n\n else:\n axes = (axis,)\n\n # Update whether tick labels for an axis are shown or not\n if show is not None:\n self._menu_options['show_tick_labels'].set(show)\n\n # Update tick label options for selected axes (must be done once they are shown)\n for axis in axes:\n\n tick_labels = self.get_tick_labels(axis=axis, which=which, mpl_text=True)\n\n for label in tick_labels:\n label.update(kwargs)\n\n self._figure_canvas.draw()\n\n # Controls certain axes display options for current plot. invert_axis can have values x|y|both|none.\n # show_border is a boolean that controls whether a border is displayed around image. To keep existing\n # values use None.\n def set_axes_display(self, invert_axis=None, show_border=None):\n\n if invert_axis is not None:\n self._menu_options['invert_axis'].set(invert_axis)\n\n if show_border is not None:\n self._menu_options['show_border'].set(show_border)\n\n # Save the plot image to disk (as currently displayed). The extension in filename controls the image\n # format unless *format* is set; likely supported formats are support png, pdf, ps, eps and svg.\n def save_image(self, filename, format=None):\n\n # Save figure, ensure facecolor is not ignored\n mpl_canvas = self._figure_canvas.mpl_canvas\n mpl_canvas.print_figure(filename,\n dpi=self._settings['dpi'],\n facecolor=self._figure_canvas.mpl_figure.get_facecolor(),\n format=format)\n\n # Freezes redrawing of image/plot on the screen, such that any updates to the plot are not reflected\n # until it is thawed via `thaw_display`. This can be helpful, both for performance reasons and to hide\n # ugly redrawing, if the plot would otherwise be redrawn a number of intermediate times.\n def freeze_display(self):\n\n # Increment counter that stores number of times freeze_display/thaw_display has been called\n self._freeze_display_counter += 1\n\n # If display is not already frozen, freeze it (by unpacking display_frame and freezing the canvas)\n if self._freeze_display_counter == 1:\n\n if self._figure_canvas is not None:\n self._figure_canvas.freeze()\n\n # Thaws a frozen display (see `freeze_display`)\n def thaw_display(self):\n\n # Decrement counter that stores number of times freeze_display/thaw_display has been called\n if self._freeze_display_counter > 0:\n self._freeze_display_counter -= 1\n\n # If display should be thawed, then do so\n if self._freeze_display_counter == 0:\n\n # Thaw the image now that its being displayed again\n if self._figure_canvas is not None:\n self._figure_canvas.thaw()\n\n # Update scrollable canvas to account for new scrollregion needed\n self._update_scrollable_canvas_dimensions()\n\n # Adds menu options used for manipulating the data display\n def _add_menus(self):\n\n # Add Save Plot option to the File menu\n file_menu = self._menu('File', in_menu='main')\n file_menu.insert_command(0, label='Save Plot', command=self._save_file_box)\n\n file_menu.insert_separator(1)\n\n # Add a Data menu\n data_menu = self._add_menu('Data', in_menu='main')\n\n data_menu.add_command(label='Lines / Points',\n command=lambda: self._open_plot_options('Lines / Points'))\n\n data_menu.add_separator()\n\n data_menu.add_command(label='Error Bars',\n command=lambda: self._open_plot_options('Error Bars'))\n\n # Add an Axes menu\n axes_menu = self._add_menu('Axes', in_menu='main')\n\n axes_menu.add_checkbutton(label='Tight Limits', onvalue='tight', offvalue='manual',\n variable=self._menu_options['axis_limits'])\n\n axes_menu.add_checkbutton(label='Auto Limits', onvalue='auto', offvalue='manual',\n variable=self._menu_options['axis_limits'])\n\n axes_menu.add_command(label='Manual Limits',\n command=lambda: self._open_plot_options('Axes'))\n\n axes_menu.add_separator()\n\n axes_menu.add_checkbutton(label='Pan', onvalue=True, offvalue=False, variable=self._menu_options['pan'])\n axes_menu.add_checkbutton(label='Axis-Limits to Rectangle', onvalue=True, offvalue=False,\n variable=self._menu_options['axis_limits_to_rectangle'])\n\n axes_menu.add_separator()\n\n invert_options = OrderedDict([('X', 'x'), ('Y', 'y'), ('XY', 'both')])\n for axis, option in six.iteritems(invert_options):\n\n label = 'Invert {0}'.format(axis)\n\n axes_menu.add_checkbutton(label=label, onvalue=option, offvalue='none',\n variable=self._menu_options['invert_axis'])\n\n axes_menu.add_separator()\n\n # Add an Axis Scaling sub-menu to the Axes menu\n axis_scaling_menu = self._add_menu('Axis Scaling', in_menu='Axes')\n\n axis_scaling = OrderedDict([('Linear-Linear', 'linear-linear'), ('Log-Log', 'log-log'),\n ('SymLog-SymLog', 'symlog-symlog'),\n ('X-Log', 'log-linear'), ('Y-Log', 'linear-log'),\n ('X-SymLog', 'symlog-linear'), ('Y-SymLog', 'linear-symlog')])\n for label, scale in six.iteritems(axis_scaling):\n\n if 'X' in label:\n axis_scaling_menu.add_separator()\n\n axis_scaling_menu.add_checkbutton(label=label, onvalue=scale, offvalue=scale,\n variable=self._menu_options['axis_scaling'])\n\n # Add a Chart menu\n chart_menu = self._add_menu('Chart', in_menu='main')\n\n # grid_menu.add_separator()\n #\n # for color in ('white', 'gray', 'black'):\n # grid_menu.add_checkbutton(label=color.upper(), onvalue=color, offvalue=color,\n # variable=self._menu_options['grid_color'])\n\n chart_menu.add_checkbutton(label='Show Plot Border', onvalue=True, offvalue=False,\n variable=self._menu_options['show_border'])\n\n chart_menu.add_separator()\n\n # Add a Grid sub-menu to the Chart menu\n grid_menu = self._add_menu('Grid', in_menu='Chart')\n\n grid_menu.add_checkbutton(label='Show Major Grid', onvalue=True, offvalue=False,\n variable=self._menu_options['show_major_grid'])\n\n grid_menu.add_checkbutton(label='Show Minor Grid', onvalue=True, offvalue=False,\n variable=self._menu_options['show_minor_grid'])\n\n grid_menu.add_separator()\n\n for grid_linestyle in ('dotted', 'dashed', 'dashdot', 'solid'):\n grid_menu.add_checkbutton(label=grid_linestyle.capitalize(), onvalue=grid_linestyle,\n offvalue=grid_linestyle, variable=self._menu_options['grid_linestyle'])\n\n chart_menu.add_separator()\n\n # Add a Ticks sub-menu to the Chart menu\n ticks_menu = self._add_menu('Ticks', in_menu='Chart')\n\n ticks_menu.add_checkbutton(label='Inward Facing Ticks', onvalue='in', offvalue='in',\n variable=self._menu_options['tick_direction'])\n ticks_menu.add_checkbutton(label='Outward Facing Ticks', onvalue='out', offvalue='out',\n variable=self._menu_options['tick_direction'])\n\n ticks_menu.add_separator()\n\n ticks_menu.add_checkbutton(label='Show Major Ticks', onvalue=True, offvalue=False,\n variable=self._menu_options['show_major_ticks'])\n ticks_menu.add_checkbutton(label='Show Minor Ticks', onvalue=True, offvalue=False,\n variable=self._menu_options['show_minor_ticks'])\n\n ticks_menu.add_separator()\n\n ticks_menu.add_checkbutton(label='Show Tick Labels', onvalue='both', offvalue='none',\n variable=self._menu_options['show_tick_labels'])\n\n chart_menu.add_separator()\n\n # Add a Legend sub-menu to the Chart menu\n # legend_menu = self._add_menu('Legend', in_menu='Chart')\n #\n # legend_menu.add_checkbutton(label='Show Legend', onvalue=True, offvalue=False,\n # variable=self._menu_options['show_legend'])\n #\n # legend_menu.add_command(label='Set Legend', command=\n # lambda: self._add_dependent_window(PlotOptionsWindow(self._viewer, self)))\n #\n # legend_menu.add_separator()\n #\n # for legend_position in ('upper right', 'upper left', 'lower right', 'lower left'):\n # legend_menu.add_checkbutton(label=legend_position.title(), onvalue=legend_position,\n # offvalue=legend_position, variable=self._menu_options['legend_position'])\n #\n # chart_menu.add_separator()\n\n chart_menu.add_command(label='Colors', command=\n lambda: self._open_plot_options(initial_display='Colors'))\n\n chart_menu.add_command(label='Invert Colors', command=self.invert_colors)\n\n # Add a Labels menu\n labels_menu = self._add_menu('Labels', in_menu='main')\n\n labels_menu.add_checkbutton(label='Show Title', onvalue=True, offvalue=False,\n variable=self._menu_options['show_title'])\n\n labels_menu.add_command(label='Set Title', command=lambda: self._open_plot_options('Labels'))\n\n labels_menu.add_separator()\n\n labels_menu.add_checkbutton(label='Show Axis Labels', onvalue=True, offvalue=False,\n variable=self._menu_options['show_labels'])\n\n labels_menu.add_command(label='Set Axis Labels', command=lambda: self._open_plot_options('Labels'))\n\n # Add a Size menu\n size_menu = self._add_menu('Size', in_menu='main')\n\n size_menu.add_command(label='Fit to Window Size', command=self.enlarge_to_fit)\n\n size_menu.add_separator()\n\n size_menu.add_command(label='Reset Original Size', command=lambda: self._enlarge(enlarge_level=1))\n\n size_menu.add_separator()\n\n size_menu.add_command(label='Enlarge Plot', command=lambda: self._enlarge('in'))\n size_menu.add_command(label='Shrink Plot', command=lambda: self._enlarge('out'))\n\n # Add a View Menu\n self._add_view_menu()\n\n # Adds a view menu\n def _add_view_menu(self):\n self._add_menu('View', in_menu='main', postcommand=self._update_view_menu)\n\n # Adds or updates menu options for the View menu\n def _update_view_menu(self):\n\n view_menu = self._menu('View')\n\n # Delete all items in the menu\n view_menu.delete(0, view_menu.index('last'))\n\n # Find unique structures\n structures = [series.structure for series in self.series]\n unique_structures = set(structures)\n\n # Add Labels sub-menu if necessary\n multi_label = len(unique_structures) > 1\n if multi_label:\n label_menu = self._add_menu('Labels', 'View')\n\n else:\n label_menu = view_menu\n\n # Add Label open button for each unique structure in plot\n for structure in unique_structures:\n\n labels = [structure.full_label, structure.label]\n label_text = 'Label - {}'.format(structure.id) if multi_label else 'Label'\n\n label_menu.add_command(label=label_text, command=lambda: label_view.open_label(\n self._viewer, *labels, initial_display='object label'))\n\n view_menu.add_separator()\n\n view_menu.add_command(label='Warnings',\n command=lambda: MessageWindow(self._viewer, 'Warnings', self._warnings))\n\n # Draws the header box, which contains the pixel location that mouse pointer is over\n def _draw_header(self):\n\n header_box = Frame(self._header, bg=self.get_bg('gray'))\n header_box.pack(fill='x', expand=1)\n\n value_box_params = {'background': self.get_bg('gray'), 'borderwidth': 1, 'relief': 'groove'}\n line_box_params = {'background': self.get_bg('gray'), 'height': 25}\n\n entry_params = {'disabledbackground': self.get_bg('gray'), 'state': 'disabled',\n 'borderwidth': 0, 'highlightthickness': 0, 'disabledforeground': 'black'}\n\n # Add the header line containing X and Y value the mouse is hovering over\n pixel_line_box = Frame(header_box, **line_box_params)\n pixel_line_box.pack(side='top', anchor='w', pady=(2, 2))\n\n pixel_text_box = Frame(pixel_line_box, height=25, width=70, bg=self.get_bg('gray'))\n pixel_text_box.pack(side='left')\n\n w = Label(pixel_text_box, text='Pixel', bg=self.get_bg('gray'))\n w.pack(side='left')\n\n # X value\n w = Label(pixel_text_box, text='X', bg=self.get_bg('gray'))\n w.pack(side='right', padx=(0, 5))\n\n pixel_text_box.pack_propagate(False)\n\n x_pixel_box = Frame(pixel_line_box, height=25, **value_box_params)\n x_pixel_box.pack(side='left')\n\n x_pixel = StringVar()\n self._header_widgets['x'] = x_pixel\n e = Entry(x_pixel_box, textvariable=x_pixel, width=13, **entry_params)\n e.pack(side='left', padx=(10, 10))\n\n # Y value\n w = Label(pixel_line_box, text='Y', bg=self.get_bg('gray'))\n w.pack(side='left', padx=(10, 5))\n\n y_pixel_box = Frame(pixel_line_box, height=25, **value_box_params)\n y_pixel_box.pack(side='left')\n\n y_pixel = StringVar()\n self._header_widgets['y'] = y_pixel\n e = Entry(y_pixel_box, textvariable=y_pixel, width=13, **entry_params)\n e.pack(side='left', padx=(10, 10))\n\n divider = Frame(header_box, height=1, bg='#737373')\n divider.pack(side='bottom', fill='x', expand=1)\n\n # Initializes or updates the MPL Figure and draws a plot for the series on it. load_table() must have\n # been called for the table this series came from prior to this method being called.\n def _draw_series(self, series, lines=None, points=None, mask_special=None):\n\n # Freeze the plot display temporarily so it is not needlessly re-drawn multiple times\n self.freeze_display()\n\n # Create the figure if it does not exist\n if not self._data_open:\n\n # Determine figure display properties\n dpi = self._settings['dpi']\n smallest_dim = min(self._static_canvas.winfo_width(), self._static_canvas.winfo_height())\n fig_size = (smallest_dim / dpi, smallest_dim / dpi)\n\n # Store initial figure size\n self._settings['pixel_init_dimensions'] = (smallest_dim, smallest_dim)\n\n # Create the figure\n figure_kwargs = {'figsize': fig_size, 'dpi': self._settings['dpi'], 'facecolor': 'white'}\n\n try:\n figure = Figure(tight_layout=True, **figure_kwargs)\n\n # MPL versions earlier than 1.1 do not have tight layout\n except TypeError:\n figure = Figure(**figure_kwargs)\n\n # Create the FigureCanvas, which is a wrapper for FigureCanvasTkAgg()\n self._figure_canvas = FigureCanvas(figure, master=self._scrollable_canvas)\n self._figure_canvas.tk_widget.config(background='white')\n self._scrollable_canvas.create_window(0, 0, window=self._figure_canvas.tk_widget, anchor='nw')\n\n # Create the toolbar (hidden, used for its pan and axis-limits to rectangle options)\n self._toolbar = MPLCompat.NavigationToolbar2Tk(self._figure_canvas.mpl_canvas, self._display_frame)\n self._toolbar.update()\n self._toolbar.pack_forget()\n\n # Add the plot axes\n self._plot = figure.add_subplot(1, 1, 1)\n\n # Add the plot / series to the axes\n _series = self.series[series]\n plot_line, error_caps, error_lines = self._plot.errorbar(_series.data('x', masked=mask_special),\n _series.data('y', masked=mask_special),\n xerr=_series.data('x_err', masked=mask_special),\n yerr=_series.data('y_err', masked=mask_special),\n capsize=3,\n zorder=500)\n _series.add_plot(plot_line, error_caps, error_lines)\n\n # Set default Lines and Points options\n self.set_line_options(series, width=1, style='solid', color='#0000ff', show=lines)\n self.set_point_options(series, style='point', color='#0000ff', show=points)\n\n # Set default Error Bar options\n self.set_error_bar_options(series, style='dotted', color='#3535ff', width=1)\n\n # Set default Title, Axis Labels and Tick Labels options\n self.set_title('', fontsize='14', fontweight='normal', y=1.01)\n self.set_axis_label('x', _series.label('x'), fontsize='11', fontweight='bold')\n self.set_axis_label('y', _series.label('y'), fontsize='11', fontweight='bold')\n self.set_tick_label_options(axis='both', which='both', fontsize='12')\n\n # Update all settings to match current menu_options\n self._update_labels()\n self._update_invert_axis()\n self._update_axis_scaling()\n self._update_grid()\n self._update_border()\n self._update_enlarge_level()\n\n # Thaw the plot display since it was frozen above\n self.thaw_display()\n\n # Activates the Pan image option\n def _pan(self, *args):\n\n # Disable axis-limits to rectangle if it is enabled\n limits_option = self._menu_options['axis_limits_to_rectangle']\n pan_option = self._menu_options['pan']\n\n if pan_option.get() and limits_option.get():\n limits_option.set(False)\n\n # Disable auto limits if enabled and if enabling pan\n auto_limits = self.menu_option('axis_limits') != 'manual'\n\n if auto_limits and pan_option.get():\n self.set_axis_limits(auto='manual')\n\n # Enable pan\n self._toolbar.pan()\n\n # Activates the Axis-Limits to Rectangle option\n def _axis_limits_to_rectangle(self, *args):\n\n # Disable pan if it is enabled\n limits_option = self._menu_options['axis_limits_to_rectangle']\n pan_option = self._menu_options['pan']\n\n if pan_option.get() and limits_option.get():\n pan_option.set(False)\n\n # Disable auto limits if enabled and if enabling axis-limits to rectangle\n auto_limits = self.menu_option('axis_limits') != 'manual'\n\n if auto_limits and limits_option.get():\n self.set_axis_limits(auto='manual')\n\n # Enable axis-limits to rectangle (called zoom by MPL)\n self._toolbar.zoom()\n\n # Update menu_options to specified enlarge_level, then call `_update_enlarge` to enlarge to that level.\n # If no enlarge level is specified then an action may be specified, and the plot size in changed in or out\n # (depending on the action) by the enlarge_level variable\n def _enlarge(self, action='in', enlarge_level=None):\n\n # Determine zoom level if none if specified\n if enlarge_level is None:\n\n # Obtain the current enlarge level\n enlarge_level = self.get_enlarge_level()\n\n # Determine enlarge level when adjusted by enlarge factor\n enlarge_factor = 0.20\n\n if action == 'in':\n enlarge_level *= (1 + enlarge_factor)\n else:\n enlarge_level /= (1 + enlarge_factor)\n\n # Save the new enlarge level\n self.set_enlarge_level(enlarge_level)\n\n # Enlarge image to the level set by menu_options\n def _update_enlarge_level(self, *args):\n\n # Freeze the plot display temporarily so it is not needlessly re-drawn multiple times\n self.freeze_display()\n\n fig_size = self._settings['pixel_init_dimensions']\n\n # Change figure size by enlarge_level\n enlarge_level = self.get_enlarge_level()\n enlarged_size = [fig_size[0] * enlarge_level,\n fig_size[1] * enlarge_level]\n\n # Ensure that the enlarged size is at least 1x1 pixel\n enlarged_size[0] = 1 if enlarged_size[0] < 1 else enlarged_size[0]\n enlarged_size[1] = 1 if enlarged_size[1] < 1 else enlarged_size[1]\n\n # Resize the figure to match the enlarge level\n self._figure_canvas.set_dimensions(enlarged_size, type='pixels')\n\n # Update ticks to set new tick lengths, and new number of ticks\n self._update_ticks(adjust_num_ticks=True)\n\n # The scrollable canvas dimensions change since plot dimensions change and need updating\n self._update_scrollable_canvas_dimensions()\n\n # Thaw the plot display since it was frozen above\n self.thaw_display()\n\n # Enlarge or shrink the plot to fit the current window\n def enlarge_to_fit(self):\n\n fig_size = self._settings['pixel_init_dimensions']\n\n # Retrieve width and height of static_canvas (the width and height that we need to fit)\n self._widget.update_idletasks()\n width = self._static_canvas.winfo_width()\n height = self._static_canvas.winfo_height()\n\n fig_size_div = (width / fig_size[0],\n height / fig_size[1])\n\n enlarge_level = min(fig_size_div)\n self._enlarge(enlarge_level=enlarge_level)\n\n # Determine if either axis is a date. Valid options for axis are x|y|both|any.\n def _is_date_axis(self, axis):\n\n x_date = False\n y_date = False\n\n # Check if any serious has datetime data\n for _series in self.series:\n\n if (not x_date) and _series.meta_data('x').data_type().issubtype('datetime'):\n x_date = True\n\n if (not y_date) and _series.meta_data('y').data_type().issubtype('datetime'):\n y_date = True\n\n # Return result\n if axis == 'x':\n return x_date\n\n elif axis == 'y':\n return y_date\n\n elif axis == 'both':\n return x_date and y_date\n\n elif axis == 'any':\n return x_date or y_date\n\n else:\n raise ValueError('Unknown axis: {0}'.format(axis))\n\n # Update axis limits setting to match the current menu_options value\n def _update_axis_limits(self, *args):\n\n # Freeze the plot display temporarily so it is not needlessly re-drawn multiple times\n self.freeze_display()\n\n # Obtain the current axis limits settings\n axis_limits = self.menu_option('axis_limits')\n\n # Keep track of when to reset margins (needed when turning off tight limits)\n reset_margins = False\n\n # Set new axis limits\n ax = self._plot.axes\n\n # Disable pan and axis-limits to rectangle if they are enabled and we are not on manual axis limits\n if axis_limits != 'manual':\n\n limits_option = self._menu_options['axis_limits_to_rectangle']\n pan_option = self._menu_options['pan']\n\n if limits_option.get():\n limits_option.set(False)\n\n elif pan_option.get():\n pan_option.set(False)\n\n # Intelligent limits. If error bars are present or only points are on, equivalent to auto scaling. Otherwise\n # uses tight scaling for linear data, and uses auto scaling for all others.\n if axis_limits == 'intelligent':\n\n shows_error_bars = False\n shows_only_points = False\n\n for i in range(0, len(self.series)):\n\n if self.is_series_shown(i, which='points') and (not self.is_series_shown(i, which='line')):\n shows_only_points = True\n break\n\n elif self.is_series_shown(i) and self.is_error_bar_shown(i):\n shows_error_bars = True\n break\n\n if (ax.get_xscale() == 'linear') and (ax.get_yscale() == 'linear') and \\\n (not shows_error_bars) and (not shows_only_points):\n\n ax.autoscale(axis='both', enable=True, tight=True)\n\n else:\n reset_margins = True\n ax.autoscale(axis='both', enable=True, tight=False)\n\n # Automatic limits. Usually uses axis limits which are somewhat bigger than data limits.\n elif axis_limits == 'auto':\n reset_margins = True\n ax.autoscale(axis='both', enable=True, tight=False)\n\n # Tight limits. Constrains axis limits to exactly data limits.\n elif axis_limits == 'tight':\n ax.autoscale(axis='both', enable=True, tight=True)\n\n elif axis_limits != 'manual':\n ax.autoscale(axis='both', enable=False)\n\n self._menu_options['axis_limits'].set('intelligent')\n raise ValueError('Unknown axis limits: {0}'.format(axis_limits))\n\n # Set default margins for MPL 2+. Otherwise setting autoscale to tight permanently sets these to 0,\n # which means that auto and intelligent limits will not work in the 'data' autolimit mode.\n if reset_margins and (mpl.rcParams.get('axes.autolimit_mode') == 'data'):\n ax.margins(x=0.05, y=0.05)\n\n # Update ticks to set new number of ticks\n self._update_ticks(adjust_num_ticks=True)\n\n # Thaw the plot display since it was frozen above\n self.thaw_display()\n\n # Update scaling of the axes to match the current menu_options values\n def _update_axis_scaling(self, *args):\n\n # Obtain the current axis scaling setting\n axis_scaling = self.menu_option('axis_scaling')\n\n # Find new axis scaling for axes\n ax = self._plot.axes\n x_scale, y_scale = axis_scaling.split('-')\n\n if (x_scale not in ('linear', 'log', 'symlog')) or (y_scale not in ('linear', 'log', 'symlog')):\n\n self._menu_options['axis_scaling'].set('linear-linear')\n raise ValueError('Unknown scale type: {0}'.format(axis_scaling))\n\n else:\n\n # Freeze the plot display temporarily so it is not needlessly re-drawn multiple times\n self.freeze_display()\n\n # Set new scaling of the axes\n if not self._is_date_axis('x'):\n ax.set_xscale(x_scale)\n\n if not self._is_date_axis('y'):\n ax.set_yscale(y_scale)\n\n # For intelligent axis limits we need to update the axis limits based on current scale type.\n # Inside this method it also updates ticks, which is necessary because setting new scaling above\n # automatically adjusts some tick options (e.g. minor tick visibility).\n self._update_axis_limits()\n\n # Thaw the plot display since it was frozen above\n self.thaw_display()\n\n def _update_labels(self, *args):\n\n # Freeze the plot display temporarily so it is not needlessly re-drawn multiple times\n self.freeze_display()\n\n # Obtain current axis label settings\n show_title = self.menu_option('show_title')\n show_labels = self.menu_option('show_labels')\n\n # Show / Hide labels\n show_both_labels = show_labels and (not self.is_label_shown('any'))\n hide_both_labels = (not show_labels) and self.is_label_shown('any')\n\n if show_both_labels or hide_both_labels:\n\n self.set_axis_label('x', show=show_labels)\n self.set_axis_label('y', show=show_labels)\n\n # Show / Hide title\n self.set_title(show=show_title)\n\n # Thaw the plot display since it was frozen above\n self.thaw_display()\n\n # Update tick options (show / hide ticks and labels, and tick direction) to match\n # current menu_options values\n def _update_ticks(self, adjust_num_ticks=False, *args):\n\n # Obtain current tic settings\n show_major_ticks = self.menu_option('show_major_ticks')\n show_minor_ticks = self.menu_option('show_minor_ticks')\n show_tick_labels = self.menu_option('show_tick_labels')\n tick_direction = self.menu_option('tick_direction')\n\n ax = self._plot.axes\n\n # Validate tick labels setting\n if show_tick_labels not in ('x', 'y', 'both', 'none'):\n self._menu_options['show_tick_labels'].set('both')\n raise ValueError('Unknown tick labels axis to display: {0}'.format(show_tick_labels))\n\n # Validate tick direction setting\n if tick_direction not in ('in', 'out'):\n self._menu_options['tick_direction'].set('in')\n raise ValueError('Unknown tick direction selected: {0}'.format(tick_direction))\n\n # Determine a good tick length for the current plot size\n width, height = self._figure_canvas.get_dimensions(type='pixels')\n major_tick_length = max(4, 4 * min(width, height) / 400)\n minor_tick_length = major_tick_length / 2\n\n # Set new major tick settings (show / hide, direction, labels and size)\n ax.tick_params(axis='both', which='major', direction=tick_direction,\n bottom=show_major_ticks, top=show_major_ticks,\n left=show_major_ticks, right=show_major_ticks,\n labelbottom=show_tick_labels in ('x', 'both'),\n labelleft=show_tick_labels in ('y', 'both'),\n length=major_tick_length, width=0.5)\n\n # Set number of major tick labels for X-axis (in small plots, these are prone to overlapping)\n # This is intended to work with the default tick label fonts and font sizes only.\n if adjust_num_ticks and ax.get_xscale() == 'linear':\n\n # Initially we reset to default number of major ticks\n # (ensures that when enlarging plot from a small plot, we go back to proper number of ticks;\n # we distinguish for date axes because AutoDateLocator does not support locator_params)\n if self._is_date_axis('x'):\n ax.xaxis.set_major_locator(mpl.dates.AutoDateLocator())\n else:\n self._plot.locator_params(axis='x', nbins=9, prune='both')\n\n # The correct tick labels are not given by MPL's ``Axis.get_ticklabels`` until they are drawn\n # (it will return empty text objects instead). To avoid the ugly redrawing of the plot to\n # obtain the correct tick labels (needed below), we use the draw method of the Axes instead.\n # This does not seem to actually draw anything on the screen, but afterward we can obtain the\n # correct tick labels as expected.\n renderer = self._figure_canvas.mpl_canvas.get_renderer()\n ax.draw(renderer)\n\n plot_size = self._figure_canvas.get_dimensions(type='pixels')\n\n num_iterations = 0\n num_ticks = len(ax.xaxis.get_ticklabels())\n\n while True:\n\n # Get tick labels (note that this only works if plot has been redrawn\n # once the parameters that determine the tick labels were set)\n tick_labels = [label.get_text() for label in ax.xaxis.get_ticklabels()]\n\n # Remove mathtext, as we do cannot actually estimate its length easily\n tick_labels = [re.sub(r'\\$.+\\$', '', label) for label in tick_labels]\n\n num_label_chars = len(''.join(tick_labels))\n num_tick_labels = len(tick_labels)\n num_bins = num_ticks - num_iterations\n\n if num_tick_labels <= 2 or num_label_chars <= 1 or num_bins <= 0:\n break\n\n # Adjust maximum number of ticks so that the below equation is satisfied\n # (the specific number is chosen based on experimentation of what looks good;\n # we distinguish for date axes because AutoDateLocator does not support locator_params)\n avg_label_len = sum(map(len, tick_labels)) / num_tick_labels\n max_density = min(20 - avg_label_len, 15)\n\n if plot_size[0] / num_label_chars < max_density:\n\n if self._is_date_axis('x'):\n ax.xaxis.set_major_locator(mpl.dates.AutoDateLocator(maxticks=num_bins))\n else:\n self._plot.locator_params(axis='x', nbins=num_bins, prune='both')\n\n else:\n break\n\n num_iterations += 1\n\n # Set new minor tick settings (show / hide, direction and size)\n if show_minor_ticks:\n\n # Enable minor ticks\n ax.minorticks_on()\n\n ax.tick_params(axis='both', which='minor', direction=tick_direction,\n bottom=True, top=True, left=True, right=True,\n length=minor_tick_length, width=0.5)\n\n # Turning off major ticks makes them completely disappear. Instead we show them, but shorter,\n # so they look the same as minor ticks.\n if not show_major_ticks:\n ax.tick_params(axis='both', which='major', direction=tick_direction,\n bottom=True, top=True, left=True, right=True,\n length=minor_tick_length, width=0.5)\n\n else:\n\n # Instead of `axis.minorticks_off` we set length to 0. The former method has the disadvantage that\n # minor grid lines will not appear when minor ticks are off.\n ax.tick_params(axis='both', which='minor', length=0, width=0)\n\n # Remove offset and scientific notation when tick labels are not shown\n for axis_name, axis_select in six.iteritems({'x': ax.xaxis, 'y': ax.yaxis}):\n\n if isinstance(axis_select.get_major_formatter(), mpl.ticker.ScalarFormatter):\n\n use_offset = show_tick_labels in (axis_name, 'both')\n style = 'sci' if use_offset else 'plain'\n\n ax.ticklabel_format(useOffset=use_offset, style=style, axis=axis_name)\n\n self._figure_canvas.draw()\n\n # Update the plot border visibility to match current menu_options value\n def _update_border(self, *args):\n\n # Obtain current border setting\n show_border = self.menu_option('show_border')\n ax = self._plot.axes\n\n for spine in ['top', 'bottom', 'left', 'right']:\n ax.spines[spine].set_visible(show_border)\n\n self._figure_canvas.draw()\n\n # Update grid options (show/hide and linestyle) to match current menu_options values\n def _update_grid(self, *args):\n\n # Obtain current grid settings\n show_major_grid = self.menu_option('show_major_grid')\n show_minor_grid = self.menu_option('show_minor_grid')\n grid_linestyle = self.menu_option('grid_linestyle')\n\n ax = self._plot.axes\n\n if grid_linestyle not in ('solid', 'dashed', 'dashdot', 'dotted'):\n\n self._menu_options['grid_linestyle'].set('dotted')\n raise ValueError('Unknown grid linestyle: {0}'.format(grid_linestyle))\n\n # Set major grid line settings\n if show_major_grid:\n ax.grid(which='major', linestyle=grid_linestyle, linewidth=1)\n else:\n ax.grid(which='major', b=False)\n\n # Set minor grid line settings\n if show_minor_grid:\n\n ax.grid(which='minor', linestyle=grid_linestyle, linewidth=0.5)\n\n # Show major grid line with same thickness as minor grid lines if it is not enabled. Otherwise\n # there will simply be missing grid lines in those spots.\n if not show_major_grid:\n ax.grid(which='major', linestyle=grid_linestyle, linewidth=0.5)\n\n else:\n ax.grid(which='minor', b=False)\n\n self._figure_canvas.draw()\n\n # Update axis inversion to match current menu_options value\n def _update_invert_axis(self, *args):\n\n invert_axis = self.menu_option('invert_axis')\n ax = self._plot.axes\n\n # Reset any axis inversion\n if ax.yaxis_inverted():\n ax.invert_yaxis()\n\n if ax.xaxis_inverted():\n ax.invert_xaxis()\n\n # Invert X, Y or both axes based on current menu settings\n if invert_axis == 'x':\n ax.invert_xaxis()\n\n elif invert_axis == 'y':\n ax.invert_yaxis()\n\n elif invert_axis == 'both':\n ax.invert_xaxis()\n ax.invert_yaxis()\n\n elif invert_axis != 'none':\n self._menu_options['invert_axis'].set('none')\n raise ValueError('Unknown axis to invert: {0}'.format(invert_axis))\n\n self._figure_canvas.draw()\n\n # Sets the X and Y in the header based on current mouse pointer location\n def _update_mouse_pixel_value(self, event):\n\n event_outside_bounds = True\n\n # If the event is an MPL MouseEvent then we may have scrolled mouse on the image\n if isinstance(event, mpl.backend_bases.MouseEvent):\n\n event_has_position = (event.xdata is not None) and (event.ydata is not None)\n is_on_plot = event.inaxes == self._plot.axes\n\n if event_has_position and is_on_plot:\n\n self._header_widgets['x'].set(round(event.xdata, 5))\n self._header_widgets['y'].set(round(event.ydata, 5))\n\n event_outside_bounds = False\n\n # Remove values from X and Y if the mouse pointer is not on the image\n if event_outside_bounds:\n self._header_widgets['x'].set('')\n self._header_widgets['y'].set('')\n\n # Opens a PlotOptionsWindow\n def _open_plot_options(self, initial_display=None):\n\n window = PlotOptionsWindow(self._viewer, self._widget, self, initial_display=initial_display)\n self._add_dependent_window(window)\n\n # Called when the window has been resized, this method updates the dimensions of the various things that\n # need resizing together with a window resize\n def _window_resize(self, event):\n\n self._update_window_dimensions()\n self._update_scrollable_canvas_dimensions()\n\n # Updates scrollable canvas size and scroll region, needed any time the contents of scrollable canvas\n # have changed size\n def _update_scrollable_canvas_dimensions(self):\n\n self._widget.update_idletasks()\n\n # Retrieve width and height of the image\n dimensions = self._figure_canvas.get_dimensions()\n scroll_width = dimensions[0]\n scroll_height = dimensions[1]\n\n # Adjust width and height of the _scrollable_canvas, while ensuring that it is not larger than the\n # window dimensions (or more specifically the static_canvas dimensions, because both header and\n # scrollbars take up some space)\n width = scroll_width\n if width > self._static_canvas.winfo_width():\n width = self._static_canvas.winfo_width()\n\n height = scroll_height\n if height > self._static_canvas.winfo_height():\n height = self._static_canvas.winfo_height()\n\n self._scrollable_canvas.configure(width=width, height=height)\n self._scrollable_canvas.configure(scrollregion=(0, 0, scroll_width, scroll_height))\n\n # Called on mouse wheel scroll action, zooms image in or out\n def _mousewheel_scroll(self, event):\n\n # A forced update seems to be required on Mac in order to not break scrollbars during\n # quick changes, e.g. on quick zoom changes via mousewheel.\n if platform.system() == 'Darwin':\n self._widget.update()\n\n # Zoom in\n if event.delta > 0:\n self._enlarge('in')\n\n # Zoom out\n else:\n self._enlarge('out')\n\n # Dialog window to save the plot as currently displayed\n def _save_file_box(self):\n\n mpl_canvas = self._figure_canvas.mpl_canvas\n filetypes = mpl_canvas.get_supported_filetypes().copy()\n default_filetype = mpl_canvas.get_default_filetype()\n\n default_filetype_name = filetypes[default_filetype]\n del filetypes[default_filetype]\n\n sorted_filetypes = list(six.iteritems(filetypes))\n sorted_filetypes.sort()\n sorted_filetypes.insert(0, (default_filetype, default_filetype_name))\n\n tk_filetypes = [(name, '*.%s' % ext) for (ext, name) in sorted_filetypes]\n\n initial_dir = cache.get_last_open_dir(if_exists=True)\n initial_file = mpl_canvas.get_default_filename()\n\n # We add an empty defaultextension because otherwise changing to any extension does not work properly\n filename = asksaveasfilename(title='Save the figure',\n parent=self._widget,\n filetypes=tk_filetypes,\n initialdir=initial_dir,\n initialfile=initial_file,\n defaultextension='')\n\n if filename == '' or filename == ():\n return\n\n cache.write_last_open_dir(os.path.dirname(filename))\n\n # Save the plot image\n self.save_image(filename)\n\n def close(self):\n\n self.series = None\n\n if self._toolbar is not None:\n self._toolbar = None\n\n if self._figure_canvas is not None:\n self._figure_canvas.destroy()\n\n super(PlotViewWindow, self).close()\n\n\nclass PlotOptionsWindow(Window):\n \"\"\" Window used to show and set numerous options for the plot in PlotViewWindow\n\n Allows control over Labels, Lines and Points, Error Bars, Colors and Axes Limits and Scaling.\n \"\"\"\n\n def __init__(self, viewer, master, plot_view_window, initial_display=None):\n\n # Set initial necessary variables and do other required initialization procedures\n super(PlotOptionsWindow, self).__init__(viewer, withdrawn=True)\n\n # Set the title\n self.set_window_title('{0} - Plot Options'.format(self.get_window_title()))\n\n # Set PlotOptionsWindow to be transient, meaning it does not show up in the task bar and it stays\n # on top of its master window. This encourages the user to close this window when they are done\n # with it, otherwise it is easy to spawn many identical windows because numerous menu options of\n # PlotViewWindow lead to this PlotOptionsWindow.\n self._widget.transient(master)\n\n # Set the PlotViewWindow as an instance variable\n self._structure_window = plot_view_window\n\n # Initialize necessary instance variables used to store values in all tabs\n self._line_options = []\n self._point_options = []\n self._error_bar_options = []\n self._labels_options = {'x_label': None, 'y_label': None, 'title': None}\n self._color_options = {'plot_background': None, 'axes_background': None,\n 'border': None, 'ticks': None, 'grid': None}\n self._axes_options = {'axis_limits': None, 'axis_scale_x': None, 'axis_scale_y': None,\n 'min_x': None, 'max_x': None, 'min_y': None, 'max_y': None}\n\n # Box which will contain the Tabs\n self._tab_box = Frame(self._widget)\n self._tab_box.pack(side='top', fill='both', expand=1, padx=10, pady=10)\n\n # Add a tab bar, which allows switching of tabs\n self._tab_menu = TabBar(self._tab_box, init_name=initial_display)\n\n # Create and add all the tabs, each of which allows user to modify the plot\n self._add_labels_tab()\n self._add_lines_points_tab()\n self._add_error_bars_tab()\n self._add_colors_tab()\n self._add_axes_tab()\n\n self._tab_menu.show()\n\n # Add Apply and Close buttons for the whole window\n buttons_box = Frame(self._widget)\n buttons_box.pack(side='top', pady=(0, 10))\n bottom_buttons_params = {'bd': 1, 'width': 5, 'font': self.get_font(size=10)}\n\n plot = Button(buttons_box, text='Apply', command=self._apply, **bottom_buttons_params)\n plot.grid(row=0, column=0, padx=5)\n\n close = Button(buttons_box, text='Close', command=self.close, **bottom_buttons_params)\n close.grid(row=0, column=2, padx=5)\n\n # Set window size (maximum size of any tab for each dimension, the Apply/Close buttons, and padding)\n width, height = self._tab_menu.dimensions()\n width += 20\n height += buttons_box.winfo_reqheight() + 35\n self.set_window_geometry(width=width, height=height)\n self._center_window()\n\n # Update window to ensure it has taken its final form, then show it\n self._widget.update_idletasks()\n self.show_window()\n\n # Add tab and contents that control Labels options (text, visibility, font, size, style, color, )\n def _add_labels_tab(self):\n\n tab = Tab(self._tab_box, 'Labels')\n\n content_box = Frame(tab)\n content_box.pack(anchor='nw', pady=10)\n\n # Header\n label = Label(content_box, text='Show', font=self.get_font(10))\n label.grid(row=0, column=2, padx=2)\n\n label = Label(content_box, text='Font Family', font=self.get_font(10))\n label.grid(row=0, column=3)\n\n label = Label(content_box, text='Size (pt)', font=self.get_font(10))\n label.grid(row=0, column=4)\n\n label = Label(content_box, text='Style', font=self.get_font(10))\n label.grid(row=0, column=5, padx=(0, 5))\n\n label = Label(content_box, text='Color', font=self.get_font(10))\n label.grid(row=0, column=6)\n\n # Add buttons and menus to control settings\n for i, name in enumerate(['Title', 'X Label', 'Y Label', 'Tick Labels']):\n\n if name == 'Title':\n\n plot_label_mpl = self._structure_window.get_title(mpl_text=True)\n plot_label = self._structure_window.get_title(mpl_text=False)\n show_label = self._structure_window.is_title_shown()\n\n elif name in ('X Label', 'Y Label'):\n\n axis = name.split(' ')[0].lower()\n\n plot_label_mpl = self._structure_window.get_axis_label(axis, mpl_text=True)\n plot_label = self._structure_window.get_axis_label(axis, mpl_text=False)\n show_label = self._structure_window.is_label_shown(axis)\n\n else:\n\n plot_label_mpl = self._structure_window.get_tick_labels(axis='x', which='major', mpl_text=True)[0]\n plot_label = self._structure_window.get_tick_labels(axis='x', mpl_text=False)[0]\n show_label = self._structure_window.is_tick_labels_shown('both')\n\n option_menu_params = {'highlightthickness': 1, 'takefocus': 1}\n\n # Label text\n label = Label(content_box, text=name, font=self.get_font(10))\n label.grid(row=i+1, column=0, padx=5)\n\n if name != 'Tick Labels':\n entry_width = 30 if platform.system() == 'Windows' else 20\n entry = Entry(content_box, width=entry_width, bg='white')\n entry.insert(0, plot_label)\n entry.grid(row=i+1, column=1, ipady=3, padx=(0, 5))\n\n # Label visibility\n show = BooleanVar()\n show.set(show_label)\n\n show_button = Checkbutton(content_box, variable=show)\n show_button.grid(row=i+1, column=2)\n\n # Label font name\n fonts = sorted(set([font.name for font in mpl.font_manager.fontManager.ttflist]))\n font_name = StringVar()\n font_name.set(plot_label_mpl.get_name())\n\n font_name_params = ({'width': 20} if platform.system() == 'Windows' else\n {'width': 15, 'font': self.get_font(9)})\n font_name_params.update(option_menu_params)\n\n option_menu = OptionMenu(content_box, font_name, *fonts)\n option_menu.config(**font_name_params)\n option_menu.grid(row=i+1, column=3, padx=(0, 5))\n\n # Label font size\n font_size = IntVar()\n font_size.set(int(plot_label_mpl.get_size()))\n\n option_menu = OptionMenu(content_box, font_size, *range(6, 30))\n option_menu.config(width=5, **option_menu_params)\n option_menu.grid(row=i+1, column=4, padx=(0, 5))\n\n # Bold font\n style_options = Frame(content_box)\n style_options.grid(row=i+1, column=5, padx=(0, 5))\n\n weight = plot_label_mpl.get_weight()\n current_bold = (weight == 'bold') or (isinstance(weight, int) and weight >= 700)\n bold = BooleanVar()\n bold.set(current_bold)\n\n bold_button = Checkbutton(style_options, text='Bold', variable=bold)\n bold_button.pack(side='left', padx=(0, 2))\n\n # Italic font\n italic = BooleanVar()\n italic.set(plot_label_mpl.get_style() == 'italic')\n\n italic_button = Checkbutton(style_options, text='Italic', variable=italic)\n italic_button.pack(side='left')\n\n # Label color\n current_colors = self._structure_window.get_colors()\n type_name = name.lower().replace(' ', '_')\n font_color = StringVar()\n font_color.set(current_colors[type_name])\n\n color_width = 10 if platform.system() == 'Windows' else 8\n color_picker = functools.partial(self._choose_color, type=type_name)\n color_button = Button(content_box, textvariable=font_color, width=color_width,\n font=self.get_font(size=9), command=color_picker)\n color_button.grid(row=i+1, column=6, padx=(0, 5))\n\n self._labels_options[type_name] = {'value': entry,\n 'show': show,\n 'font': font_name,\n 'size': font_size,\n 'bold': bold,\n 'italic': italic,\n 'color': font_color}\n\n self._tab_menu.add(tab)\n\n # Add tab and contents that control Lines and Points options for each data series (visibility, font, size,\n # style, color, frequency)\n def _add_lines_points_tab(self):\n\n tab = Tab(self._tab_box, 'Lines / Points')\n\n series_box = Frame(tab)\n series_box.pack(side='top', anchor='nw', padx=5, pady=15)\n\n option_menu_params = {'highlightthickness': 1, 'takefocus': 1}\n\n # Selected Data Series for which all the below options apply\n # (only one series can currently be plotted at a time)\n label = Label(series_box, text='Series: ', font=self.get_font(10))\n label.pack(side='left')\n\n series = IntVar()\n series.set(0)\n\n option_menu = OptionMenu(series_box, series, *range(0, len(self._structure_window.series)))\n option_menu.config(width=5, **option_menu_params)\n option_menu.pack(side='left')\n\n caption_box = Frame(tab)\n caption_box.pack(side='top', anchor='nw', padx=5, pady=(0, 10))\n\n # Frame that stores the contents for the Lines and Points options\n options_box = Frame(tab)\n options_box.pack(anchor='nw', padx=10, pady=(0, 15))\n\n # Header for Line Options\n label = Label(options_box, text='Show', font=self.get_font(10))\n label.grid(row=0, column=0)\n\n label = Label(options_box, text='Line Style', font=self.get_font(10))\n label.grid(row=0, column=1)\n\n label = Label(options_box, text='Line Width', font=self.get_font(10))\n label.grid(row=0, column=2)\n\n label = Label(options_box, text='Line Color', font=self.get_font(10))\n label.grid(row=0, column=3)\n\n # For each data series, show Line Options (currently this does not really work, as only one data\n # series can be plotted at a time. In the future, the contents of each iteration could be put into a\n # single frame and which frame is displayed controlled based on the selected series)\n for i in range(0, len(self._structure_window.series)):\n\n current_opts = self._structure_window.get_line_options(series.get())\n\n # Visibility\n current_show_line = self._structure_window.is_series_shown(series.get(), which='line')\n show_line = BooleanVar()\n show_line.set(current_show_line)\n\n show_button = Checkbutton(options_box, text='Line', variable=show_line)\n show_button.grid(row=1, column=0, padx=(0, 5))\n\n # Line style\n current_line_style = current_opts['style'] if current_show_line else 'solid'\n line_style = StringVar()\n line_style.set(current_line_style)\n\n option_menu = OptionMenu(options_box, line_style, *get_mpl_linestyles(include_none=False).values())\n option_menu.config(width=15, **option_menu_params)\n option_menu.grid(row=1, column=1, padx=(0, 5))\n\n # Line width\n line_width = IntVar()\n line_width.set(int(current_opts['width']))\n\n option_menu = OptionMenu(options_box, line_width, *range(1, 10))\n option_menu.config(width=5, **option_menu_params)\n option_menu.grid(row=1, column=2, padx=(0, 5))\n\n # Line color\n line_color = StringVar()\n line_color.set(current_opts['color'])\n\n color_picker = functools.partial(self._choose_color, type='line', index=i)\n color_button = Button(options_box, textvariable=line_color, width=10,\n font=self.get_font(size=9), command=color_picker)\n color_button.grid(row=1, column=3, padx=(0, 5))\n\n self._line_options.append({'show': show_line,\n 'style': line_style,\n 'width': line_width,\n 'color': line_color})\n\n # Header for Point Options\n label = Label(options_box, text='Show', font=self.get_font(10))\n label.grid(row=2, column=0, pady=(10, 0))\n\n label = Label(options_box, text='Point Style', font=self.get_font(10))\n label.grid(row=2, column=1, pady=(10, 0))\n\n label = Label(options_box, text='Point Width', font=self.get_font(10))\n label.grid(row=2, column=2, pady=(10, 0))\n\n label = Label(options_box, text='Point Color', font=self.get_font(10))\n label.grid(row=2, column=3, pady=(10, 0))\n\n label = Label(options_box, text='Frequency', font=self.get_font(10))\n label.grid(row=2, column=4, pady=(10, 0), padx=(0, 10))\n\n # For each data series, show Point Options (currently this does not really work, as only one data\n # series can be plotted at a time. In the future, the contents of each iteration could be put into a\n # single frame and which frame is displayed controlled based on the selected series)\n for i in range(0, len(self._structure_window.series)):\n\n current_opts = self._structure_window.get_point_options(series.get())\n\n # Visibility\n current_show_points = self._structure_window.is_series_shown(i, which='points')\n show_points = BooleanVar()\n show_points.set(current_show_points)\n\n show_button = Checkbutton(options_box, text='Points', variable=show_points)\n show_button.grid(row=3, column=0, padx=(0, 5))\n\n # Point style\n current_points_style = current_opts['style'] if current_show_points else 'point'\n points_style = StringVar()\n points_style.set(current_points_style)\n\n option_menu = OptionMenu(options_box, points_style, *get_mpl_markerstyles(include_none=False).values())\n option_menu.config(width=15, **option_menu_params)\n option_menu.grid(row=3, column=1, padx=(0, 5))\n\n # Point width\n point_widths = itertools.chain(range(1, 10), range(10, 22, 2))\n points_width = IntVar()\n points_width.set(int(current_opts['width']))\n\n option_menu = OptionMenu(options_box, points_width, *point_widths)\n option_menu.config(width=5, **option_menu_params)\n option_menu.grid(row=3, column=2, padx=(0, 5))\n\n # Point color\n points_color = StringVar()\n points_color.set(current_opts['color'])\n\n color_picker = functools.partial(self._choose_color, type='points', index=i)\n color_button = Button(options_box, textvariable=points_color, width=10,\n font=self.get_font(size=9), command=color_picker)\n color_button.grid(row=3, column=3, padx=(0, 5))\n\n if current_opts['frequency']:\n current_point_frequency = '1/{0}'.format(current_opts['frequency'])\n\n else:\n current_point_frequency = '1/1'\n\n # Point frequency\n point_periods = itertools.chain(range(1, 10), range(10, 50, 5), range(50, 525, 50))\n point_frequencies = ['1/{0}'.format(period) for period in point_periods]\n points_frequency = StringVar()\n points_frequency.set(current_point_frequency)\n\n option_menu = OptionMenu(options_box, points_frequency, *point_frequencies)\n option_menu.config(width=15, **option_menu_params)\n option_menu.grid(row=3, column=4, padx=(0, 5))\n\n self._point_options.append({'show': show_points,\n 'style': points_style,\n 'width': points_width,\n 'color': points_color,\n 'frequency': points_frequency})\n\n self._tab_menu.add(tab)\n\n # Add tab and contents that control Error Bar options for each data series (visibility, size, style\n # and color)\n def _add_error_bars_tab(self):\n\n tab = Tab(self._tab_box, 'Error Bars')\n\n series_box = Frame(tab)\n series_box.pack(side='top', anchor='nw', padx=5, pady=15)\n\n # Selected Data Series for which all the below options apply\n # (only one series can currently be plotted at a time)\n label = Label(series_box, text='Series: ', font=self.get_font(10))\n label.pack(side='left')\n\n series = IntVar()\n series.set(0)\n\n option_menu_params = {'highlightthickness': 1, 'takefocus': 1}\n\n option_menu = OptionMenu(series_box, series, *range(0, len(self._structure_window.series)))\n option_menu.config(width=5, **option_menu_params)\n option_menu.pack(side='left')\n\n caption_box = Frame(tab)\n caption_box.pack(side='top', anchor='nw', padx=5, pady=(0, 10))\n\n # Frame that stores the contents for the Error Bar vertical and horizontal options\n options_box = Frame(tab)\n options_box.pack(anchor='nw', padx=10, pady=(0, 15))\n\n # Options for each error bar direction\n for i, which in enumerate(('vertical', 'horizontal')):\n\n current_opts = self._structure_window.get_error_bar_options(series.get(), which=which)\n no_error_bar = False\n\n # Set options to show if error bar does not exist\n if current_opts is None:\n\n no_error_bar = True\n current_opts = {'style': 'dotted',\n 'width': 1,\n 'color': '#000000'}\n\n # Header for Error Bar Options\n label = Label(options_box, text='Show', font=self.get_font(10))\n label.grid(row=i*2, column=0)\n\n label = Label(options_box, text='Line Style', font=self.get_font(10))\n label.grid(row=i*2, column=1)\n\n label = Label(options_box, text='Line Width', font=self.get_font(10))\n label.grid(row=i*2, column=2)\n\n label = Label(options_box, text='Line Color', font=self.get_font(10))\n label.grid(row=i*2, column=3)\n\n # For each data series, show Error Bar Options (currently this does not really work, as only one\n # data series can be plotted at a time. In the future, the contents of each iteration could be\n # put into a single frame and which frame is displayed controlled based on the selected series)\n for j in range(0, len(self._structure_window.series)):\n\n # Visibility\n current_show_error_bar = self._structure_window.is_error_bar_shown(series.get(), which=which)\n show_error_bar = BooleanVar()\n show_error_bar.set(current_show_error_bar)\n\n disabled_error_bar = {'state': 'disabled'} if no_error_bar else {}\n show_button = Checkbutton(options_box, text=which.capitalize(), variable=show_error_bar,\n **disabled_error_bar)\n show_button.grid(row=i*2+j+1, column=0, padx=(0, 5), pady=(0, 10))\n\n # Line style\n current_line_style = current_opts['style'] if current_show_error_bar else 'dotted'\n line_style = StringVar()\n line_style.set(current_line_style)\n\n option_menu = OptionMenu(options_box, line_style, *get_mpl_linestyles(include_none=False).values())\n option_menu.config(width=15, **option_menu_params)\n option_menu.grid(row=i*2+j+1, column=1, padx=(0, 5), pady=(0, 10))\n\n # Line width\n line_width = IntVar()\n line_width.set(int(current_opts['width']))\n\n option_menu = OptionMenu(options_box, line_width, *range(1, 10))\n option_menu.config(width=5, **option_menu_params)\n option_menu.grid(row=i*2+j+1, column=2, padx=(0, 5), pady=(0, 10))\n\n # Line color\n line_color = StringVar()\n line_color.set(current_opts['color'])\n\n color_picker = functools.partial(self._choose_color, type='error_bar_{0}'.format(which), index=j)\n color_button = Button(options_box, textvariable=line_color, width=10,\n font=self.get_font(size=9), command=color_picker)\n color_button.grid(row=i*2+j+1, column=3, padx=(0, 5), pady=(0, 10))\n\n self._error_bar_options.append({'vertical': {},\n 'horizontal': {}})\n\n self._error_bar_options[j][which] = {'show': show_error_bar,\n 'style': line_style,\n 'width': line_width,\n 'color': line_color}\n\n self._tab_menu.add(tab)\n\n # Add tab and contents that control Colors of plot elements, including plot and axis backgrounds,\n # as well as border, tick and grid line colors\n def _add_colors_tab(self):\n\n tab = Tab(self._tab_box, 'Colors')\n current_colors = self._structure_window.get_colors()\n\n content_box = Frame(tab)\n content_box.pack(anchor='nw', padx=5, pady=10)\n\n pady = 1 if platform.system() == 'Linux' else 2\n\n # Plot Background color\n label = Label(content_box, text='Plot Background:', font=self.get_font(10))\n label.grid(row=0, column=0, sticky='w', padx=(0, 10), pady=pady)\n\n plot_background_color = StringVar()\n plot_background_color.set(current_colors['plot_background'])\n\n color_picker = functools.partial(self._choose_color, type='plot_background')\n color_button = Button(content_box, textvariable=plot_background_color, width=10,\n font=self.get_font(size=9), command=color_picker)\n color_button.grid(row=0, column=1, sticky='w', pady=pady)\n\n # Axes Background color\n label = Label(content_box, text='Axes Background:', font=self.get_font(10))\n label.grid(row=1, column=0, sticky='w', pady=pady)\n\n axes_background_color = StringVar()\n axes_background_color.set(current_colors['axes_background'])\n\n color_picker = functools.partial(self._choose_color, type='axes_background')\n color_button = Button(content_box, textvariable=axes_background_color, width=10,\n font=self.get_font(size=9), command=color_picker)\n color_button.grid(row=1, column=1, sticky='w', pady=pady)\n\n # Plot Border color\n label = Label(content_box, text='Border:', font=self.get_font(10))\n label.grid(row=2, column=0, sticky='w', pady=pady)\n\n border_color = StringVar()\n border_color.set(current_colors['border'])\n\n color_picker = functools.partial(self._choose_color, type='border')\n color_button = Button(content_box, textvariable=border_color, width=10,\n font=self.get_font(size=9), command=color_picker)\n color_button.grid(row=2, column=1, sticky='w', pady=pady)\n\n # Tick color\n label = Label(content_box, text='Ticks:', font=self.get_font(10))\n label.grid(row=3, column=0, sticky='w', pady=pady)\n\n tick_color = StringVar()\n tick_color.set(current_colors['ticks'])\n\n color_picker = functools.partial(self._choose_color, type='ticks')\n color_button = Button(content_box, textvariable=tick_color, width=10,\n font=self.get_font(size=9), command=color_picker)\n color_button.grid(row=3, column=1, sticky='w', pady=pady)\n\n # Grid Line color\n label = Label(content_box, text='Grid Lines:', font=self.get_font(10))\n label.grid(row=4, column=0, sticky='w', pady=pady)\n\n grid_color = StringVar()\n grid_color.set(self._structure_window.get_grid_options('major')['color'])\n\n color_picker = functools.partial(self._choose_color, type='grid')\n color_button = Button(content_box, textvariable=grid_color, width=10,\n font=self.get_font(size=9), command=color_picker)\n color_button.grid(row=4, column=1, sticky='w', pady=pady)\n\n # Label colors (directing to other tabs)\n label = Label(content_box, text='Labels:', font=self.get_font(10))\n label.grid(row=5, column=0, sticky='w', pady=pady)\n\n label = Label(content_box, text='See appropriate tab above.', font=self.get_font(10))\n label.grid(row=5, column=1, sticky='w', pady=pady)\n\n # Lines and Points colors (directing to other tabs)\n label = Label(content_box, text='Lines / Points:', font=self.get_font(10))\n label.grid(row=6, column=0, sticky='w', pady=(pady, 0))\n\n label = Label(content_box, text='See appropriate tab above.', font=self.get_font(10))\n label.grid(row=6, column=1, sticky='w', pady=(pady, 0))\n\n self._color_options = {'plot_background': plot_background_color,\n 'axes_background': axes_background_color,\n 'border': border_color,\n 'ticks': tick_color,\n 'grid': grid_color}\n\n self._tab_menu.add(tab)\n\n # Add tab and contents that control Axes limits and scaling.\n def _add_axes_tab(self):\n\n tab = Tab(self._tab_box, 'Axes')\n\n content_box = Frame(tab)\n content_box.pack(anchor='nw', padx=5, pady=10)\n\n text_params = {'font': self.get_font(10)}\n\n option_menus_box = Frame(content_box)\n option_menus_box.pack(side='top', anchor='nw')\n\n option_menu_params = {'highlightthickness': 1, 'takefocus': 1}\n\n # Automatic Axis Limits\n w = Label(option_menus_box, text='Axis Limits:', **text_params)\n w.grid(row=0, column=0, sticky='w')\n\n current_axis_limits = self._structure_window.menu_option('axis_limits')\n axis_limits = self._axes_options['axis_limits'] = StringVar()\n self._add_trace(axis_limits, 'w', self._update_limits_setting, default=current_axis_limits.capitalize())\n\n menu = OptionMenu(option_menus_box, axis_limits, *('Intelligent', 'Tight', 'Auto', 'Manual'))\n menu.config(width=15, **option_menu_params)\n menu.grid(row=0, column=1)\n\n # Manual Axis Limits\n manual_limits_box = Frame(content_box)\n manual_limits_box.pack(side='top', anchor='nw', pady=10)\n\n manual_limits = BooleanVar()\n self._add_trace(manual_limits, 'w', self._update_limits_setting, default=(current_axis_limits == 'manual'))\n\n b = Checkbutton(manual_limits_box, text='Manual Limits', variable=axis_limits,\n onvalue='Manual', offvalue='Intelligent', **text_params)\n b.grid(row=0, column=0, pady=(0, 5))\n\n # Add Entries containing limits for each axis\n for i, axis in enumerate(('x', 'y')):\n\n w = Label(manual_limits_box, text='{0} Limits:'.format(axis.upper()), **text_params)\n w.grid(row=i+1, column=0)\n\n w = Label(manual_limits_box, text='Low', **text_params)\n w.grid(row=i+1, column=1, padx=(0, 5))\n\n x_lim, y_lim = self._structure_window.get_axis_limits()\n\n current_min = x_lim[0] if axis == 'x' else y_lim[0]\n current_max = x_lim[1] if axis == 'x' else y_lim[1]\n\n min_entry = Entry(manual_limits_box, width=15, bg='white')\n min_entry.grid(row=i+1, column=2, ipady=3, pady=3)\n min_entry.insert(0, current_min)\n self._axes_options['min_{0}'.format(axis)] = min_entry\n\n w = Label(manual_limits_box, text='High', **text_params)\n w.grid(row=i+1, column=3, padx=(10, 5))\n\n max_entry = Entry(manual_limits_box, width=15, bg='white')\n max_entry.grid(row=i+1, column=4, ipady=3, pady=3)\n max_entry.insert(0, current_max)\n self._axes_options['max_{0}'.format(axis)] = max_entry\n\n # Axis Scaling\n axis_scaling_box = Frame(content_box)\n axis_scaling_box.pack(side='top', anchor='nw')\n\n w = Label(axis_scaling_box, text='Axis Scaling ', **text_params)\n w.pack(side='top', anchor='w')\n\n axis_scales = ('Linear', 'Log', 'SymLog')\n x_scale, y_scale = self._structure_window.menu_option('axis_scaling').split('-')\n x_scale_idx = [item.lower() for item in axis_scales].index(x_scale)\n y_scale_idx = [item.lower() for item in axis_scales].index(y_scale)\n\n axis_scale_x = StringVar()\n axis_scale_x.set(axis_scales[x_scale_idx])\n\n axis_scale_y = StringVar()\n axis_scale_y.set(axis_scales[y_scale_idx])\n\n # X-axis scaling\n w = Label(axis_scaling_box, text='X', **text_params)\n w.pack(side='left', padx=(20, 3))\n\n m = OptionMenu(axis_scaling_box, axis_scale_x, *axis_scales)\n m.config(width=15, **option_menu_params)\n m.pack(side='left')\n\n # Y-axis scaling\n w = Label(axis_scaling_box, text='Y', **text_params)\n w.pack(side='left', padx=(10, 3))\n\n m = OptionMenu(axis_scaling_box, axis_scale_y, *axis_scales)\n m.config(width=15, **option_menu_params)\n m.pack(side='left')\n\n # Enable / disable entries for manual axis limits\n self._update_limits_setting()\n\n self._axes_options = {'axis_limits': axis_limits,\n 'min_x': self._axes_options['min_x'], 'max_x': self._axes_options['max_x'],\n 'min_y': self._axes_options['min_y'], 'max_y': self._axes_options['max_y'],\n 'axis_scale_x': axis_scale_x,\n 'axis_scale_y': axis_scale_y}\n\n self._tab_menu.add(tab)\n\n # Color selection for any color in this window.\n def _choose_color(self, type, index=None):\n\n if type in ('title', 'x_label', 'y_label', 'tick_labels'):\n\n label_option = self._labels_options[type]\n color = label_option['color']\n\n elif type == 'line':\n\n line_option = self._line_options[index]\n color = line_option['color']\n\n elif type == 'points':\n\n point_option = self._point_options[index]\n color = point_option['color']\n\n elif type in ('plot_background', 'axes_background', 'ticks', 'border', 'grid'):\n\n color = self._color_options[type]\n\n elif type in ('error_bar_vertical', 'error_bar_horizontal'):\n\n axis = type.split('_')[2]\n color = self._error_bar_options[index][axis]['color']\n\n else:\n raise ValueError('Unknown type for color choice: {0}'.format(type))\n\n # Get new label color\n rgb, hex = tkinter_colorchooser.askcolor(parent=self._widget, initialcolor=color.get())\n\n # Set new color\n if hex is not None:\n color.set(hex)\n\n # Applies all options in all tabs to the plot\n def _apply(self):\n\n # Freeze the plot display temporarily so it is not needlessly re-drawn multiple times\n self._structure_window.freeze_display()\n\n # Update / show / hide title and labels\n for label_name in ('title', 'x_label', 'y_label', 'tick_labels'):\n\n label_opts = self._labels_options[label_name]\n\n label_value = label_opts['value'].get()\n label_show = label_opts['show'].get()\n\n kwargs = {'fontname': label_opts['font'].get(),\n 'fontweight': 'bold' if label_opts['bold'].get() else 'normal',\n 'fontstyle': 'italic' if label_opts['italic'].get() else 'normal',\n 'fontsize': label_opts['size'].get(),\n 'color': label_opts['color'].get()}\n\n if label_name == 'title':\n self._structure_window.set_title(label_value, show=label_show, **kwargs)\n\n elif label_name in ('x_label', 'y_label'):\n axis = label_name.split('_')[0]\n self._structure_window.set_axis_label(axis, label_value, show=label_show, **kwargs)\n\n else:\n label_show = 'both' if label_show else 'none'\n self._structure_window.set_tick_label_options(axis='both', which='major',\n show=label_show, **kwargs)\n\n # Update Lines and Points\n for series in range(0, len(self._line_options)):\n\n line_opts = self._line_options[series]\n point_opts = self._point_options[series]\n error_opts = self._error_bar_options[series]\n\n # Update Lines\n self._structure_window.set_line_options(series,\n style=line_opts['style'].get(),\n width=line_opts['width'].get(),\n color=line_opts['color'].get(),\n show=line_opts['show'].get())\n # Update Points\n self._structure_window.set_point_options(series,\n style=point_opts['style'].get(),\n width=point_opts['width'].get(),\n color=point_opts['color'].get(),\n frequency=Fraction(point_opts['frequency'].get()).denominator,\n show=point_opts['show'].get())\n\n # Update Error Bars\n for which in 'vertical', 'horizontal':\n\n error_opts_axis = error_opts[which]\n self._structure_window.set_error_bar_options(series,\n which=which,\n style=error_opts_axis['style'].get(),\n width=error_opts_axis['width'].get(),\n color=error_opts_axis['color'].get(),\n show=error_opts_axis['show'].get())\n\n # Update colors for Foreground, Background, Border and Ticks\n color_opts = self._color_options\n self._structure_window.set_colors(plot_background=color_opts['plot_background'].get(),\n axes_background=color_opts['axes_background'].get(),\n border=color_opts['border'].get(),\n ticks=color_opts['ticks'].get())\n\n # Update colors of Grid lines\n self._structure_window.set_grid_options(which='both', color=color_opts['grid'].get())\n\n # Update axis limits\n axes_opts = self._axes_options\n axis_limits = axes_opts['axis_limits'].get().lower()\n\n if axis_limits == 'manual':\n\n self._structure_window.set_axis_limits(x=(float(axes_opts['min_x'].get()), float(axes_opts['max_x'].get())),\n y=(float(axes_opts['min_y'].get()), float(axes_opts['max_y'].get())))\n\n else:\n\n self._structure_window.set_axis_limits(auto=axis_limits)\n\n # Update axis scaling\n self._structure_window.set_axis_scaling(x=axes_opts['axis_scale_x'].get().lower(),\n y=axes_opts['axis_scale_y'].get().lower())\n\n # Thaw the plot display since it was frozen above\n self._structure_window.thaw_display()\n\n # Updates whether manual axis limits options are enabled or disabled in the Axes tab based on user\n # selection changes in that tab.\n def _update_limits_setting(self, *args):\n\n opts = self._axes_options\n\n # Determine necessary state\n if opts['axis_limits'].get().lower() == 'manual':\n state = 'normal'\n\n else:\n state = 'disabled'\n\n # Set necessary state\n for axis in ('x', 'y'):\n\n opts['min_{0}'.format(axis)].config(state=state)\n opts['max_{0}'.format(axis)].config(state=state)\n\n def close(self):\n\n self._structure_window = None\n super(PlotOptionsWindow, self).close()\n\n\nclass PlotColumnsWindow(Window):\n \"\"\" Window allowing a user to choose which table columns to plot.\"\"\"\n\n def __init__(self, viewer, table_structure):\n\n # Set initial necessary variables and do other required initialization procedures\n super(PlotColumnsWindow, self).__init__(viewer, withdrawn=True)\n\n # Set the title\n self.set_window_title(\"{0} - Select Plot Columns from Table '{1}'\".\n format(self.get_window_title(), table_structure.id))\n\n # Initialize plot columns window variables\n self._structure = table_structure\n\n # Will lists RowNumber, followed by the names of all fields in the table\n self._field_listbox = None\n\n # Will contain an Entry for each axis (X, Y, X_Err, Y_Err in that order), where the entry contains\n # the name of the selected field\n self._axis_entries = [None, None, None, None]\n\n # Contains the index for the selected field (the index in field_listbox) for each axis. This index\n # is 1 bigger than the field's index in table_structure.data, because of RowNumber.\n self._axis_selections = [None, None, None, None]\n\n # Contains field indexes that are disabled in the field listbox (because said fields\n # cannot be plotted, i.e, they are not numeric or not 1 dimensional)\n self._disabled_indexes = []\n\n # Controls whether lines and points checkbuttons are checked (and subsequently which type will be\n # drawn for the plot), and whether special constants are ignored on the plot\n self._lines = BooleanVar()\n self._points = BooleanVar()\n self._mask_special = BooleanVar()\n\n # Draw the main window content\n self.draw_content()\n\n # Update window to ensure it has taken its final form, then show it\n self._widget.update_idletasks()\n self.show_window()\n\n # Draws the main content of the window\n def draw_content(self):\n\n left_side_box = Frame(self._widget)\n left_side_box.pack(side='left', fill='both', expand=1)\n\n # Listbox containing RowNumber and all the field names\n field_name_width = 30 if platform.system() == 'Windows' else 22\n self._field_listbox = Listbox(left_side_box, width=field_name_width, activestyle='none', bg='white',\n highlightthickness=0, bd=0)\n self._field_listbox.pack(side='left', fill='both', expand=1)\n\n field_scrollbar = Scrollbar(left_side_box, orient='vertical', command=self._field_listbox.yview)\n self._field_listbox.config(yscrollcommand=field_scrollbar.set)\n field_scrollbar.pack(side='right', fill='y')\n\n # Add RowNumber to listbox\n self._field_listbox.insert('end', ' ' + 'RowNumber')\n\n # Add field names to listbox\n for i, field in enumerate(self._structure.fields):\n self._field_listbox.insert('end', ' ' + field.meta_data.full_name(skip_parents=True).upper())\n\n # Disable non-numeric fields, fields with more than one dimension and fields with only one value\n is_flat_array = (len(field.shape) == 1) and (field.size > 1)\n is_numeric_array = np.issubdtype(field.dtype, np.floating) or is_pds_integer_data(data=field)\n is_date_array = field.meta_data.data_type().issubtype('datetime')\n\n if (not is_flat_array) or (not is_numeric_array and not is_date_array):\n self._disabled_indexes.append(i+1)\n self._field_listbox.itemconfig(i + 1, {'fg': '#999999', 'selectforeground': '#999999',\n 'selectbackground': self._field_listbox.cget('background')})\n\n right_side_box = Frame(self._widget, bg=self.get_bg('gray'))\n right_side_box.pack(side='right', fill='both')\n\n instructions = Label(right_side_box, wraplength=250, bd=2, relief='groove', bg=self.get_bg('gray'),\n text=\"Click on a column name then select the corresponding plot axis or error bar\")\n instructions.pack(side='top', padx=20, pady=10, ipadx=20, ipady=5)\n\n middle_box = Frame(right_side_box, bg=self.get_bg('gray'))\n middle_box.pack(side='top', padx=5)\n\n axis_options_box = Frame(middle_box, bg=self.get_bg('gray'))\n axis_options_box.pack(side='top')\n\n axis = Label(axis_options_box, bg=self.get_bg('gray'), text='Axis')\n axis.grid(row=0, column=0)\n\n column = Label(axis_options_box, bg=self.get_bg('gray'), text='Column name to plot')\n column.grid(row=0, column=1)\n\n # Entry and button that allows user to select a field as the data for each axis\n for i, axis_type in enumerate(['X', 'Y', 'X Error', 'Y Error']):\n\n choose_field = functools.partial(self._choose_field, i)\n\n button = Button(axis_options_box, text=axis_type, width=6, font=self.get_font(size=9),\n bg=self.get_bg('gray'), highlightbackground=self.get_bg('gray'),\n command=choose_field)\n button.grid(row=i+1, column=0)\n\n entry = Entry(axis_options_box, width=field_name_width, state='readonly', relief='sunken', bd=1,\n readonlybackground='white', highlightthickness=0, takefocus=0)\n entry.grid(row=i+1, column=1, padx=(5, 0), ipady=3)\n\n self._axis_entries[i] = entry\n\n # Determine whether structure contains masked data. For such data, scatter plots are usually\n # better than line plots.\n has_masked = any([np.ma.is_masked(field) for field in self._structure.as_masked().fields])\n self._lines.set(not has_masked)\n self._points.set(has_masked)\n self._mask_special.set(True)\n\n # Lines and Points checkbuttons\n checkbutton_box = Frame(middle_box)\n checkbutton_box.pack(side='top', pady=(10, 0))\n\n line_plot = Checkbutton(checkbutton_box, text='Lines', bg=self.get_bg('gray'),\n variable=self._lines, onvalue=True, offvalue=False)\n line_plot.pack(side='left')\n\n point_plot = Checkbutton(checkbutton_box, text='Points', bg=self.get_bg('gray'),\n variable=self._points, onvalue=True, offvalue=False)\n point_plot.pack(side='left')\n\n if has_masked:\n mask_special = Checkbutton(middle_box, text='Ignore special constants and nulls',\n bg=self.get_bg('gray'), variable=self._mask_special,\n onvalue=True, offvalue=False)\n mask_special.pack(side='top')\n\n # add_plot = Checkbutton(middle_box, text='Add curve to the current graph', bg=self.get_bg('gray'))\n # add_plot.pack(side='top')\n\n # Plot, Clear and Close buttons\n bottom_box = Frame(right_side_box, relief='groove', bd=2, bg=self.get_bg('gray'))\n bottom_box.pack(side='bottom', fill='x', padx=10, pady=(5, 2))\n\n buttons_box = Frame(bottom_box, bg=self.get_bg('gray'))\n buttons_box.pack()\n bottom_buttons_params = {'width': 5, 'font': self.get_font(size=10),\n 'bg': self.get_bg('gray'), 'highlightbackground': self.get_bg('gray')}\n\n plot = Button(buttons_box, text='Plot', command=self._plot, **bottom_buttons_params)\n plot.grid(row=0, column=0, padx=5)\n\n clear = Button(buttons_box, text='Clear', command=self._clear, **bottom_buttons_params)\n clear.grid(row=0, column=1, padx=5)\n\n close = Button(buttons_box, text='Close', command=self.close, **bottom_buttons_params)\n close.grid(row=0, column=2, padx=5)\n\n # Plot the selected data, and close this window\n def _plot(self):\n\n # Do nothing if no axes to plot are selected\n if None in self._axis_selections[0:2]:\n return\n\n # Ensure at least one of Lines or Points is checked, otherwise default to Lines\n line_plot = self._lines.get()\n point_plot = self._points.get()\n mask_special = self._mask_special.get()\n\n if (not line_plot) and (not point_plot):\n line_plot = True\n\n # Plot selected data\n plot_window = PlotViewWindow(self._viewer)\n plot_window.load_table(self._structure,\n self._axis_selections,\n lines=line_plot,\n points=point_plot,\n mask_special=mask_special)\n\n self.close()\n\n # Choose a field for a given axis (X, Y, X_Err, Y_err), where the axis is specified as an index\n def _choose_field(self, axis_index):\n\n # Do nothing if no field name is selected\n if len(self._field_listbox.curselection()) == 0:\n return\n\n # Do nothing for disabled fields\n listbox_index = self._field_listbox.index('active')\n\n if listbox_index in self._disabled_indexes:\n return\n\n # Add field name to axis' entry for display\n axis_entry = self._axis_entries[axis_index]\n\n axis_entry.config(state='normal')\n axis_entry.delete(0, 'end')\n axis_entry.insert(0, self._field_listbox.get('active').strip())\n axis_entry.config(state='readonly')\n\n # Adjust index to account for RowNumber not actually existing as a field\n if listbox_index == 0:\n listbox_index = 'row'\n\n else:\n listbox_index -= 1\n\n # Select field for the given axis\n self._axis_selections[axis_index] = listbox_index\n\n # Clears all field selections\n def _clear(self):\n\n self._axis_selections = [None, None, None, None]\n\n for axis_entry in self._axis_entries:\n\n axis_entry.config(state='normal')\n axis_entry.delete(0, 'end')\n axis_entry.config(state='readonly')\n\n def close(self):\n\n self._structure = None\n super(PlotColumnsWindow, self).close()\n\n\nclass _Series(object):\n \"\"\" Helper class containing data about the series being displayed \"\"\"\n\n def __init__(self, table_structure, axis_selections):\n\n self.structure = table_structure\n self.axis_selections = axis_selections\n\n self.plot_line = None\n self.error_caps = None\n self.error_lines = None\n\n def add_plot(self, plot_line, error_caps, error_lines):\n\n # MPL Line2D that is shown on the plot as line and/or points\n self.plot_line = plot_line\n\n # List of MPL Line2Ds that are the caps of error bars\n self.error_caps = {\n 'vertical': [cap for cap in error_caps if cap.get_marker() == '_'],\n 'horizontal': [cap for cap in error_caps if cap.get_marker() == '|']\n }\n\n # MPL LineCollection that are the lines of error bars. (This is currently MPL implementation dependent\n # in that it relies on the order error lines are added in MPL's `errorbar` call. There is likely\n # a more complicated method of using error_lines[0].get_paths().vertices to produce an implementation\n # independent result; however care would need to be taken for cases where the error bars are extremely\n # small.)\n self.error_lines = {\n 'vertical': error_lines[-1] if (self.axis_selections[3] is not None) else None,\n 'horizontal': error_lines[0] if (self.axis_selections[2] is not None) else None\n }\n\n # 'vertical': next((col for col in error_lines\n # if col.get_paths()[0].vertices[0][0] == col.get_paths()[0].vertices[1][0]), None),\n # 'horizontal': next((col for col in error_lines\n # if col.get_paths()[0].vertices[0][1] == col.get_paths()[0].vertices[1][1]), None),\n\n # Obtains the data for the series and the given axis. Valid options for axis are x|y|x_err|y_err.\n def data(self, axis, masked=None):\n\n axis_selection = self._axis_to_axis_selection(axis)\n\n # Select nothing if there is no axis specified\n if axis_selection is None:\n data = None\n\n # Select the RowNumber axis\n elif axis_selection == 'row':\n\n num_rows = len(self.structure.fields[0])\n data = np.arange(num_rows)\n\n # Select an axis from the fields in the table\n else:\n\n data = self.structure.fields[axis_selection]\n\n if data.meta_data.data_type().issubtype('datetime'):\n data = data_type_convert_dates(data)\n\n # \"Mask\" data if requested\n if masked and (data is not None):\n\n mask = self._get_normalized_mask()\n if mask is not np.ma.nomask:\n data = data[np.invert(mask)]\n\n return data\n\n # Obtains the data for the series and the given axis. Valid options for axis are x|y|x_err|y_err.\n def meta_data(self, axis):\n\n axis_selection = self._axis_to_axis_selection(axis)\n\n if axis_selection is None:\n meta_data = None\n\n elif axis_selection == 'row':\n meta_data = Meta_Field({'name': 'Row Number',\n 'data_type': 'object'})\n\n else:\n\n meta_data = self.data(axis, masked=False).meta_data\n\n return meta_data\n\n # Obtains a label for the series and the given axis. Valid options for axis are x|y|x_err|y_err.\n def label(self, axis):\n\n name = self.meta_data(axis)['name']\n unit = self.meta_data(axis).get('unit', None)\n\n label = name\n\n if unit is not None:\n label = '{0} ({1})'.format(label, unit)\n\n return label\n\n # Transforms axis from x|y|x_err|y_err to an axis selection\n # (either index of a table field, the string 'row' or None)\n def _axis_to_axis_selection(self, axis):\n\n axis_idx = {'x': 0,\n 'y': 1,\n 'x_err': 2,\n 'y_err': 3,\n }[axis]\n\n axis_selection = self.axis_selections[axis_idx]\n\n return axis_selection\n\n # Obtains a mask which is set to True in any place where any of the axis selections are masked out\n def _get_normalized_mask(self):\n\n all_fields = self.structure.as_masked().fields\n fields = [all_fields[axis] for axis in self.axis_selections\n if isinstance(axis, int)]\n\n mask = np.ma.nomask\n\n for field in fields:\n mask = np.ma.mask_or(field.mask, mask, copy=False, shrink=True)\n\n return mask\n\n\ndef open_plot(viewer, table_structure, axis_selections, lines=True, points=False, mask_special=False):\n \"\"\" Open a plot view for fields from a TableStructure.\n\n Parameters\n ----------\n viewer : PDS4Viewer\n An instance of PDS4Viewer.\n table_structure : TableStructure\n Table structure from which the fields to plot are taken.\n axis_selections : list[int str, unicode or None]\n A four valued list, which specifies the table fields to use for x,y,x_err,y_err by indicating their\n field index in *table_structure*. To plot against row number, the string 'row' may be used instead\n of an index. x_err and/or y_err may use None to skip error bars.\n lines : bool, optional\n When True, lines will connect individual data points. Defaults to True.\n points : bool, optional\n When True, markers will be shown on individual data points. Defaults to False.\n mask_special : bool, optional\n When True, special constants and null values are removed from the data to be plotted.\n Defaults to False.\n\n Returns\n -------\n PlotViewWindow\n The window instance for plot view.\n \"\"\"\n\n plot_window = PlotViewWindow(viewer)\n plot_window.load_table(table_structure, axis_selections,\n lines=lines, points=points, mask_special=mask_special)\n\n return plot_window\n\n\ndef open_plot_column_select(viewer, table_structure):\n \"\"\" Open a window that allows selection of fields to plot from a TableStructure.\n\n Parameters\n ----------\n viewer : PDS4Viewer\n An instance of PDS4Viewer.\n table_structure : TableStructure\n Table structure from which the fields available to plot are taken.\n\n Returns\n -------\n PlotColumnsWindow\n The window instance for the plot column selection window.\n \"\"\"\n\n plot_columns_window = PlotColumnsWindow(viewer, table_structure)\n\n return plot_columns_window\n" ]
[ [ "matplotlib.rcParams.get", "numpy.invert", "matplotlib.figure.Figure", "numpy.arange", "numpy.issubdtype", "numpy.ma.mask_or", "matplotlib.dates.AutoDateLocator", "matplotlib.lines._get_dash_pattern", "numpy.ma.is_masked" ] ]
KeithBrodie/RANSAC
[ "c77b2103a6439138ccda7641d999af0963cff669" ]
[ "ransac_core.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\n RANSAC_Core Class Definition\n \n \n Copyright (c) Keith Brodie 2021\n \n MIT License\n\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nclass RANSAC_Core(object):\n \"\"\"RANSAC Core Object defining fitted function.\n \n This is a template, it cannot be used directly. A derived class must\n overwrite these methods:\n \n dof() - Return the number of degrees of freedom for the fit function\n \n fit() - Perform the fit and return the model from the arrays of\n sampled x,y\n \n predict()\n \n The derived class defines the function we're using to model the data\n and, along with the limit, define outliers.\n \n These methods can be used as-is once the above methods are \n over-written.\n \n __init__ : Instantiate derived class with (x,y,limit)\n fitSamples()\n classify()\n iteration()\n run()\n plot()\n \n \"\"\"\n def __init__(self,x:np.ndarray,y:np.ndarray,limit:float):\n \"\"\"Initialize the RANSAC object with the data points and the consensus limit.\n \n This data does not change with an iteration of the RANSAC algorithm.\n \n \"\"\"\n self.x = x\n self.y = y\n self.limit = limit\n self.n = len(x)\n self.bestResult = 0.\n assert(self.n == len(y))\n \n #\n ########################################################################\n #\n # Overwrite these methods in the derived class\n #\n def dof(self)->int:\n \"\"\"Returns the number of parameters to be used in the model.\n \n Overwrite this method in the derived class.\n \"\"\"\n return 0\n \n def fit(self,x:np.ndarray,y:np.ndarray)->np.ndarray:\n \"\"\"Return the model parameters from fitting the x,y samples.\n \n x, y are of length self.dof(). The expected return\n array is also of length self.dof().\n \n Overwrite this routine with the fit method for the particular\n model on which you are using RANSAC.\n \"\"\"\n return np.ndarray([])\n \n def predict(self,param:np.ndarray,x:np.ndarray)->np.ndarray:\n \"\"\"Return the modeled y values for x using param.\n \n Overwrite this routine with the predict method for the \n particular model in use.\n \n The output array contains a prediction for each x.\n \"\"\"\n return np.zeros_like(self.x)\n \n #######################################################################\n #\n def fitSamples(self):\n #\n # Select the points randomly, insuring we have unique 'x' values\n # in the samples\n #\n while True:\n pts = np.random.choice(len(self.x),self.dof(),replace=False)\n if len(np.unique(self.x[pts])) == self.dof():\n break\n \n self.pts = pts\n \n self.param = self.fit(self.x[self.pts],self.y[self.pts])\n \n def classify(self):\n \"\"\"Classify data points as in or out of Consensus by checking limit.\"\"\"\n \n self.yModel = self.predict(self.param,self.x)\n \n self.consensus = np.abs(self.y - self.yModel) < self.limit\n \n def iteration(self):\n \n self.fitSamples()\n self.classify()\n \n return self.consensus.sum() / self.n\n \n def run(self,success:float=0.95,maxIter:int=500):\n \n for i in range(maxIter):\n \n result = self.iteration()\n \n if result > self.bestResult:\n self.bestResult = result\n self.bestParam = self.param\n self.bestPts = self.pts\n \n if (result >= success):\n break\n \n if self.bestResult > result:\n \n self.param = self.bestParam\n self.pts = self.bestPts\n self.classify()\n result = self.consensus.sum() / self.n\n \n return result\n \n def plot(self,title=\"RANSAC Result\",filename=None):\n \n fig, ax = plt.subplots(figsize=(15,10))\n plt.plot(self.x,self.yModel,label='Model')\n plt.plot(self.x,self.yModel+self.limit,'b',label='Boundary')\n plt.plot(self.x,self.yModel-self.limit,'b')\n\n plt.plot(self.x[self.consensus],self.y[self.consensus],'g.',label='Consensus')\n plt.plot(self.x[~self.consensus],self.y[~self.consensus],'r.',label='Outlier')\n\n # Mark the samples used in the fit\n for i in range(self.dof()):\n plt.plot(self.x[self.pts[i]],self.y[self.pts[i]],'r*')\n \n # Write some results on the plot\n \n plt.text(0.5, 0.95, \n 'n: {} In: {} Out: {} Frac: {:.3f}'.format(self.n,\n self.consensus.sum(),\n self.n - self.consensus.sum(),\n self.consensus.sum() / self.n),\n ha='center',\n va='center',\n transform=ax.transAxes)\n\n plt.text(0.5, 0.925, \n 'Param: {}'.format(self.param),\n ha='center',\n va='center',\n transform=ax.transAxes)\n\n plt.grid()\n plt.legend()\n plt.title(title)\n \n if filename is None:\n plt.show()\n else:\n plt.savefig(filename)\n \n plt.show()\n \n plt.close()\n \nclass LinearRANSAC(RANSAC_Core):\n \n def dof(self):\n \"\"\"Return degrees-of-freedom for linear model.\"\"\"\n return 2\n \n def fit(self,x:np.ndarray,y:np.ndarray)->np.ndarray:\n \"\"\"Fit linear model to two samples.\"\"\"\n a = (y[1] - y[0]) / (x[1] - x[0])\n b = y[0] - x[0] * a\n return np.array([a,b])\n\n def predict(self,param:np.ndarray,x:np.ndarray)->np.ndarray:\n \"\"\"Compute prediction from model.\"\"\"\n return x * param[0] + param[1]\n \n\nclass QuadraticRANSAC(RANSAC_Core):\n \n def dof(self):\n \"\"\"Return degrees-of-freedom for linear model.\"\"\"\n return 3\n \n def fit(self,x:np.ndarray,y:np.ndarray)->np.ndarray:\n \"\"\"Quadratic fit to three samples.\"\"\"\n gamma = - (x[1] - x[0]) / (x[2] - x[0])\n a = (y[1] - y[0] + gamma * (y[2] - y[0])) / ((x[1]**2 - x[0]**2) + gamma * (x[2]**2 - x[0]**2))\n b = ( (y[2] - y[0]) - a * (x[2]**2 - x[0]**2) ) / (x[2] - x[0])\n c = y[0] - a * x[0]**2 - b * x[0]\n return np.array([a,b,c])\n\n def predict(self,param:np.ndarray,x:np.ndarray)->np.ndarray:\n \"\"\"Compute prediction from model.\"\"\"\n return x * x * param[0] + x * param[1] + param[2]\n \nif __name__ == '__main__':\n \n n = 100\n \n x = 20 + np.arange(n)\n \n y = 0.0068 * x * x - 2.56 * x + 1.3 + np.random.randn(n)\n \n lRANSAC = LinearRANSAC(x, y, 3)\n \n qRANSAC = QuadraticRANSAC(x, y, 3)\n \n lRANSAC.run()\n \n lRANSAC.plot('Linear RANSAC Test','Linear.png')\n \n qRANSAC.run()\n \n qRANSAC.plot('Quadratic RANSAC Test','Quadratic.png')\n \n \n " ]
[ [ "matplotlib.pyplot.legend", "numpy.abs", "matplotlib.pyplot.title", "numpy.unique", "numpy.arange", "matplotlib.pyplot.subplots", "numpy.ndarray", "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "numpy.zeros_like", "numpy.random.randn", "matplotlib.pyplot.grid", "matplotlib.pyplot.close", "numpy.array", "matplotlib.pyplot.show" ] ]
Ellawin/nevergrad
[ "d4ea61d0fff9292045f72714b26972ea1e48bd88", "850418e9e4d00ee2e4fc12d8fc7a6981b0152641" ]
[ "nevergrad/functions/iohprofiler/test_core.py", "nevergrad/optimization/test_sequences.py" ]
[ "import pytest\nimport numpy as np\nfrom . import core\n\n\[email protected](\"fid\", range(1, 24)) # type: ignore\ndef test_PBO(fid: int) -> None:\n func = core.PBOFunction(fid, 0, 16)\n x = func.parametrization.sample()\n value = func(x.value)\n assert isinstance(value, float), \"All output of the iohprofiler-functions should be float\"\n assert np.isfinite(value)\n\n\[email protected](\"instrumentation\", [\"Softmax\", \"Ordered\"])\ndef test_PBO_parameterization(instrumentation) -> None:\n func = core.PBOFunction(1, 0, 16, instrumentation=instrumentation)\n x = func.parametrization.sample()\n value = func(x.value)\n assert isinstance(value, float), \"All output of the iohprofiler-functions should be float\"\n assert np.isfinite(value)\n\n\ndef test_W_model() -> None:\n func = core.WModelFunction()\n x = func.parametrization.sample()\n func2 = core.PBOFunction(1, 0, 16)\n assert func(x.value) == func2(x.value), \"W-model with default setting should equal base_function\"\n func = core.WModelFunction(base_function=\"LeadingOnes\")\n x = func.parametrization.sample()\n func2 = core.PBOFunction(2, 0, 16)\n assert func(x.value) == func2(x.value), \"W-model with default setting should equal base_function\"\n", "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\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\nimport typing as tp\nimport numpy as np\nfrom ..common import testing\nfrom . import sequences\nfrom .sequences import samplers\n\n\ndef test_get_first_primes() -> None:\n # check first 10\n first_10 = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n for k in range(11):\n np.testing.assert_array_equal(sequences._get_first_primes(k), first_10[:k])\n # generate a big number of them\n num = np.random.randint(1000, 1000000)\n output = sequences._get_first_primes(num)\n # verify the last value and one random value\n for value in [np.random.choice(output), output[-1]]:\n for k in range(3, 1 + int(np.sqrt(value)), 2):\n assert value % k, f\"Value {value} obtained with num={num} can be divided by {k}\"\n\[email protected](**{name: (sampler,) for name, sampler in samplers.items()})\ndef test_samplers(sampler_cls: tp.Type[sequences.Sampler]) -> None:\n sampler = sampler_cls(144, 4)\n np.testing.assert_equal(sampler.index, 0)\n output = sampler()\n np.testing.assert_equal(sampler.index, 1)\n np.testing.assert_equal(len(output), 144)\n assert min(output) > 0\n assert max(output) < 1\n\n\ndef test_sampler_draw() -> None:\n sampler = sequences.RandomSampler(5, 4)\n sampler.draw()\n\n\[email protected](\n # lhs=(\"LHSSampler\", [0.069, 0.106, 0.384], [0.282, 0.857, 0.688]), # previous: for the record\n lhs=(\"LHSSampler\", [0.931, 0.422, 0.391], [0.428, 0.625, 0.797]),\n halton=(\"HaltonSampler\", [0.5, 0.333, 0.2], [0.25, 0.667, 0.4]),\n)\ndef test_sampler_values(name: str, seq1: tp.List[float], seq2: tp.List[float]) -> None:\n budget = 4\n np.random.seed(12)\n sampler = samplers[name](3, budget)\n samples = list(sampler)\n for k, expected in enumerate([seq1, seq2]):\n np.testing.assert_almost_equal(samples[k], expected, decimal=3)\n np.testing.assert_raises(AssertionError, sampler) # budget is over\n sampler.reinitialize()\n samples2 = list(sampler)\n testing.printed_assert_equal(samples2, samples)\n\n\ndef test_permutation_generator() -> None:\n np.random.seed(12)\n gen = sequences.HaltonPermutationGenerator(5, scrambling=True)\n value1 = list(gen.get_permutations_generator())\n value2 = list(gen.get_permutations_generator())\n gen = sequences.HaltonPermutationGenerator(5, scrambling=True)\n value3 = list(gen.get_permutations_generator())\n testing.printed_assert_equal(value1, value2)\n # testing.printed_assert_equal(value1[:3], [[0, 1], [0, 2, 1], [0, 4, 3, 2, 1]]) # previous: for the record\n testing.printed_assert_equal(value1[:3], [[0, 1], [0, 1, 2], [0, 2, 3, 1, 4]])\n np.testing.assert_raises(AssertionError, testing.printed_assert_equal, value3, value2)\n #\n gen = sequences.HaltonPermutationGenerator(5, scrambling=False)\n value = list(gen.get_permutations_generator())\n testing.printed_assert_equal(value, [np.arange(p) for p in [2, 3, 5, 7, 11]])\n\n\ndef test_rescaler_on_hammersley() -> None:\n np.random.seed(12)\n sampler = sequences.HammersleySampler(dimension=3, budget=4, scrambling=True)\n samples = list(sampler)\n sampler.reinitialize()\n samples2 = list(sampler)\n sampler.reinitialize()\n np.testing.assert_array_equal(samples, samples2, \"Not repeatable\") # test repeatability of hammersley first\n rescaler = sequences.Rescaler(sampler)\n sampler.reinitialize()\n rescaled_samples = [rescaler.apply(x) for x in sampler]\n expected = [[1e-15, 0.600, 0.667], [0.333, 0.200, 0.167], [0.667, 1.0, 1e-15], [1.0, 1e-15, 1.0]]\n np.testing.assert_almost_equal(rescaled_samples, expected, decimal=3)\n" ]
[ [ "numpy.isfinite" ], [ "numpy.testing.assert_equal", "numpy.sqrt", "numpy.random.seed", "numpy.random.choice", "numpy.arange", "numpy.testing.assert_array_equal", "numpy.testing.assert_almost_equal", "numpy.testing.assert_raises", "numpy.random.randint" ] ]
unkcpz/aiida-quantumespresso
[ "fbac0993bb8b6cdeba85717453debcf0ab062b5a" ]
[ "aiida_quantumespresso/parsers/dos.py" ]
[ "# -*- coding: utf-8 -*-\nimport numpy as np\nfrom aiida.parsers.parser import Parser\nfrom aiida.orm.data.array.xy import XyData\nfrom aiida.orm.data.parameter import ParameterData\nfrom aiida.common.exceptions import InvalidOperation\nfrom aiida.common.datastructures import calc_states\nfrom aiida_quantumespresso.parsers import QEOutputParsingError\nfrom aiida_quantumespresso.parsers import parse_raw_out_basic\nfrom aiida_quantumespresso.calculations.dos import DosCalculation\n\nclass DosParser(Parser):\n \"\"\"\n This class is the implementation of the Parser class for Dos.\n \"\"\"\n _dos_name = 'output_dos'\n _units_name = 'output_units'\n\n def __init__(self, calculation):\n \"\"\"\n Initialize the instance of DosParser\n \"\"\"\n # check for valid input\n if not isinstance(calculation, DosCalculation):\n raise QEOutputParsingError(\"Input calc must be a DosCalculation\")\n\n self._calc = calculation\n\n super(DosParser, self).__init__(calculation)\n\n def get_linkname_dos(self):\n \"\"\"\n Returns the name of the link of dos\n \"\"\"\n return self._dos_name\n\n def get_linkname_units(self):\n \"\"\"\n Returns the name of the link of units\n \"\"\"\n return self._units_name\n\n def parse_with_retrieved(self, retrieved):\n \"\"\"\n Parses the datafolder, stores results.\n Retrieves dos output, and some basic information from the\n out_file, such as warnings and wall_time\n \"\"\"\n\n # suppose at the start that the job is successful\n successful = True\n new_nodes_list = []\n\n try:\n out_folder = self._calc.get_retrieved_node()\n except KeyError:\n self.logger.error(\"No retrieved folder found\")\n return successful, new_nodes_list\n\n # Read standard out\n try:\n filpath = out_folder.get_abs_path(self._calc._OUTPUT_FILE_NAME)\n with open(filpath, 'r') as fil:\n out_file = fil.readlines()\n except OSError:\n self.logger.error(\"Standard output file could not be found.\")\n successful = False\n return successful, new_nodes_list\n\n successful = False\n for i in range(len(out_file)):\n line = out_file[-i]\n if \"JOB DONE\" in line:\n successful = True\n break\n if not successful:\n self.logger.error(\"Computation did not finish properly\")\n return successful, new_nodes_list\n\n # check that the dos file is present, if it is, read it\n try:\n dos_path = out_folder.get_abs_path(self._calc._DOS_FILENAME)\n with open(dos_path, 'r') as fil:\n dos_file = fil.readlines()\n except OSError:\n successful = False\n self.logger.error(\"Dos output file could not found\")\n return successful, new_nodes_list\n\n # end of initial checks\n\n array_names = [[], []]\n array_units = [[], []]\n array_names[0] = ['dos_energy', 'dos',\n 'integrated_dos'] # When spin is not displayed\n array_names[1] = ['dos_energy', 'dos_spin_up', 'dos_spin_down',\n 'integrated_dos'] # When spin is displayed\n array_units[0] = ['eV', 'states/eV',\n 'states'] # When spin is not displayed\n array_units[1] = ['eV', 'states/eV', 'states/eV',\n 'states'] # When spin is displayed\n\n # grabs parsed data from aiida.dos\n array_data, spin = parse_raw_dos(dos_file, array_names, array_units)\n \n energy_units = 'eV'\n dos_units = 'states/eV'\n int_dos_units = 'states' \n xy_data = XyData()\n xy_data.set_x(array_data[\"dos_energy\"],\"dos_energy\", energy_units)\n y_arrays = []\n y_names = []\n y_units = []\n y_arrays += [array_data[\"integrated_dos\"]]\n y_names += [\"integrated_dos\"]\n y_units += [\"states\"]\n if spin:\n y_arrays += [array_data[\"dos_spin_up\"]]\n y_arrays += [array_data[\"dos_spin_down\"]]\n y_names += [\"dos_spin_up\"]\n y_names += [\"dos_spin_down\"]\n y_units += [\"states/eV\"]*2\n else:\n y_arrays += [array_data[\"dos\"]]\n y_names += [\"dos\"]\n y_units += [\"states/eV\"]\n xy_data.set_y(y_arrays,y_names,y_units)\n\n # grabs the parsed data from aiida.out\n parsed_data = parse_raw_out_basic(out_file, \"DOS\")\n output_params = ParameterData(dict=parsed_data)\n # Adds warnings\n for message in parsed_data['warnings']:\n self.logger.error(message)\n # Create New Nodes List\n new_nodes_list = [(self.get_linkname_outparams(), output_params),\n (self.get_linkname_dos(), xy_data)]\n return successful,new_nodes_list\n\n\n\ndef parse_raw_dos(dos_file, array_names, array_units):\n \"\"\"\n This function takes as input the dos_file as a list of filelines along\n with information on how to give labels and units to the parsed data\n \n :param dos_file: dos file lines in the form of a list\n :type dos_file: list\n :param array_names: list of all array names, note that array_names[0]\n is for the case with non spin-polarized calculations\n and array_names[1] is for the case with spin-polarized\n calculation\n :type array_names: list\n :param array_units: list of all array units, note that array_units[0] is\n for the case with non spin-polarized calculations and\n array_units[1] is for the case with spin-polarized\n calculation\n :type array_units: list\n \n :return array_data: narray, a dictionary for ArrayData type, which contains\n all parsed dos output along with labels and units\n :return spin: boolean, indicates whether the parsed results are spin\n polarized \n \"\"\"\n\n dos_header = dos_file[0]\n try:\n dos_data = np.genfromtxt(dos_file)\n except ValueError:\n raise QEOutputParsingError('dosfile could not be loaded '\n ' using genfromtxt')\n if len(dos_data) == 0:\n raise QEOutputParsingError(\"Dos file is empty.\")\n if np.isnan(dos_data).any():\n raise QEOutputParsingError(\"Dos file contains non-numeric elements.\")\n\n # Checks the number of columns, essentially to see whether spin was used\n if len(dos_data[0]) == 3:\n # spin is not used\n array_names = array_names[0]\n array_units = array_units[0]\n spin = False\n elif len(dos_data[0]) == 4:\n # spin is used\n array_names = array_names[1]\n array_units = array_units[1]\n spin = True \n else:\n raise QEOutputParsingError(\"Dos file in format that the parser is not \"\n \"designed to handle.\")\n\n i = 0\n array_data = {}\n array_data['header'] = np.array(dos_header)\n while i < len(array_names):\n array_data[array_names[i]] = dos_data[:, i]\n array_data[array_names[i]+'_units'] = np.array(array_units[i])\n i += 1\n return array_data,spin\n" ]
[ [ "numpy.isnan", "numpy.array", "numpy.genfromtxt" ] ]
santiagoinfantinom/pandapower
[ "b0873a161f2bec73fce2982d55040e6afc733931" ]
[ "pandapower/test/api/test_create.py" ]
[ "# -*- coding: utf-8 -*-\n\n# Copyright (c) 2016-2019 by University of Kassel and Fraunhofer Institute for Energy Economics\n# and Energy System Technology (IEE), Kassel. All rights reserved.\n\n\nimport numpy as np\nimport pandapower as pp\nimport pytest\n\nimport pandas as pd\npd.set_option('display.max_rows', 500)\npd.set_option('display.max_columns', 500)\npd.set_option('display.width', 1000)\n\ndef test_convenience_create_functions():\n net = pp.create_empty_network()\n b1 = pp.create_bus(net, 110.)\n b2 = pp.create_bus(net, 110.)\n b3 = pp.create_bus(net, 20)\n pp.create_ext_grid(net, b1)\n pp.create_line_from_parameters(net, b1, b2, length_km=20., r_ohm_per_km=0.0487,\n x_ohm_per_km=0.1382301, c_nf_per_km=160., max_i_ka=0.664)\n\n l0 = pp.create_load_from_cosphi(net, b2, 10, 0.95, \"ind\", name=\"load\")\n pp.runpp(net, init=\"flat\")\n assert net.load.p_mw.at[l0] == 9.5\n assert net.load.q_mvar.at[l0] > 0\n assert np.sqrt(net.load.p_mw.at[l0] ** 2 + net.load.q_mvar.at[l0] ** 2) == 10\n assert np.isclose(net.res_bus.vm_pu.at[b2], 0.99990833838)\n assert net.load.name.at[l0] == \"load\"\n\n sh0 = pp.create_shunt_as_capacitor(net, b2, 10, loss_factor=0.01, name=\"shunt\")\n pp.runpp(net, init=\"flat\")\n assert np.isclose(net.res_shunt.q_mvar.at[sh0], -10.043934174)\n assert np.isclose(net.res_shunt.p_mw.at[sh0], 0.10043933665)\n assert np.isclose(net.res_bus.vm_pu.at[b2], 1.0021942964)\n assert net.shunt.name.at[sh0] == \"shunt\"\n\n sg0 = pp.create_sgen_from_cosphi(net, b2, 5, 0.95, \"cap\", name=\"sgen\")\n pp.runpp(net, init=\"flat\")\n assert np.sqrt(net.sgen.p_mw.at[sg0] ** 2 + net.sgen.q_mvar.at[sg0] ** 2) == 5\n assert net.sgen.p_mw.at[sg0] == 4.75\n assert net.sgen.q_mvar.at[sg0] > 0\n assert np.isclose(net.res_bus.vm_pu.at[b2], 1.0029376578)\n assert net.sgen.name.at[sg0] == \"sgen\"\n\n tol = 1e-6\n sind = pp.create_series_reactor_as_impedance(net, b1, b2, r_ohm=100, x_ohm=200, sn_mva=100)\n assert net.impedance.at[sind, 'rft_pu'] - 8.264463e-04 < tol\n assert net.impedance.at[sind, 'xft_pu'] - 0.001653 < tol\n\n tid = pp.create_transformer_from_parameters(net, hv_bus=b2, lv_bus=b3, sn_mva=0.1, vn_hv_kv=110,\n vn_lv_kv=20, vkr_percent=5, vk_percent=20,\n pfe_kw=1, i0_percent=1)\n pp.create_load(net, b3, 0.1)\n assert net.trafo.at[tid, 'df'] == 1\n pp.runpp(net)\n tr_l = net.res_trafo.at[tid, 'loading_percent']\n net.trafo.at[tid, 'df'] = 2\n pp.runpp(net)\n tr_l_2 = net.res_trafo.at[tid, 'loading_percent']\n assert tr_l == tr_l_2 * 2\n net.trafo.at[tid, 'df'] = 0\n with pytest.raises(UserWarning):\n pp.runpp(net)\n\n\n\ndef test_nonexistent_bus():\n from functools import partial\n net = pp.create_empty_network()\n create_functions = [partial(pp.create_load, net=net, p_mw=0, q_mvar=0, bus=0, index=0),\n partial(pp.create_sgen, net=net, p_mw=0, q_mvar=0, bus=0, index=0),\n partial(pp.create_dcline, net, from_bus=0, to_bus=1, p_mw=0.1,\n loss_percent=0, loss_mw=0.01, vm_from_pu=1., vm_to_pu=1., index=0),\n partial(pp.create_gen, net=net, p_mw=0, bus=0, index=0),\n partial(pp.create_ward, net, 0, 0, 0, 0, 0, index=0),\n partial(pp.create_xward, net, 0, 0, 0, 0, 0, 1, 1, 1, index=0),\n partial(pp.create_shunt, net=net, q_mvar=0, bus=0, index=0),\n partial(pp.create_ext_grid, net=net, bus=1, index=0),\n partial(pp.create_line, net=net, from_bus=0, to_bus=1, length_km=1.,\n std_type=\"NAYY 4x50 SE\", index=0),\n partial(pp.create_line_from_parameters, net=net, from_bus=0, to_bus=1,\n length_km=1., r_ohm_per_km=0.1, x_ohm_per_km=0.1, max_i_ka=0.4,\n c_nf_per_km=10, index=1),\n partial(pp.create_transformer, net=net, hv_bus=0, lv_bus=1,\n std_type=\"63 MVA 110/20 kV\", index=0),\n partial(pp.create_transformer3w, net=net, hv_bus=0, lv_bus=1, mv_bus=2,\n std_type=\"63/25/38 MVA 110/20/10 kV\", index=0),\n partial(pp.create_transformer3w_from_parameters, net=net, hv_bus=0,\n lv_bus=1, mv_bus=2, i0_percent=0.89, pfe_kw=3.5,\n vn_hv_kv=110, vn_lv_kv=10, vn_mv_kv=20, sn_hv_mva=63,\n sn_lv_mva=38, sn_mv_mva=25, vk_hv_percent=10.4,\n vk_lv_percent=10.4, vk_mv_percent=10.4, vkr_hv_percent=0.28,\n vkr_lv_percent=0.35, vkr_mv_percent=0.32, index=1),\n partial(pp.create_transformer_from_parameters, net=net, hv_bus=0, lv_bus=1,\n sn_mva=60, vn_hv_kv=20., vn_lv_kv=0.4, vk_percent=10,\n vkr_percent=0.1, pfe_kw=0, i0_percent=0, index=1),\n partial(pp.create_impedance, net=net, from_bus=0, to_bus=1,\n rft_pu=0.1, xft_pu=0.1, sn_mva=0.6, index=0),\n partial(pp.create_switch, net, bus=0, element=1, et=\"b\", index=0)]\n for func in create_functions:\n with pytest.raises(Exception): # exception has to be raised since bus doesn't exist\n func()\n pp.create_bus(net, 0.4)\n pp.create_bus(net, 0.4)\n pp.create_bus(net, 0.4)\n for func in create_functions:\n func() # buses exist, element can be created\n with pytest.raises(Exception): # exception is raised because index already exists\n func()\n\n\ndef test_tap_phase_shifter_default():\n expected_default = False\n net = pp.create_empty_network()\n pp.create_bus(net, 110)\n pp.create_bus(net, 20)\n data = pp.load_std_type(net, \"25 MVA 110/20 kV\", \"trafo\")\n if \"tap_phase_shifter\" in data:\n del data[\"tap_phase_shifter\"]\n pp.create_std_type(net, data, \"without_tap_shifter_info\", \"trafo\")\n pp.create_transformer_from_parameters(net, 0, 1, 25e3, 110, 20, 0.4, 12, 20, 0.07)\n pp.create_transformer(net, 0, 1, \"without_tap_shifter_info\")\n assert (net.trafo.tap_phase_shifter == expected_default).all()\n\n\ndef test_create_line_conductance():\n net = pp.create_empty_network()\n pp.create_bus(net, 20)\n pp.create_bus(net, 20)\n pp.create_std_type(net, {'c_nf_per_km': 210, 'max_i_ka': 0.142, 'q_mm2': 50,\n 'r_ohm_per_km': 0.642, 'type': 'cs', 'x_ohm_per_km': 0.083,\n \"g_us_per_km\": 1}, \"test_conductance\")\n\n l = pp.create_line(net, 0, 1, 1., \"test_conductance\")\n assert net.line.g_us_per_km.at[l] == 1\n\n\ndef test_create_buses():\n net = pp.create_empty_network()\n # standard\n b1 = pp.create_buses(net, 3, 110)\n # with geodata\n b2 = pp.create_buses(net, 3, 110, geodata=(10, 20))\n # with geodata as array\n geodata = np.array([[10, 20], [20, 30], [30, 40]])\n b3 = pp.create_buses(net, 3, 110, geodata=geodata)\n\n assert len(net.bus) == 9\n assert len(net.bus_geodata) == 6\n\n for i in b2:\n assert net.bus_geodata.at[i, 'x'] == 10\n assert net.bus_geodata.at[i, 'y'] == 20\n\n assert (net.bus_geodata.loc[b3, ['x', 'y']].values == geodata).all()\n\n # no way of creating buses with not matching shape\n with pytest.raises(ValueError):\n pp.create_buses(net, 2, 110, geodata=geodata)\n\n\ndef test_create_lines():\n # standard\n net = pp.create_empty_network()\n b1 = pp.create_bus(net, 10)\n b2 = pp.create_bus(net, 10)\n l = pp.create_lines(net, [b1, b1], [b2, b2], 4, std_type=\"48-AL1/8-ST1A 10.0\")\n assert len(net.line) == 2\n assert len(net.line_geodata) == 0\n assert sum(net.line.std_type == \"48-AL1/8-ST1A 10.0\") == 2\n assert len(set(net.line.r_ohm_per_km)) == 1\n\n # with geodata\n net = pp.create_empty_network()\n b1 = pp.create_bus(net, 10)\n b2 = pp.create_bus(net, 10)\n l = pp.create_lines(net, [b1, b1], [b2, b2], [1.5, 3], std_type=\"48-AL1/8-ST1A 10.0\",\n geodata=[[(1,1),(2,2),(3,3)], [(1,1),(1,2)]])\n\n assert len(net.line) == 2\n assert len(net.line_geodata) == 2\n assert net.line_geodata.at[l[0], \"coords\"] == [(1,1),(2,2),(3,3)]\n assert net.line_geodata.at[l[1], \"coords\"] == [(1,1),(1,2)]\n\n # setting params as single value\n net = pp.create_empty_network()\n b1 = pp.create_bus(net, 10)\n b2 = pp.create_bus(net, 10)\n l = pp.create_lines(net, [b1, b1], [b2, b2], length_km=5, df=0.8, in_service=False,\n geodata=[(10, 10), (20, 20)], parallel=1, max_loading_percent=90,\n name=\"test\", std_type=\"48-AL1/8-ST1A 10.0\")\n\n assert len(net.line) == 2\n assert len(net.line_geodata) == 2\n assert net.line.length_km.at[l[0]] == 5\n assert net.line.length_km.at[l[1]] == 5\n assert net.line.at[l[0], \"in_service\"] == False # is actually <class 'numpy.bool_'>\n assert net.line.at[l[1], \"in_service\"] == False # is actually <class 'numpy.bool_'>\n assert net.line_geodata.at[l[0], \"coords\"] == [(10,10), (20,20)]\n assert net.line_geodata.at[l[1], \"coords\"] == [(10,10), (20,20)]\n assert net.line.at[l[0], \"name\"] == \"test\"\n assert net.line.at[l[1], \"name\"] == \"test\"\n assert net.line.at[l[0], \"max_loading_percent\"] == 90\n assert net.line.at[l[1], \"max_loading_percent\"] == 90\n assert net.line.at[l[0], \"parallel\"] == 1\n assert net.line.at[l[1], \"parallel\"] == 1\n\n # setting params as array\n net = pp.create_empty_network()\n b1 = pp.create_bus(net, 10)\n b2 = pp.create_bus(net, 10)\n l = pp.create_lines(net, [b1, b1], [b2, b2], length_km=[1, 5], df=[0.8, 0.7],\n in_service=[True, False],\n geodata=[[(10, 10), (20, 20)], [(100, 10), (200, 20)]], parallel=[2, 1],\n max_loading_percent=[80, 90], name=[\"test1\", \"test2\"],\n std_type=\"48-AL1/8-ST1A 10.0\")\n\n assert len(net.line) == 2\n assert len(net.line_geodata) == 2\n assert net.line.at[l[0], \"length_km\"] == 1\n assert net.line.at[l[1], \"length_km\"] == 5\n assert net.line.at[l[0], \"in_service\"] == True # is actually <class 'numpy.bool_'>\n assert net.line.at[l[1], \"in_service\"] == False # is actually <class 'numpy.bool_'>\n assert net.line_geodata.at[l[0], \"coords\"] == [(10,10), (20,20)]\n assert net.line_geodata.at[l[1], \"coords\"] == [(100,10), (200,20)]\n assert net.line.at[l[0], \"name\"] == \"test1\"\n assert net.line.at[l[1], \"name\"] == \"test2\"\n assert net.line.at[l[0], \"max_loading_percent\"] == 80\n assert net.line.at[l[1], \"max_loading_percent\"] == 90\n assert net.line.at[l[0], \"parallel\"] == 2\n assert net.line.at[l[1], \"parallel\"] == 1\n\n\ndef test_create_line_alpha_temperature():\n net=pp.create_empty_network()\n b = pp.create_buses(net, 5, 110)\n\n l1=pp.create_line(net,0,1, 10, \"48-AL1/8-ST1A 10.0\")\n l2=pp.create_line(net,1,2, 10, \"48-AL1/8-ST1A 10.0\", alpha=4.03e-3, temperature_degree_celsius=80)\n l3=pp.create_line(net,2,3, 10, \"48-AL1/8-ST1A 10.0\")\n l4=pp.create_line_from_parameters(net, 3,4,10, 1,1,1,100)\n l5=pp.create_line_from_parameters(net, 3,4,10, 1,1,1,100, alpha=4.03e-3)\n\n assert 'alpha' in net.line.columns\n assert all(net.line.loc[[l2,l3,l5], 'alpha'] == 4.03e-3)\n assert all(net.line.loc[[l1,l4], 'alpha'].isnull())\n assert net.line.loc[l2, 'temperature_degree_celsius'] == 80\n assert all(net.line.loc[[l1,l3,l4,l5], 'temperature_degree_celsius'].isnull())\n\n\n\nif __name__ == '__main__':\n test_create_lines()\n # pytest.main([\"test_create.py\"])\n" ]
[ [ "pandas.set_option", "numpy.array", "numpy.sqrt", "numpy.isclose" ] ]
bhaskargautam/record-linkage
[ "01eb29f8b7fb4dd1625187232f2dafe47f24cddf" ]
[ "tests/er/test_transe.py" ]
[ "import config\nimport itertools\nimport pandas as pd\nimport numpy as np\nimport recordlinkage\nimport unittest\n\nfrom common import (\n export_embeddings,\n export_false_positives,\n export_false_negatives,\n export_result_prob,\n get_optimal_threshold,\n get_logger,\n InformationRetrievalMetrics,\n log_quality_results,\n sigmoid)\nfrom data.cora import Cora\nfrom data.febrl import FEBRL\nfrom data.census import Census\nfrom ER.model import Graph_ER\nfrom ER.transe import TransE\nfrom scipy import spatial\nfrom scipy.optimize import linear_sum_assignment\nfrom sklearn.metrics import precision_recall_curve\n\nclass TestTransE(unittest.TestCase):\n def _test_transe(self, dataset, params):\n #Load Graph Data\n graph = Graph_ER(dataset)\n model = dataset()\n logger = get_logger('RL.Test.er.TransE.' + str(model))\n\n transe = TransE(graph, dimension=params['dimension'],\n learning_rate=params['learning_rate'],\n margin=params['margin'],\n regularizer_scale=params['regularizer_scale'],\n batchSize=params['batchSize'],\n neg_rate=params['neg_rate'],\n neg_rel_rate=params['neg_rel_rate'])\n loss = transe.train(max_epochs=params['epochs'])\n logger.info(\"Training Complete with loss: %f\", loss)\n\n ent_embeddings = transe.get_ent_embeddings()\n\n result_prob = []\n for i in range(0, len(graph.entity_pairs)):\n distance = abs(spatial.distance.cosine(\n ent_embeddings[graph.entity_pairs[i][0]],\n ent_embeddings[graph.entity_pairs[i][1]]))\n result_prob.append((graph.entity_pairs[i][0], graph.entity_pairs[i][1], distance))\n #logger.info(\"i: %d, distance: %f true_pairs: %s\", i, distance, graph.entity_pairs[i] in true_pairs)\n\n #Write Embeddings to file\n export_embeddings('er', str(model), 'TransE', graph.entity, ent_embeddings)\n export_result_prob(dataset, 'er', str(model), 'TransE', graph.entity, result_prob, graph.true_pairs)\n optimal_threshold, max_fscore = get_optimal_threshold(result_prob, graph.true_pairs)\n\n try:\n params['threshold'] = optimal_threshold\n result = pd.MultiIndex.from_tuples([(e1, e2) for (e1, e2, d) in result_prob if d <= optimal_threshold])\n log_quality_results(logger, result, graph.true_pairs, len(graph.entity_pairs), params)\n export_false_negatives(dataset, 'er', str(model), 'Transe', graph.entity, result_prob,\n graph.true_pairs, result, graph.entity)\n export_false_positives(dataset, 'er', str(model), 'Transe', graph.entity, result_prob,\n graph.true_pairs, result, graph.entity)\n except:\n logger.info(\"Zero Reults\")\n\n #Log MAP, MRR and Hits@K\n ir_metrics = InformationRetrievalMetrics(result_prob, graph.true_pairs)\n precison_at_1 = ir_metrics.log_metrics(logger, params)\n\n transe.close_tf_session()\n return (max_fscore, precison_at_1)\n\n def get_default_params(self):\n return {'learning_rate': 0.1, 'margin': 1, 'dimension': 128, 'epochs': 1000,\n 'regularizer_scale' : 0.1, 'batchSize' : 64, 'neg_rate' : 7, 'neg_rel_rate': 1}\n\n def test_transe_cora(self):\n self._test_transe(Cora, self.get_default_params())\n\n def test_transe_febrl(self):\n self._test_transe(FEBRL, self.get_default_params())\n\n def test_transe_census(self):\n self._test_transe(Census, self.get_default_params())\n\n def _test_grid_search(self, dataset):\n dimension= [128, 256]\n batchSize= [1024, 32]\n learning_rate= [0.1]\n margin= [1]\n regularizer_scale = [0.1]\n epochs = [1000, 5000]\n neg_rel_rate = [7, 12]\n neg_rate = [1, 4]\n count = 0\n max_fscore = 0\n max_prec_at_1 = 0\n\n model = dataset()\n logger = get_logger('RL.Test.er.GridSearch.TransE.' + str(model))\n\n for d, bs, lr, m, reg, e, nr, nrr in \\\n itertools.product(dimension, batchSize, learning_rate, margin, regularizer_scale, epochs, neg_rate, neg_rel_rate):\n params = {'learning_rate': lr, 'margin': m, 'dimension': d, 'epochs': e, 'batchSize' : bs,\n 'regularizer_scale' : reg, 'neg_rate' : nr, 'neg_rel_rate': nrr}\n logger.info(\"\\nTest:%d, PARAMS: %s\", count, str(params))\n count = count + 1\n\n cur_fscore, cur_prec_at_1 = self._test_transe(dataset, params)\n if max_fscore <= cur_fscore:\n max_fscore = cur_fscore\n if max_prec_at_1 <= cur_prec_at_1:\n max_prec_at_1 = cur_prec_at_1\n\n logger.info(\"Ran total %d Tests.\", count)\n logger.info(\"Max Fscore: %f\", max_fscore)\n logger.info(\"Max Mean Precision@1: %f\", max_prec_at_1)\n\n def test_grid_search_cora(self):\n self._test_grid_search(Cora)\n\n def test_grid_search_febrl(self):\n self._test_grid_search(FEBRL)\n\n def test_grid_search_census(self):\n self._test_grid_search(Census)" ]
[ [ "scipy.spatial.distance.cosine", "pandas.MultiIndex.from_tuples" ] ]
kira7005/pytorch-image-models
[ "096e6caef70565a4970ddc33ca6c64aac2f7b7d4" ]
[ "train.py" ]
[ "#!/usr/bin/env python3\n\"\"\" ImageNet Training Script\n\nThis is intended to be a lean and easily modifiable ImageNet training script that reproduces ImageNet\ntraining results with some of the latest networks and training techniques. It favours canonical PyTorch\nand standard Python style over trying to be able to 'do it all.' That said, it offers quite a few speed\nand training result improvements over the usual PyTorch example scripts. Repurpose as you see fit.\n\nThis script was started from an early version of the PyTorch ImageNet example\n(https://github.com/pytorch/examples/tree/master/imagenet)\n\nNVIDIA CUDA specific speedups adopted from NVIDIA Apex examples\n(https://github.com/NVIDIA/apex/tree/master/examples/imagenet)\n\nHacked together by / Copyright 2020 Ross Wightman (https://github.com/rwightman)\n\"\"\"\nimport argparse\nimport time\nimport yaml\nimport os\nimport logging\nfrom collections import OrderedDict\nfrom contextlib import suppress\nfrom datetime import datetime\n\nimport torch\nimport torch.nn as nn\nimport torchvision.utils\nfrom torch.nn.parallel import DistributedDataParallel as NativeDDP\n\nfrom timm.data import create_dataset, create_loader, resolve_data_config, Mixup, FastCollateMixup, AugMixDataset\nfrom timm.models import create_model, safe_model_name, resume_checkpoint, load_checkpoint,\\\n convert_splitbn_model, model_parameters\nfrom timm.utils import *\nfrom timm.loss import *\nfrom timm.optim import create_optimizer_v2, optimizer_kwargs\nfrom timm.scheduler import create_scheduler\nfrom timm.utils import ApexScaler, NativeScaler\n\ntry:\n from apex import amp\n from apex.parallel import DistributedDataParallel as ApexDDP\n from apex.parallel import convert_syncbn_model\n has_apex = True\nexcept ImportError:\n has_apex = False\n\nhas_native_amp = False\ntry:\n if getattr(torch.cuda.amp, 'autocast') is not None:\n has_native_amp = True\nexcept AttributeError:\n pass\n\ntry:\n import wandb\n has_wandb = True\nexcept ImportError: \n has_wandb = False\n\ntorch.backends.cudnn.benchmark = True\n_logger = logging.getLogger('train')\n\n# The first arg parser parses out only the --config argument, this argument is used to\n# load a yaml file containing key-values that override the defaults for the main parser below\nconfig_parser = parser = argparse.ArgumentParser(description='Training Config', add_help=False)\nparser.add_argument('-c', '--config', default='', type=str, metavar='FILE',\n help='YAML config file specifying default arguments')\n\n\nparser = argparse.ArgumentParser(description='PyTorch ImageNet Training')\n\n# Dataset parameters\nparser.add_argument('data_dir', metavar='DIR',\n help='path to dataset')\nparser.add_argument('--dataset', '-d', metavar='NAME', default='',\n help='dataset type (default: ImageFolder/ImageTar if empty)')\nparser.add_argument('--train-split', metavar='NAME', default='train',\n help='dataset train split (default: train)')\nparser.add_argument('--val-split', metavar='NAME', default='validation',\n help='dataset validation split (default: validation)')\nparser.add_argument('--dataset-download', action='store_true', default=False,\n help='Allow download of dataset for torch/ and tfds/ datasets that support it.')\nparser.add_argument('--class-map', default='', type=str, metavar='FILENAME',\n help='path to class to idx mapping file (default: \"\")')\n\n# Model parameters\nparser.add_argument('--model', default='resnet50', type=str, metavar='MODEL',\n help='Name of model to train (default: \"resnet50\"')\nparser.add_argument('--pretrained', action='store_true', default=False,\n help='Start with pretrained version of specified network (if avail)')\nparser.add_argument('--initial-checkpoint', default='', type=str, metavar='PATH',\n help='Initialize model from this checkpoint (default: none)')\nparser.add_argument('--resume', default='', type=str, metavar='PATH',\n help='Resume full model and optimizer state from checkpoint (default: none)')\nparser.add_argument('--no-resume-opt', action='store_true', default=False,\n help='prevent resume of optimizer state when resuming model')\nparser.add_argument('--num-classes', type=int, default=None, metavar='N',\n help='number of label classes (Model default if None)')\nparser.add_argument('--gp', default=None, type=str, metavar='POOL',\n help='Global pool type, one of (fast, avg, max, avgmax, avgmaxc). Model default if None.')\nparser.add_argument('--img-size', type=int, default=None, metavar='N',\n help='Image patch size (default: None => model default)')\nparser.add_argument('--input-size', default=None, nargs=3, type=int,\n metavar='N N N', help='Input all image dimensions (d h w, e.g. --input-size 3 224 224), uses model default if empty')\nparser.add_argument('--crop-pct', default=None, type=float,\n metavar='N', help='Input image center crop percent (for validation only)')\nparser.add_argument('--mean', type=float, nargs='+', default=None, metavar='MEAN',\n help='Override mean pixel value of dataset')\nparser.add_argument('--std', type=float, nargs='+', default=None, metavar='STD',\n help='Override std deviation of of dataset')\nparser.add_argument('--interpolation', default='', type=str, metavar='NAME',\n help='Image resize interpolation type (overrides model)')\nparser.add_argument('-b', '--batch-size', type=int, default=128, metavar='N',\n help='input batch size for training (default: 128)')\nparser.add_argument('-vb', '--validation-batch-size', type=int, default=None, metavar='N',\n help='validation batch size override (default: None)')\n\n# Optimizer parameters\nparser.add_argument('--opt', default='sgd', type=str, metavar='OPTIMIZER',\n help='Optimizer (default: \"sgd\"')\nparser.add_argument('--opt-eps', default=None, type=float, metavar='EPSILON',\n help='Optimizer Epsilon (default: None, use opt default)')\nparser.add_argument('--opt-betas', default=None, type=float, nargs='+', metavar='BETA',\n help='Optimizer Betas (default: None, use opt default)')\nparser.add_argument('--momentum', type=float, default=0.9, metavar='M',\n help='Optimizer momentum (default: 0.9)')\nparser.add_argument('--weight-decay', type=float, default=2e-5,\n help='weight decay (default: 2e-5)')\nparser.add_argument('--clip-grad', type=float, default=None, metavar='NORM',\n help='Clip gradient norm (default: None, no clipping)')\nparser.add_argument('--clip-mode', type=str, default='norm',\n help='Gradient clipping mode. One of (\"norm\", \"value\", \"agc\")')\n\n\n# Learning rate schedule parameters\nparser.add_argument('--sched', default='cosine', type=str, metavar='SCHEDULER',\n help='LR scheduler (default: \"step\"')\nparser.add_argument('--lr', type=float, default=0.05, metavar='LR',\n help='learning rate (default: 0.05)')\nparser.add_argument('--lr-noise', type=float, nargs='+', default=None, metavar='pct, pct',\n help='learning rate noise on/off epoch percentages')\nparser.add_argument('--lr-noise-pct', type=float, default=0.67, metavar='PERCENT',\n help='learning rate noise limit percent (default: 0.67)')\nparser.add_argument('--lr-noise-std', type=float, default=1.0, metavar='STDDEV',\n help='learning rate noise std-dev (default: 1.0)')\nparser.add_argument('--lr-cycle-mul', type=float, default=1.0, metavar='MULT',\n help='learning rate cycle len multiplier (default: 1.0)')\nparser.add_argument('--lr-cycle-decay', type=float, default=0.5, metavar='MULT',\n help='amount to decay each learning rate cycle (default: 0.5)')\nparser.add_argument('--lr-cycle-limit', type=int, default=1, metavar='N',\n help='learning rate cycle limit, cycles enabled if > 1')\nparser.add_argument('--lr-k-decay', type=float, default=1.0,\n help='learning rate k-decay for cosine/poly (default: 1.0)')\nparser.add_argument('--warmup-lr', type=float, default=0.0001, metavar='LR',\n help='warmup learning rate (default: 0.0001)')\nparser.add_argument('--min-lr', type=float, default=1e-6, metavar='LR',\n help='lower lr bound for cyclic schedulers that hit 0 (1e-5)')\nparser.add_argument('--epochs', type=int, default=300, metavar='N',\n help='number of epochs to train (default: 300)')\nparser.add_argument('--epoch-repeats', type=float, default=0., metavar='N',\n help='epoch repeat multiplier (number of times to repeat dataset epoch per train epoch).')\nparser.add_argument('--start-epoch', default=None, type=int, metavar='N',\n help='manual epoch number (useful on restarts)')\nparser.add_argument('--decay-epochs', type=float, default=100, metavar='N',\n help='epoch interval to decay LR')\nparser.add_argument('--warmup-epochs', type=int, default=3, metavar='N',\n help='epochs to warmup LR, if scheduler supports')\nparser.add_argument('--cooldown-epochs', type=int, default=10, metavar='N',\n help='epochs to cooldown LR at min_lr, after cyclic schedule ends')\nparser.add_argument('--patience-epochs', type=int, default=10, metavar='N',\n help='patience epochs for Plateau LR scheduler (default: 10')\nparser.add_argument('--decay-rate', '--dr', type=float, default=0.1, metavar='RATE',\n help='LR decay rate (default: 0.1)')\n\n# Augmentation & regularization parameters\nparser.add_argument('--no-aug', action='store_true', default=False,\n help='Disable all training augmentation, override other train aug args')\nparser.add_argument('--scale', type=float, nargs='+', default=[0.08, 1.0], metavar='PCT',\n help='Random resize scale (default: 0.08 1.0)')\nparser.add_argument('--ratio', type=float, nargs='+', default=[3./4., 4./3.], metavar='RATIO',\n help='Random resize aspect ratio (default: 0.75 1.33)')\nparser.add_argument('--hflip', type=float, default=0.5,\n help='Horizontal flip training aug probability')\nparser.add_argument('--vflip', type=float, default=0.,\n help='Vertical flip training aug probability')\nparser.add_argument('--color-jitter', type=float, default=0.4, metavar='PCT',\n help='Color jitter factor (default: 0.4)')\nparser.add_argument('--aa', type=str, default=None, metavar='NAME',\n help='Use AutoAugment policy. \"v0\" or \"original\". (default: None)'),\nparser.add_argument('--aug-repeats', type=int, default=0,\n help='Number of augmentation repetitions (distributed training only) (default: 0)')\nparser.add_argument('--aug-splits', type=int, default=0,\n help='Number of augmentation splits (default: 0, valid: 0 or >=2)')\nparser.add_argument('--jsd-loss', action='store_true', default=False,\n help='Enable Jensen-Shannon Divergence + CE loss. Use with `--aug-splits`.')\nparser.add_argument('--bce-loss', action='store_true', default=False,\n help='Enable BCE loss w/ Mixup/CutMix use.')\nparser.add_argument('--mil-loss', action='store_true', default=False,\n help='Enable MIL ranking loss')\nparser.add_argument('--bce-target-thresh', type=float, default=None,\n help='Threshold for binarizing softened BCE targets (default: None, disabled)')\nparser.add_argument('--reprob', type=float, default=0., metavar='PCT',\n help='Random erase prob (default: 0.)')\nparser.add_argument('--remode', type=str, default='pixel',\n help='Random erase mode (default: \"pixel\")')\nparser.add_argument('--recount', type=int, default=1,\n help='Random erase count (default: 1)')\nparser.add_argument('--resplit', action='store_true', default=False,\n help='Do not random erase first (clean) augmentation split')\nparser.add_argument('--mixup', type=float, default=0.0,\n help='mixup alpha, mixup enabled if > 0. (default: 0.)')\nparser.add_argument('--cutmix', type=float, default=0.0,\n help='cutmix alpha, cutmix enabled if > 0. (default: 0.)')\nparser.add_argument('--cutmix-minmax', type=float, nargs='+', default=None,\n help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)')\nparser.add_argument('--mixup-prob', type=float, default=1.0,\n help='Probability of performing mixup or cutmix when either/both is enabled')\nparser.add_argument('--mixup-switch-prob', type=float, default=0.5,\n help='Probability of switching to cutmix when both mixup and cutmix enabled')\nparser.add_argument('--mixup-mode', type=str, default='batch',\n help='How to apply mixup/cutmix params. Per \"batch\", \"pair\", or \"elem\"')\nparser.add_argument('--mixup-off-epoch', default=0, type=int, metavar='N',\n help='Turn off mixup after this epoch, disabled if 0 (default: 0)')\nparser.add_argument('--smoothing', type=float, default=0.1,\n help='Label smoothing (default: 0.1)')\nparser.add_argument('--train-interpolation', type=str, default='random',\n help='Training interpolation (random, bilinear, bicubic default: \"random\")')\nparser.add_argument('--drop', type=float, default=0.0, metavar='PCT',\n help='Dropout rate (default: 0.)')\nparser.add_argument('--drop-connect', type=float, default=None, metavar='PCT',\n help='Drop connect rate, DEPRECATED, use drop-path (default: None)')\nparser.add_argument('--drop-path', type=float, default=None, metavar='PCT',\n help='Drop path rate (default: None)')\nparser.add_argument('--drop-block', type=float, default=None, metavar='PCT',\n help='Drop block rate (default: None)')\n\n# Batch norm parameters (only works with gen_efficientnet based models currently)\nparser.add_argument('--bn-momentum', type=float, default=None,\n help='BatchNorm momentum override (if not None)')\nparser.add_argument('--bn-eps', type=float, default=None,\n help='BatchNorm epsilon override (if not None)')\nparser.add_argument('--sync-bn', action='store_true',\n help='Enable NVIDIA Apex or Torch synchronized BatchNorm.')\nparser.add_argument('--dist-bn', type=str, default='reduce',\n help='Distribute BatchNorm stats between nodes after each epoch (\"broadcast\", \"reduce\", or \"\")')\nparser.add_argument('--split-bn', action='store_true',\n help='Enable separate BN layers per augmentation split.')\n\n# Model Exponential Moving Average\nparser.add_argument('--model-ema', action='store_true', default=False,\n help='Enable tracking moving average of model weights')\nparser.add_argument('--model-ema-force-cpu', action='store_true', default=False,\n help='Force ema to be tracked on CPU, rank=0 node only. Disables EMA validation.')\nparser.add_argument('--model-ema-decay', type=float, default=0.9998,\n help='decay factor for model weights moving average (default: 0.9998)')\n\n# Misc\nparser.add_argument('--seed', type=int, default=42, metavar='S',\n help='random seed (default: 42)')\nparser.add_argument('--worker-seeding', type=str, default='all',\n help='worker seed mode (default: all)')\nparser.add_argument('--log-interval', type=int, default=50, metavar='N',\n help='how many batches to wait before logging training status')\nparser.add_argument('--recovery-interval', type=int, default=0, metavar='N',\n help='how many batches to wait before writing recovery checkpoint')\nparser.add_argument('--checkpoint-hist', type=int, default=10, metavar='N',\n help='number of checkpoints to keep (default: 10)')\nparser.add_argument('-j', '--workers', type=int, default=4, metavar='N',\n help='how many training processes to use (default: 4)')\nparser.add_argument('--save-images', action='store_true', default=False,\n help='save images of input bathes every log interval for debugging')\nparser.add_argument('--amp', action='store_true', default=False,\n help='use NVIDIA Apex AMP or Native AMP for mixed precision training')\nparser.add_argument('--apex-amp', action='store_true', default=False,\n help='Use NVIDIA Apex AMP mixed precision')\nparser.add_argument('--native-amp', action='store_true', default=False,\n help='Use Native Torch AMP mixed precision')\nparser.add_argument('--no-ddp-bb', action='store_true', default=False,\n help='Force broadcast buffers for native DDP to off.')\nparser.add_argument('--channels-last', action='store_true', default=False,\n help='Use channels_last memory layout')\nparser.add_argument('--pin-mem', action='store_true', default=False,\n help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.')\nparser.add_argument('--no-prefetcher', action='store_true', default=False,\n help='disable fast prefetcher')\nparser.add_argument('--output', default='', type=str, metavar='PATH',\n help='path to output folder (default: none, current dir)')\nparser.add_argument('--experiment', default='', type=str, metavar='NAME',\n help='name of train experiment, name of sub-folder for output')\nparser.add_argument('--eval-metric', default='top1', type=str, metavar='EVAL_METRIC',\n help='Best metric (default: \"top1\"')\nparser.add_argument('--tta', type=int, default=0, metavar='N',\n help='Test/inference time augmentation (oversampling) factor. 0=None (default: 0)')\nparser.add_argument(\"--local_rank\", default=0, type=int)\nparser.add_argument('--use-multi-epochs-loader', action='store_true', default=False,\n help='use the multi-epochs-loader to save time at the beginning of every epoch')\nparser.add_argument('--torchscript', dest='torchscript', action='store_true',\n help='convert model torchscript for inference')\nparser.add_argument('--fuser', default='', type=str,\n help=\"Select jit fuser. One of ('', 'te', 'old', 'nvfuser')\")\nparser.add_argument('--log-wandb', action='store_true', default=False,\n help='log training and validation metrics to wandb')\n\n\ndef _parse_args():\n # Do we have a config file to parse?\n args_config, remaining = config_parser.parse_known_args()\n if args_config.config:\n with open(args_config.config, 'r') as f:\n cfg = yaml.safe_load(f)\n parser.set_defaults(**cfg)\n\n # The main arg parser parses the rest of the args, the usual\n # defaults will have been overridden if config file specified.\n args = parser.parse_args(remaining)\n\n # Cache the args as a text string to save them in the output dir later\n args_text = yaml.safe_dump(args.__dict__, default_flow_style=False)\n return args, args_text\n\n\ndef main():\n setup_default_logging()\n args, args_text = _parse_args()\n \n if args.log_wandb:\n if has_wandb:\n wandb.init(project=args.experiment, config=args)\n else: \n _logger.warning(\"You've requested to log metrics to wandb but package not found. \"\n \"Metrics not being logged to wandb, try `pip install wandb`\")\n \n args.prefetcher = not args.no_prefetcher\n args.distributed = False\n if 'WORLD_SIZE' in os.environ:\n args.distributed = int(os.environ['WORLD_SIZE']) > 1\n args.device = 'cuda:0'\n args.world_size = 1\n args.rank = 0 # global rank\n if args.distributed:\n args.device = 'cuda:%d' % args.local_rank\n torch.cuda.set_device(args.local_rank)\n torch.distributed.init_process_group(backend='nccl', init_method='env://')\n args.world_size = torch.distributed.get_world_size()\n args.rank = torch.distributed.get_rank()\n _logger.info('Training in distributed mode with multiple processes, 1 GPU per process. Process %d, total %d.'\n % (args.rank, args.world_size))\n else:\n _logger.info('Training with a single process on 1 GPUs.')\n assert args.rank >= 0\n\n # resolve AMP arguments based on PyTorch / Apex availability\n use_amp = None\n if args.amp:\n # `--amp` chooses native amp before apex (APEX ver not actively maintained)\n if has_native_amp:\n args.native_amp = True\n elif has_apex:\n args.apex_amp = True\n if args.apex_amp and has_apex:\n use_amp = 'apex'\n elif args.native_amp and has_native_amp:\n use_amp = 'native'\n elif args.apex_amp or args.native_amp:\n _logger.warning(\"Neither APEX or native Torch AMP is available, using float32. \"\n \"Install NVIDA apex or upgrade to PyTorch 1.6\")\n\n random_seed(args.seed, args.rank)\n\n if args.fuser:\n set_jit_fuser(args.fuser)\n\n model = create_model(\n args.model,\n pretrained=args.pretrained,\n num_classes=args.num_classes,\n drop_rate=args.drop,\n drop_connect_rate=args.drop_connect, # DEPRECATED, use drop_path\n drop_path_rate=args.drop_path,\n drop_block_rate=args.drop_block,\n global_pool=args.gp,\n bn_momentum=args.bn_momentum,\n bn_eps=args.bn_eps,\n scriptable=args.torchscript,\n checkpoint_path=args.initial_checkpoint)\n if args.num_classes is None:\n assert hasattr(model, 'num_classes'), 'Model must have `num_classes` attr if not set on cmd line/config.'\n args.num_classes = model.num_classes # FIXME handle model default vs config num_classes more elegantly\n\n if args.local_rank == 0:\n _logger.info(\n f'Model {safe_model_name(args.model)} created, param count:{sum([m.numel() for m in model.parameters()])}')\n\n data_config = resolve_data_config(vars(args), model=model, verbose=args.local_rank == 0)\n\n # setup augmentation batch splits for contrastive loss or split bn\n num_aug_splits = 0\n if args.aug_splits > 0:\n assert args.aug_splits > 1, 'A split of 1 makes no sense'\n num_aug_splits = args.aug_splits\n\n # enable split bn (separate bn stats per batch-portion)\n if args.split_bn:\n assert num_aug_splits > 1 or args.resplit\n model = convert_splitbn_model(model, max(num_aug_splits, 2))\n\n # move model to GPU, enable channels last layout if set\n model.cuda()\n if args.channels_last:\n model = model.to(memory_format=torch.channels_last)\n\n # setup synchronized BatchNorm for distributed training\n if args.distributed and args.sync_bn:\n assert not args.split_bn\n if has_apex and use_amp == 'apex':\n # Apex SyncBN preferred unless native amp is activated\n model = convert_syncbn_model(model)\n else:\n model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)\n if args.local_rank == 0:\n _logger.info(\n 'Converted model to use Synchronized BatchNorm. WARNING: You may have issues if using '\n 'zero initialized BN layers (enabled by default for ResNets) while sync-bn enabled.')\n\n if args.torchscript:\n assert not use_amp == 'apex', 'Cannot use APEX AMP with torchscripted model'\n assert not args.sync_bn, 'Cannot use SyncBatchNorm with torchscripted model'\n model = torch.jit.script(model)\n\n optimizer = create_optimizer_v2(model, **optimizer_kwargs(cfg=args))\n\n # setup automatic mixed-precision (AMP) loss scaling and op casting\n amp_autocast = suppress # do nothing\n loss_scaler = None\n if use_amp == 'apex':\n model, optimizer = amp.initialize(model, optimizer, opt_level='O1')\n loss_scaler = ApexScaler()\n if args.local_rank == 0:\n _logger.info('Using NVIDIA APEX AMP. Training in mixed precision.')\n elif use_amp == 'native':\n amp_autocast = torch.cuda.amp.autocast\n loss_scaler = NativeScaler()\n if args.local_rank == 0:\n _logger.info('Using native Torch AMP. Training in mixed precision.')\n else:\n if args.local_rank == 0:\n _logger.info('AMP not enabled. Training in float32.')\n\n # optionally resume from a checkpoint\n resume_epoch = None\n if args.resume:\n resume_epoch = resume_checkpoint(\n model, args.resume,\n optimizer=None if args.no_resume_opt else optimizer,\n loss_scaler=None if args.no_resume_opt else loss_scaler,\n log_info=args.local_rank == 0)\n\n # setup exponential moving average of model weights, SWA could be used here too\n model_ema = None\n if args.model_ema:\n # Important to create EMA model after cuda(), DP wrapper, and AMP but before SyncBN and DDP wrapper\n model_ema = ModelEmaV2(\n model, decay=args.model_ema_decay, device='cpu' if args.model_ema_force_cpu else None)\n if args.resume:\n load_checkpoint(model_ema.module, args.resume, use_ema=True)\n\n # setup distributed training\n if args.distributed:\n if has_apex and use_amp == 'apex':\n # Apex DDP preferred unless native amp is activated\n if args.local_rank == 0:\n _logger.info(\"Using NVIDIA APEX DistributedDataParallel.\")\n model = ApexDDP(model, delay_allreduce=True)\n else:\n if args.local_rank == 0:\n _logger.info(\"Using native Torch DistributedDataParallel.\")\n model = NativeDDP(model, device_ids=[args.local_rank], broadcast_buffers=not args.no_ddp_bb)\n # NOTE: EMA model does not need to be wrapped by DDP\n\n # setup learning rate schedule and starting epoch\n lr_scheduler, num_epochs = create_scheduler(args, optimizer)\n start_epoch = 0\n if args.start_epoch is not None:\n # a specified start_epoch will always override the resume epoch\n start_epoch = args.start_epoch\n elif resume_epoch is not None:\n start_epoch = resume_epoch\n if lr_scheduler is not None and start_epoch > 0:\n lr_scheduler.step(start_epoch)\n\n if args.local_rank == 0:\n _logger.info('Scheduled epochs: {}'.format(num_epochs))\n\n # create the train and eval datasets\n dataset_train = create_dataset(\n args.dataset, root=args.data_dir, split=args.train_split, is_training=True,\n class_map=args.class_map,\n download=args.dataset_download,\n batch_size=args.batch_size,\n repeats=args.epoch_repeats)\n dataset_eval = create_dataset(\n args.dataset, root=args.data_dir, split=args.val_split, is_training=False,\n class_map=args.class_map,\n download=args.dataset_download,\n batch_size=args.batch_size)\n\n # setup mixup / cutmix\n collate_fn = None\n mixup_fn = None\n mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None\n if mixup_active:\n mixup_args = dict(\n mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax,\n prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode,\n label_smoothing=args.smoothing, num_classes=args.num_classes)\n if args.prefetcher:\n assert not num_aug_splits # collate conflict (need to support deinterleaving in collate mixup)\n collate_fn = FastCollateMixup(**mixup_args)\n else:\n mixup_fn = Mixup(**mixup_args)\n\n # wrap dataset in AugMix helper\n if num_aug_splits > 1:\n dataset_train = AugMixDataset(dataset_train, num_splits=num_aug_splits)\n\n # create data loaders w/ augmentation pipeiine\n train_interpolation = args.train_interpolation\n if args.no_aug or not train_interpolation:\n train_interpolation = data_config['interpolation']\n loader_train = create_loader(\n dataset_train,\n custom_sampler = True,\n input_size=data_config['input_size'],\n batch_size=args.batch_size,\n is_training=True,\n use_prefetcher=args.prefetcher,\n no_aug=args.no_aug,\n re_prob=args.reprob,\n re_mode=args.remode,\n re_count=args.recount,\n re_split=args.resplit,\n scale=args.scale,\n ratio=args.ratio,\n hflip=args.hflip,\n vflip=args.vflip,\n color_jitter=args.color_jitter,\n auto_augment=args.aa,\n num_aug_repeats=args.aug_repeats,\n num_aug_splits=num_aug_splits,\n interpolation=train_interpolation,\n mean=data_config['mean'],\n std=data_config['std'],\n num_workers=args.workers,\n distributed=args.distributed,\n collate_fn=collate_fn,\n pin_memory=args.pin_mem,\n use_multi_epochs_loader=args.use_multi_epochs_loader,\n worker_seeding=args.worker_seeding,\n )\n \n loader_eval = create_loader(\n dataset_eval,\n input_size=data_config['input_size'],\n batch_size=args.validation_batch_size or args.batch_size,\n is_training=False,\n use_prefetcher=args.prefetcher,\n interpolation=data_config['interpolation'],\n mean=data_config['mean'],\n std=data_config['std'],\n num_workers=args.workers,\n distributed=args.distributed,\n crop_pct=data_config['crop_pct'],\n pin_memory=args.pin_mem,\n )\n\n # setup loss function\n if args.jsd_loss:\n assert num_aug_splits > 1 # JSD only valid with aug splits set\n train_loss_fn = JsdCrossEntropy(num_splits=num_aug_splits, smoothing=args.smoothing)\n elif args.mil_loss:\n train_loss_fn = MilRankingLoss()\n elif mixup_active:\n # smoothing is handled with mixup target transform which outputs sparse, soft targets\n if args.bce_loss:\n train_loss_fn = BinaryCrossEntropy(target_threshold=args.bce_target_thresh)\n else:\n train_loss_fn = SoftTargetCrossEntropy()\n elif args.smoothing:\n if args.bce_loss:\n train_loss_fn = BinaryCrossEntropy(smoothing=args.smoothing, target_threshold=args.bce_target_thresh)\n else:\n train_loss_fn = LabelSmoothingCrossEntropy(smoothing=args.smoothing)\n else:\n train_loss_fn = nn.CrossEntropyLoss()\n train_loss_fn = train_loss_fn.cuda()\n validate_loss_fn = nn.CrossEntropyLoss().cuda()\n\n # setup checkpoint saver and eval metric tracking\n eval_metric = args.eval_metric\n best_metric = None\n best_epoch = None\n saver = None\n output_dir = None\n if args.rank == 0:\n if args.experiment:\n exp_name = args.experiment\n else:\n exp_name = '-'.join([\n datetime.now().strftime(\"%Y%m%d-%H%M%S\"),\n safe_model_name(args.model),\n str(data_config['input_size'][-1])\n ])\n output_dir = get_outdir(args.output if args.output else './output/train', exp_name)\n decreasing = True if eval_metric == 'loss' else False\n saver = CheckpointSaver(\n model=model, optimizer=optimizer, args=args, model_ema=model_ema, amp_scaler=loss_scaler,\n checkpoint_dir=output_dir, recovery_dir=output_dir, decreasing=decreasing, max_history=args.checkpoint_hist)\n with open(os.path.join(output_dir, 'args.yaml'), 'w') as f:\n f.write(args_text)\n\n try:\n for epoch in range(start_epoch, num_epochs):\n if args.distributed and hasattr(loader_train.sampler, 'set_epoch'):\n loader_train.sampler.set_epoch(epoch)\n\n train_metrics = train_one_epoch(\n epoch, model, loader_train, optimizer, train_loss_fn, args,\n lr_scheduler=lr_scheduler, saver=saver, output_dir=output_dir,\n amp_autocast=amp_autocast, loss_scaler=loss_scaler, model_ema=model_ema, mixup_fn=mixup_fn)\n\n if args.distributed and args.dist_bn in ('broadcast', 'reduce'):\n if args.local_rank == 0:\n _logger.info(\"Distributing BatchNorm running means and vars\")\n distribute_bn(model, args.world_size, args.dist_bn == 'reduce')\n\n eval_metrics = validate(model, loader_eval, validate_loss_fn, args, amp_autocast=amp_autocast)\n\n if model_ema is not None and not args.model_ema_force_cpu:\n if args.distributed and args.dist_bn in ('broadcast', 'reduce'):\n distribute_bn(model_ema, args.world_size, args.dist_bn == 'reduce')\n ema_eval_metrics = validate(\n model_ema.module, loader_eval, validate_loss_fn, args, amp_autocast=amp_autocast, log_suffix=' (EMA)')\n eval_metrics = ema_eval_metrics\n\n if lr_scheduler is not None:\n # step LR for next epoch\n lr_scheduler.step(epoch + 1, eval_metrics[eval_metric])\n\n if output_dir is not None:\n update_summary(\n epoch, train_metrics, eval_metrics, os.path.join(output_dir, 'summary.csv'),\n write_header=best_metric is None, log_wandb=args.log_wandb and has_wandb)\n\n if saver is not None:\n # save proper checkpoint with eval metric\n save_metric = eval_metrics[eval_metric]\n best_metric, best_epoch = saver.save_checkpoint(epoch, metric=save_metric)\n\n except KeyboardInterrupt:\n pass\n if best_metric is not None:\n _logger.info('*** Best metric: {0} (epoch {1})'.format(best_metric, best_epoch))\n\n\ndef train_one_epoch(\n epoch, model, loader, optimizer, loss_fn, args,\n lr_scheduler=None, saver=None, output_dir=None, amp_autocast=suppress,\n loss_scaler=None, model_ema=None, mixup_fn=None):\n \n #model.forward_features.weight.requires_grad=False\n for name, param in model.named_parameters():\n if param.requires_grad and 'blocks' in name:\n param.requires_grad = False\n #print(\"Freezed=\", name)\n #else:\n #print(\"Unfreezed=\", name)\n \n #print(model)\n\n if args.mixup_off_epoch and epoch >= args.mixup_off_epoch:\n if args.prefetcher and loader.mixup_enabled:\n loader.mixup_enabled = False\n elif mixup_fn is not None:\n mixup_fn.mixup_enabled = False\n\n second_order = hasattr(optimizer, 'is_second_order') and optimizer.is_second_order\n batch_time_m = AverageMeter()\n data_time_m = AverageMeter()\n losses_m = AverageMeter()\n\n print(\"------Training-------\")\n model.train()\n\n end = time.time()\n #print(\"loader_length=\",len(loader))\n last_idx = len(loader) - 1\n num_updates = epoch * len(loader)\n for batch_idx, (input, target) in enumerate(loader):\n #print(\"batch=\", batch_idx)\n last_batch = batch_idx == last_idx\n data_time_m.update(time.time() - end)\n if not args.prefetcher:\n input, target = input.cuda(), target.cuda()\n if mixup_fn is not None:\n input, target = mixup_fn(input, target)\n if args.channels_last:\n input = input.contiguous(memory_format=torch.channels_last)\n\n with amp_autocast():\n #print(model)\n print(input.shape)\n output = model(input)\n print(output.shape)\n print(target.shape)\n #print(output)\n #print(target)\n print(loss_fn)\n loss = loss_fn(output, target)\n print(\"loss=\", loss)\n\n if not args.distributed:\n losses_m.update(loss.item(), input.size(0))\n\n optimizer.zero_grad()\n if loss_scaler is not None:\n loss_scaler(\n loss, optimizer,\n clip_grad=args.clip_grad, clip_mode=args.clip_mode,\n parameters=model_parameters(model, exclude_head='agc' in args.clip_mode),\n create_graph=second_order)\n else:\n loss.backward(create_graph=second_order)\n if args.clip_grad is not None:\n dispatch_clip_grad(\n model_parameters(model, exclude_head='agc' in args.clip_mode),\n value=args.clip_grad, mode=args.clip_mode)\n optimizer.step()\n\n if model_ema is not None:\n model_ema.update(model)\n\n torch.cuda.synchronize()\n num_updates += 1\n batch_time_m.update(time.time() - end)\n if last_batch or batch_idx % args.log_interval == 0:\n lrl = [param_group['lr'] for param_group in optimizer.param_groups]\n lr = sum(lrl) / len(lrl)\n\n if args.distributed:\n reduced_loss = reduce_tensor(loss.data, args.world_size)\n losses_m.update(reduced_loss.item(), input.size(0))\n\n if args.local_rank == 0:\n _logger.info(\n 'Train: {} [{:>4d}/{} ({:>3.0f}%)] '\n 'Loss: {loss.val:#.4g} ({loss.avg:#.3g}) '\n 'Time: {batch_time.val:.3f}s, {rate:>7.2f}/s '\n '({batch_time.avg:.3f}s, {rate_avg:>7.2f}/s) '\n 'LR: {lr:.3e} '\n 'Data: {data_time.val:.3f} ({data_time.avg:.3f})'.format(\n epoch,\n batch_idx, len(loader),\n 100. * batch_idx / last_idx,\n loss=losses_m,\n batch_time=batch_time_m,\n rate=input.size(0) * args.world_size / batch_time_m.val,\n rate_avg=input.size(0) * args.world_size / batch_time_m.avg,\n lr=lr,\n data_time=data_time_m))\n\n if args.save_images and output_dir:\n torchvision.utils.save_image(\n input,\n os.path.join(output_dir, 'train-batch-%d.jpg' % batch_idx),\n padding=0,\n normalize=True)\n\n if saver is not None and args.recovery_interval and (\n last_batch or (batch_idx + 1) % args.recovery_interval == 0):\n saver.save_recovery(epoch, batch_idx=batch_idx)\n\n if lr_scheduler is not None:\n lr_scheduler.step_update(num_updates=num_updates, metric=losses_m.avg)\n\n end = time.time()\n # end for\n\n if hasattr(optimizer, 'sync_lookahead'):\n optimizer.sync_lookahead()\n\n return OrderedDict([('loss', losses_m.avg)])\n\n\ndef validate(model, loader, loss_fn, args, amp_autocast=suppress, log_suffix=''):\n batch_time_m = AverageMeter()\n losses_m = AverageMeter()\n top1_m = AverageMeter()\n top5_m = AverageMeter()\n\n print(\"------Validating-------\")\n model.eval()\n\n end = time.time()\n last_idx = len(loader) - 1\n with torch.no_grad():\n for batch_idx, (input, target) in enumerate(loader):\n last_batch = batch_idx == last_idx\n if not args.prefetcher:\n input = input.cuda()\n target = target.cuda()\n if args.channels_last:\n input = input.contiguous(memory_format=torch.channels_last)\n\n with amp_autocast():\n output = model(input)\n if isinstance(output, (tuple, list)):\n output = output[0]\n\n # augmentation reduction\n reduce_factor = args.tta\n if reduce_factor > 1:\n output = output.unfold(0, reduce_factor, reduce_factor).mean(dim=2)\n target = target[0:target.size(0):reduce_factor]\n\n print(\"output =\", output)\n print(\"target=\", target)\n loss = loss_fn(output, target)\n print(\"eval_loss=\", loss)\n acc1, acc5 = accuracy(output, target, topk=(1, 5))\n print(\"eval_acc1=\", acc1)\n\n if args.distributed:\n reduced_loss = reduce_tensor(loss.data, args.world_size)\n acc1 = reduce_tensor(acc1, args.world_size)\n acc5 = reduce_tensor(acc5, args.world_size)\n else:\n reduced_loss = loss.data\n\n torch.cuda.synchronize()\n\n losses_m.update(reduced_loss.item(), input.size(0))\n top1_m.update(acc1.item(), output.size(0))\n top5_m.update(acc5.item(), output.size(0))\n\n batch_time_m.update(time.time() - end)\n end = time.time()\n if args.local_rank == 0 and (last_batch or batch_idx % args.log_interval == 0):\n log_name = 'Test' + log_suffix\n _logger.info(\n '{0}: [{1:>4d}/{2}] '\n 'Time: {batch_time.val:.3f} ({batch_time.avg:.3f}) '\n 'Loss: {loss.val:>7.4f} ({loss.avg:>6.4f}) '\n 'Acc@1: {top1.val:>7.4f} ({top1.avg:>7.4f}) '\n 'Acc@5: {top5.val:>7.4f} ({top5.avg:>7.4f})'.format(\n log_name, batch_idx, last_idx, batch_time=batch_time_m,\n loss=losses_m, top1=top1_m, top5=top5_m))\n\n metrics = OrderedDict([('loss', losses_m.avg), ('top1', top1_m.avg), ('top5', top5_m.avg)])\n\n return metrics\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "torch.jit.script", "torch.cuda.synchronize", "torch.nn.CrossEntropyLoss", "torch.distributed.init_process_group", "torch.cuda.set_device", "torch.nn.SyncBatchNorm.convert_sync_batchnorm", "torch.no_grad", "torch.distributed.get_rank", "torch.distributed.get_world_size", "torch.nn.parallel.DistributedDataParallel" ] ]
mckoh/blob_creator
[ "3fb00efd91f1d0017e052858bdfe5ad432ea1e38" ]
[ "src/blob_creator/core.py" ]
[ "\"\"\"\nCore module of Blob Creator\n\nAuthor: Michael Kohlegger\nDate: 2021-09\n\"\"\"\n\nfrom shutil import rmtree\nfrom os import mkdir, remove\nfrom os.path import isdir, join\nfrom numpy import ceil\nfrom numpy.random import normal, randint\nfrom names import get_first_name\nfrom pandas import DataFrame\nfrom svglib.svglib import svg2rlg\nfrom reportlab.graphics import renderPM\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\nfrom matplotlib import use\n\nfrom .const import REPLACE_STRING\nfrom .const import MONSTER, WIDTH_MONSTER, HEIGHT_MONSTER\nfrom .const import ALIEN, WIDTH_ALIEN, HEIGHT_ALIEN\nfrom .const import BOY, WIDTH_BOY, HEIGHT_BOY\nfrom .const import MARSIAN, WIDTH_MARSIAN, HEIGHT_MARSIAN\nfrom .const import COLORS\nfrom .functions import dictionary_filter\nfrom .uploader import upload_file\n\n# Switch matplotlib backend\nuse(\"agg\")\n\nclass BlobFactory:\n \"\"\"BlobFactory class that is used to generate a blob data set.\n\n Blobs are little monsters that are intended to help you explaining\n statistical concepts around sampling. A blob population can be large\n or small. The size is adjustable by the parameter n (default is 5).\n You can also adjust the population's variability by adjusting the\n parameter scatter (default is 12; possible values are 1 to 12).\n\n :param n: The size of the dataset\n :param scatter: The variability of the data that are generated\n :param export_png: A switch that lets you export the original pngs\n :param cols: The number of columns to be used for plotting\n :param monster: Lets you select a monster template\n \"\"\"\n\n def __init__(self,\n n=5,\n scatter=12,\n kind=\"alien\") -> None:\n\n allowed = [\"alien\", \"monster\", \"boy\", \"marsian\"]\n\n assert scatter <= 12, \"Scatter cannot be larger than 12\"\n assert n > 0, \"n must be positive\"\n assert kind in allowed, \"Kind can only be \" + \"/\".join(allowed)\n assert isinstance(n, int), \"n must be int\"\n assert isinstance(scatter, int), \"scatter must be int\"\n\n self._n = n\n self._scatter = scatter\n self._population = None\n self._png_created = False\n\n if kind == \"alien\":\n self._kind = (kind, ALIEN)\n self._kind_w = WIDTH_ALIEN\n self._kind_h = HEIGHT_ALIEN\n\n elif kind == \"monster\":\n self._kind = (kind, MONSTER)\n self._kind_w = WIDTH_MONSTER\n self._kind_h = HEIGHT_MONSTER\n\n elif kind == \"boy\":\n self._kind = (kind, BOY)\n self._kind_w = WIDTH_BOY\n self._kind_h = HEIGHT_BOY\n\n elif kind == \"marsian\":\n self._kind = (kind, MARSIAN)\n self._kind_w = WIDTH_MARSIAN\n self._kind_h = HEIGHT_MARSIAN\n\n def create_blobs(self) -> None:\n \"\"\"Can be called to create a random set of blobs.\"\"\"\n\n if isdir(self.get_population_string()):\n rmtree(self.get_population_string())\n mkdir(self.get_population_string())\n\n self._population = {\n \"names\": [],\n \"sizes\": [],\n \"weights\": [],\n \"colors\": [],\n \"cuteness_levels\": [],\n \"scales\": [],\n }\n\n for i in range(self._n):\n\n # Constants for normal size\n std = 0.5 * self._scatter\n mean = 20\n\n # create the blob\n size = round(normal(loc=mean, scale=std), 2)\n weight = round(size*2+3*normal(loc=0, scale=1), 2)\n\n # determin color based on size\n # as 12 is the largest scatter,\n # 6 is the reference deviation here\n std = 6\n if size < mean-2*std:\n color = 0\n elif size < mean-std:\n color = 1\n elif size < mean-0.3*std:\n color = 2\n elif size < mean+0.3*std:\n color = 3\n elif size < mean+std:\n color = 4\n elif size < mean+2*std:\n color = 5\n else:\n color = 6\n\n color_html = COLORS[color][1]\n color_string = COLORS[color][0]\n\n cuteness = randint(low=1, high=6)\n name = get_first_name() + \" \" + str(i)\n\n self._population[\"names\"].append(name)\n self._population[\"sizes\"].append(size)\n self._population[\"weights\"].append(weight)\n self._population[\"colors\"].append(color_string)\n self._population[\"cuteness_levels\"].append(cuteness)\n\n self._draw_blob(color=color_html, filename=f\"blob_{name}\")\n\n self._size_drawings()\n\n self._png_created = True\n\n def _create_dataframe(self) -> DataFrame:\n \"\"\"Can be used to return a dataframe of the population\"\"\"\n\n data = dictionary_filter(\n self._population,\n [\"names\", \"sizes\", \"weights\", \"colors\", \"cuteness_levels\"]\n )\n\n dataframe = DataFrame(data)\n dataframe.index = dataframe[\"names\"]\n dataframe.drop(\"names\", axis=1, inplace=True)\n\n return dataframe\n\n def _draw_blob(self, filename, color=\"#000000\") -> None:\n \"\"\"Can be used to generate a blob image as png\n\n :param filename: The name of the final png file\n :param color: The HTML color that the blob should have\n \"\"\"\n\n path = join(self.get_population_string(), \"temp.svg\")\n\n with open(path, \"w\", encoding=\"utf8\") as temp_file:\n temp_file.write(\n self._kind[1].replace(REPLACE_STRING, color)\n )\n\n drawing = svg2rlg(path)\n renderPM.drawToFile(\n drawing,\n join(self.get_population_string(), f\"{filename}.png\"),\n fmt=\"PNG\"\n )\n\n remove(path)\n\n def delete_individual_pngs(self) -> None:\n \"\"\"Can be called to remove all blob png files saved to disk.\"\"\"\n if not self._png_created:\n assert False, \"No PNGs to delete.\"\n else:\n for name in self._population[\"names\"]:\n remove(join(self.get_population_string(), f\"blob_{name}.png\"))\n self._png_created = False\n\n def _size_drawings(self) -> None:\n \"\"\"Is used to scale the size of the temporary png images\"\"\"\n\n max_size = max(self._population[\"sizes\"])\n\n for size in self._population[\"sizes\"]:\n self._population[\"scales\"].append(size/max_size)\n\n for i, name in enumerate(self._population[\"names\"]):\n img_name = join(\n self.get_population_string(),\n f\"blob_{name}.png\"\n )\n image = Image.open(img_name)\n width, height = image.size\n width = max(int(width*self._population[\"scales\"][i]), 1)\n height = max(int(height*self._population[\"scales\"][i]), 1)\n image = image.resize((width, height), Image.ANTIALIAS)\n image.save(fp=img_name)\n\n def _plot_population(self, img_name, cols) -> None:\n \"\"\"Can be used to plot a population chart\n\n :param img_name: The name of the final image saved\n \"\"\"\n\n if not cols:\n cols = max(int(self._n/5), 2)\n\n nrows = int(ceil(len(self._population[\"names\"])/cols))\n\n _, axis = plt.subplots(\n ncols=cols,\n nrows=nrows,\n figsize=(15, 15*nrows/cols),\n sharex=True,\n sharey=True\n )\n\n i = 0\n for col in range(cols):\n for row in range(nrows):\n if i == len(self._population[\"names\"]):\n break\n name = self._population[\"names\"][i]\n img_path = join(\n self.get_population_string(),\n f\"blob_{name}.png\"\n )\n image = plt.imread(img_path)\n axis[row, col].set_title(name, loc=\"left\")\n axis[row, col].imshow(image)\n\n axis[row, col].set_ylim([self._kind_h, 0])\n axis[row, col].set_xlim([0, self._kind_w])\n\n i += 1\n\n for col in range(cols):\n for row in range(nrows):\n axis[row, col].axis('off')\n\n plt.tight_layout()\n plt.savefig(img_name)\n\n def export_data(self, cols=None) -> bool:\n \"\"\"Can be used to export a dataframe with blob specs.\"\"\"\n\n if not self._png_created:\n assert False, \"No PNGs created that I could export\"\n else:\n if cols:\n assert cols > 0, \"Cols must be positive\"\n assert isinstance(cols, int), \"Cols must be int\"\n assert cols < self._n, \"Cols must be less than n\"\n\n dataframe = self._create_dataframe()\n dataframe.to_csv(\n join(self.get_population_string(), \"population.csv\")\n )\n\n img_name = join(\n self.get_population_string(),\n \"population.png\"\n )\n\n self._plot_population(img_name=img_name, cols=cols)\n self._plot_data()\n\n def _plot_data(self) -> None:\n \"\"\"Can be used to plot the data.\"\"\"\n\n fig, axis = plt.subplots(nrows=1, ncols=4, figsize=(20, 5))\n\n dataframe = self._create_dataframe()\n\n axis[0].hist(dataframe[\"sizes\"], label=\"data\", color=\"k\", bins=7)\n axis[1].hist(dataframe[\"weights\"], label=\"data\", color=\"k\", bins=7)\n axis[2].bar(\n height=dataframe[\"cuteness_levels\"].value_counts().values,\n x=dataframe[\"cuteness_levels\"].value_counts().index,\n label=\"data\",\n color=\"k\"\n )\n axis[3].scatter(\n x=dataframe[\"sizes\"],\n y=dataframe[\"weights\"],\n label=\"data\",\n color=\"k\"\n )\n\n axis[0].plot(\n [dataframe[\"sizes\"].mean()],\n [0.2],\n \"vr\",\n markersize=15,\n label=\"mean\"\n )\n axis[1].plot(\n [dataframe[\"weights\"].mean()],\n [0.2],\n \"vr\",\n markersize=15,\n label=\"mean\"\n )\n\n axis[0].plot(\n [dataframe[\"sizes\"].median()],\n [0.2],\n \"v\",\n color=\"orange\",\n markersize=15,\n label=\"median\"\n )\n\n axis[1].plot(\n [dataframe[\"weights\"].median()],\n [0.2],\n \"v\",\n color=\"orange\",\n markersize=15,\n label=\"median\"\n )\n\n axis[2].plot(\n [dataframe[\"cuteness_levels\"].median()],\n [0.2],\n \"v\",\n color=\"orange\",\n markersize=15,\n label=\"median\"\n )\n\n axis[0].legend(loc=0)\n axis[1].legend(loc=0)\n axis[2].legend(loc=0)\n axis[3].legend(loc=0)\n\n axis[0].set_title(\"Size Histogram\")\n axis[1].set_title(\"Weight Histogram\")\n axis[2].set_title(\"Cuteness Barchart\")\n axis[3].set_title(\"Weight over Size Scatter Plot\")\n\n axis[0].set_xlabel(\"size class\")\n axis[0].set_ylabel(\"abs. frequency\")\n axis[1].set_xlabel(\"weight class\")\n axis[1].set_ylabel(\"abs. frequency\")\n axis[2].set_xlabel(\"cuteness class\")\n axis[2].set_ylabel(\"abs. frequency\")\n axis[3].set_xlabel(\"size\")\n axis[3].set_ylabel(\"weight\")\n fig.suptitle(\"Analysis of Population\")\n\n plt.savefig(\n join(self.get_population_string(), \"histograms.png\")\n )\n\n def upload_dataset(self) -> str:\n \"\"\"Can be used to make the dataset publicly available\n\n :return: URL of uploaded file\n \"\"\"\n url = upload_file(\n join(\n self.get_population_string(),\n \"population.csv\"\n )\n )\n return url\n\n # GETTER METHODS\n def get_kind_parameters(self) -> tuple:\n \"\"\"Returns the images height and width\"\"\"\n return self._kind[0], self._kind_h, self._kind_w\n\n def get_png_status(self) -> bool:\n \"\"\"Returns the PNG creation status\"\"\"\n return self._png_created\n\n def get_base_parameters(self) -> tuple:\n \"\"\"Returns n and scatter of an engine object\"\"\"\n return self._n, self._scatter\n\n def get_population_string(self) -> None:\n \"\"\"Can be used to generate a population string.\"\"\"\n return f\"blob_population_{self._kind[0]}_n{self._n}_s{self._scatter}\"\n\n def get_population(self) -> dict:\n \"\"\"Can be used to get population object\"\"\"\n return self._population\n" ]
[ [ "matplotlib.pyplot.tight_layout", "matplotlib.use", "matplotlib.pyplot.imread", "matplotlib.pyplot.subplots", "pandas.DataFrame", "matplotlib.pyplot.savefig", "numpy.random.normal", "numpy.random.randint" ] ]
cjcardinale/climlab
[ "95d64326713f27b9a3b84aabfd9e70e93e13a2f0" ]
[ "climlab/radiation/nband.py" ]
[ "from __future__ import division\nfrom builtins import range\nimport numpy as np\nfrom climlab.radiation.greygas import GreyGas\nfrom climlab import constants as const\nfrom climlab.domain import domain, axis, field\nfrom copy import copy\n\n\nclass NbandRadiation(GreyGas):\n '''Process for radiative transfer.\n Solves the discretized Schwarschild two-stream equations\n with the spectrum divided into N spectral bands.\n\n Every NbandRadiation object has an attribute\n ``self.band_fraction``\n with sum(self.band_fraction) == 1\n that gives the fraction of the total beam in each band\n\n Also a dictionary\n ``self.absorber_vmr``\n that gives the volumetric mixing ratio of every absorbing gas\n on the same grid as temperature\n\n and a dictionary\n ``self.absorption_cross_section``\n that gives the absorption cross-section per unit mass for each gas\n in every spectral band\n '''\n def __init__(self, absorber_vmr=None, **kwargs):\n super(NbandRadiation, self).__init__(**kwargs)\n newinput = ['band_fraction',\n 'absorber_vmr',\n 'absorption_cross_section',\n 'cosZen',]\n self.declare_input(newinput)\n # this should be overridden by daughter classes\n self.band_fraction = np.array(1.)\n ## a dictionary of absorbing gases, in volumetric mixing ratios\n # each item should have dimensions of self.Tatm\n # Can be passed as input argument\n if absorber_vmr is None:\n absorber_vmr = {}\n self.absorber_vmr = absorber_vmr\n # a dictionary of absorption cross-sections in m**2 / kg\n # each item should have dimension... (num_channels, 1)\n self.absorption_cross_section = {}\n self.cosZen = 1. # cosine of the average zenith angle\n dp = self.Tatm.domain.lev.delta\n self.mass_per_layer = dp * const.mb_to_Pa / const.g\n self.albedo_sfc = np.ones_like(self.band_fraction) * self.albedo_sfc\n\n @property\n def band_fraction(self):\n return self._band_fraction\n @band_fraction.setter\n def band_fraction(self, value):\n self.num_channels = value.size\n # abstract axis for channels\n ax = axis.Axis(num_points=self.num_channels)\n self.channel_ax = {'channel': ax}\n dom = domain._Domain(axes=self.channel_ax)\n # fraction of the total solar flux in each band:\n self._band_fraction = field.Field(value, domain=dom)\n\n def _compute_optical_path(self):\n # this will cause a problem for a model without CO2\n tau = np.zeros_like(self.absorber_vmr['CO2']*\n self.absorption_cross_section['CO2'])\n for gas, vmr in self.absorber_vmr.items():\n # convert to mass of absorber per unit total mass\n if gas == 'H2O': # H2O is stored as specific humidity, not VMR\n q = vmr\n else:\n q = vmr / (1.+vmr)\n try:\n # if this gas isn't present in absorption dictionary\n # the assumption is that there is no absorption!\n kappa = self.absorption_cross_section[gas]\n tau += q * kappa\n except: pass\n tau *= self.mass_per_layer / self.cosZen\n return tau\n\n def _compute_absorptivity(self):\n # assume that the water vapor etc is current\n optical_path = self._compute_optical_path()\n # account for finite layer depth\n absorptivity = 1. - np.exp(-optical_path)\n axes = copy(self.Tatm.domain.axes)\n # add these to the dictionary of axes\n axes.update(self.channel_ax)\n dom = domain.Atmosphere(axes=axes)\n self.absorptivity = field.Field(absorptivity, domain=dom)\n\n def _compute_emission_sfc(self):\n # need to split the total emission across the bands\n total_emission = super(NbandRadiation, self)._compute_emission_sfc()\n return self._split_channels(total_emission)\n\n def _compute_emission(self):\n # need to split the total emission across the bands\n total_emission = super(NbandRadiation, self)._compute_emission()\n band_fraction = self.band_fraction\n for n in range(self.Tatm.domain.numdims):\n band_fraction = band_fraction[:, np.newaxis]\n return total_emission * band_fraction\n\n def _compute_radiative_heating(self):\n # need to recompute transmissivities each time because\n # water vapor is changing\n self._compute_absorptivity()\n super(NbandRadiation, self)._compute_radiative_heating()\n\n def _split_channels(self, flux):\n split = np.outer(self.band_fraction, flux)\n # make sure there's a singleton dimension at the last axis (level)\n if np.size(split, axis=-1) != 1:\n split = split[..., np.newaxis]\n return split\n\n def _join_channels(self, flux):\n return np.sum(flux, axis=0)\n\n\nclass ThreeBandSW(NbandRadiation):\n def __init__(self, emissivity_sfc=0., **kwargs):\n '''A three-band mdoel for shortwave radiation.\n\n The spectral decomposition used here is largely based on the\n \"Moist Radiative-Convective Model\" by Aarnout van Delden, Utrecht University\n [email protected]\n http://www.staff.science.uu.nl/~delde102/RCM.htm\n\n Three SW channels:\n channel 0 is Hartley and Huggins band (UV, 1%, 200 - 340 nm)\n channel 1 is Chappuis band (27%, 450 - 800 nm)\n channel 2 is remaining radiation (72%)\n '''\n super(ThreeBandSW, self).__init__(emissivity_sfc=emissivity_sfc, **kwargs)\n # fraction of the total solar flux in each band:\n self.band_fraction = np.array([0.01, 0.27, 0.72])\n if 'CO2' not in self.absorber_vmr:\n self.absorber_vmr['CO2'] = 380.E-6 * np.ones_like(self.Tatm)\n if 'O3' not in self.absorber_vmr:\n self.absorber_vmr['O3'] = np.zeros_like(self.Tatm)\n if 'H2O' not in self.absorber_vmr:\n self.absorber_vmr['H2O'] = self.q\n ## absorption cross-sections in m**2 / kg\n O3 = np.array([200.E-24, 0.285E-24, 0.]) * const.Rd / const.kBoltzmann\n #self.absorption_cross_section['O3'] = np.reshape(O3,\n # (self.num_channels, 1))\n #H2O = np.array([0.002, 0.002, 0.002])\n H2O = np.array([0., 0., 0.001])\n for n in range(self.Tatm.domain.numdims):\n H2O = H2O[:, np.newaxis]\n O3 = O3[:, np.newaxis]\n self.absorption_cross_section['O3'] = O3\n self.absorption_cross_section['H2O'] = H2O\n #self.absorption_cross_section['H2O'] = np.reshape(H2O,\n # (self.num_channels, 1))\n self.absorption_cross_section['CO2'] = \\\n np.zeros_like(self.absorption_cross_section['O3'])\n self.cosZen = 0.5 # cosine of the average solar zenith angle\n\n @property\n def emissivity(self):\n # This ensures that emissivity is always zero for shortwave classes\n return np.zeros_like(self.absorptivity)\n\n\nclass FourBandSW(NbandRadiation):\n # The most recent RMCM program uses a four-channel SW model\n # this is probably a better way to do it... distinguishes between\n # visible band with no absorption and near-infrared with weak H2O absorption\n # But this needs some tuning and better documentation\n def __init__(self, emissivity_sfc=0., **kwargs):\n '''A four-band mdoel for shortwave radiation.\n\n The spectral decomposition used here is largely based on the\n \"Moist Radiative-Convective Model\" by Aarnout van Delden, Utrecht University\n [email protected]\n http://www.staff.science.uu.nl/~delde102/RCM.htm\n\n Four SW channels:\n channel 0 is Hartley and Huggins band (UV, 6%, <340 nm)\n channel 1 is part of visible with no O3 absorption (14%, 340 - 500 nm)\n channel 2 is Chappuis band (27%, 500 - 700 nm)\n channel 3 is near-infrared (53%, > 700 nm)\n '''\n super(FourBandSW, self).__init__(emissivity_sfc=emissivity_sfc, **kwargs)\n # fraction of the total solar flux in each band:\n self.band_fraction = np.array([0.06, 0.14, 0.27, 0.53])\n if 'CO2' not in self.absorber_vmr:\n self.absorber_vmr['CO2'] = 380.E-6 * np.ones_like(self.Tatm)\n if 'O3' not in self.absorber_vmr:\n self.absorber_vmr['O3'] = np.zeros_like(self.Tatm)\n if 'H2O' not in self.absorber_vmr:\n self.absorber_vmr['H2O'] = self.q\n ## absorption cross-sections in m**2 / kg\n O3 = np.array([200.E-24, 0., 0.285E-24, 0.]) * const.Rd / const.kBoltzmann\n #self.absorption_cross_section['O3'] = np.reshape(O3,\n # (self.num_channels, 1))\n H2O = np.array([0., 0., 0., 0.0012])\n for n in range(self.Tatm.domain.numdims):\n H2O = H2O[:, np.newaxis]\n O3 = O3[:, np.newaxis]\n self.absorption_cross_section['O3'] = O3\n self.absorption_cross_section['H2O'] = H2O\n #self.absorption_cross_section['H2O'] = np.reshape(H2O,\n # (self.num_channels, 1))\n self.absorption_cross_section['CO2'] = \\\n np.zeros_like(self.absorption_cross_section['O3'])\n self.cosZen = 0.5 # cosine of the average solar zenith angle\n\n @property\n def emissivity(self):\n # This ensures that emissivity is always zero for shortwave classes\n return np.zeros_like(self.absorptivity)\n\n\n\nclass FourBandLW(NbandRadiation):\n def __init__(self, **kwargs):\n '''Closely following SPEEDY / MITgcm longwave model\n band 0 is window region (between 8.5 and 11 microns)\n band 1 is CO2 channel (the band of strong absorption by CO2 around 15 microns)\n band 2 is weak H2O channel (aggregation of spectral regions with weak to moderate absorption by H2O)\n band 3 is strong H2O channel (aggregation of regions with strong absorption by H2O)\n '''\n super(FourBandLW, self).__init__(**kwargs)\n # SPEEDY uses an approximation to the Planck function\n # and the band fraction for every emission is calculated from\n # its current temperature\n # Here for simoplicity we'll just set an average band_fraction\n # and hold it fixed\n Tarray = np.linspace(-30, 30) + 273.15\n self.band_fraction = np.mean(SPEEDY_band_fraction(Tarray), axis=1)\n\n # defaults from MITgcm/aim:\n # these are layer absorptivities per dp = 10^5 Pa\n # the water vapor terms are expressed for dq = 1 g/kg\n ABLWIN = 0.7\n ABLCO2 = 4.0\n ABLWV1 = 0.7\n ABLWV2 = 50.0\n # I'm going to assume that the absorption in window region is by O3.\n # not sure if this makes any sense... maybe it should be zero\n O3 = np.array([ABLWIN, 0., 0., 0.]) / 1E5 * const.g / 5E-6\n self.absorption_cross_section['O3'] = np.reshape(O3,\n (self.num_channels, 1))\n # the CO2 mixing ratio for which SPEEDY / MITgcm is tuned...\n # not clear what this number should be\n AIMCO2 = 380E-6\n CO2 = np.array([0., ABLCO2, 0., 0.]) / 1E5 * const.g / AIMCO2\n #self.absorption_cross_section['CO2'] = np.reshape(CO2,\n # (self.num_channels, 1))\n # Need to multiply by 1E3 for H2O fields because we use kg/kg for mixing ratio\n H2O = np.array([0., 0., ABLWV1, ABLWV2]) / 1E5 * const.g * 1E3\n #self.absorption_cross_section['H2O'] = np.reshape(H2O,\n # (self.num_channels, 1))\n for n in range(self.Tatm.domain.numdims):\n CO2 = CO2[:, np.newaxis]\n O3 = O3[:, np.newaxis]\n H2O = H2O[:, np.newaxis]\n self.absorption_cross_section.update({'CO2': CO2, 'H2O': H2O, 'O3': O3})\n if 'CO2' not in self.absorber_vmr:\n self.absorber_vmr['CO2'] = 380.E-6 * np.ones_like(self.Tatm)\n if 'O3' not in self.absorber_vmr:\n self.absorber_vmr['O3'] = np.zeros_like(self.Tatm)\n if 'H2O' not in self.absorber_vmr:\n self.absorber_vmr['H2O'] = self.q\n\n\ndef SPEEDY_band_fraction(T):\n '''Python / numpy implementation of the formula used by SPEEDY and MITgcm\n to partition longwave emissions into 4 spectral bands.\n\n Input: temperature in Kelvin\n\n returns: a four-element array of band fraction\n\n Reproducing here the FORTRAN code from MITgcm/pkg/aim_v23/phy_radiat.F\n\n .. code-block:: fortran\n\n \t EPS3=0.95 _d 0\n\n \t DO JTEMP=200,320\n \t FBAND(JTEMP,0)= EPSLW\n \t FBAND(JTEMP,2)= 0.148 _d 0 - 3.0 _d -6 *(JTEMP-247)**2\n \t FBAND(JTEMP,3)=(0.375 _d 0 - 5.5 _d -6 *(JTEMP-282)**2)*EPS3\n \t FBAND(JTEMP,4)= 0.314 _d 0 + 1.0 _d -5 *(JTEMP-315)**2\n \t FBAND(JTEMP,1)= 1. _d 0 -(FBAND(JTEMP,0)+FBAND(JTEMP,2)\n \t & +FBAND(JTEMP,3)+FBAND(JTEMP,4))\n \t ENDDO\n\n \t DO JB=0,NBAND\n \t DO JTEMP=lwTemp1,199\n \t FBAND(JTEMP,JB)=FBAND(200,JB)\n \t ENDDO\n \t DO JTEMP=321,lwTemp2\n \t FBAND(JTEMP,JB)=FBAND(320,JB)\n \t ENDDO\n \t ENDDO\n\n '''\n # EPSLW is the fraction of longwave emission that goes directly to space\n # It is set to zero by default in MITgcm code. We won't use it here.\n Tarray = np.array(T)\n Tarray = np.minimum(Tarray, 320.)\n Tarray = np.maximum(Tarray, 200.)\n num_band = 4\n dims = [num_band]\n dims.extend(Tarray.shape)\n FBAND = np.zeros(dims)\n\n EPS2=0.95\n FBAND[1,:] = 0.148 - 3.0E-6 *(T-247.)**2\n FBAND[2,:] = (0.375 - 5.5E-6 *(T-282.)**2)*EPS2\n FBAND[3,:] = 0.314 + 1.0E-5 *(T-315.)**2\n FBAND[0,:] = 1. - np.sum(FBAND, axis=0)\n return FBAND\n" ]
[ [ "numpy.maximum", "numpy.minimum", "numpy.ones_like", "numpy.linspace", "numpy.reshape", "numpy.size", "numpy.zeros_like", "numpy.exp", "numpy.outer", "numpy.array", "numpy.zeros", "numpy.sum" ] ]
cpearce/scikit-ika
[ "01f90ac3e7963e4d05f73316a7d14de0d8f08d1e" ]
[ "skika/third_party/denstream/Demonstration.py" ]
[ "import numpy as np\n\n\nclass MicroCluster:\n def __init__(self, lambd):\n self.decay_factor = 2 ** (-lambd)\n self.mean = 0\n self.variance = 0\n self.sum_of_weights = 0\n\n def insert_sample(self, sample, weight):\n if self.sum_of_weights != 0:\n # Update sum of weights\n old_sum_of_weights = self.sum_of_weights\n new_sum_of_weights = old_sum_of_weights * self.decay_factor + weight\n\n # Update mean\n old_mean = self.mean\n new_mean = old_mean + \\\n (weight / new_sum_of_weights) * (sample - old_mean)\n\n # Update variance\n old_variance = self.variance\n new_variance = old_variance * ((new_sum_of_weights - weight)\n / old_sum_of_weights) \\\n + weight * (sample - new_mean) * (sample - old_mean)\n\n self.mean = new_mean\n self.variance = new_variance\n self.sum_of_weights = new_sum_of_weights\n else:\n self.mean = sample\n self.sum_of_weights = weight\n\n def radius(self):\n if self.sum_of_weights > 0:\n return np.linalg.norm(np.sqrt(self.variance / self.sum_of_weights))\n else:\n return float('nan')\n\n def center(self):\n return self.mean\n\nclass MicroClusterBad:\n def __init__(self, lambd):\n self.decay_factor = 2 ** (-lambd)\n self.linear_sum = 0\n self.squared_sum = 0\n self.sum_of_weights = 0\n\n def insert_sample(self, sample, weight):\n # Update sum of weights\n self.sum_of_weights = self.sum_of_weights * self.decay_factor + weight\n\n # Update linear sum\n self.linear_sum *= self.decay_factor\n self.linear_sum += weight * sample\n\n # Update squared sum\n self.squared_sum *= self.decay_factor\n self.squared_sum += weight * sample ** 2\n\n\n def radius(self):\n if self.sum_of_weights > 0:\n return np.linalg.norm(np.sqrt(self.squared_sum / self.sum_of_weights\n - (self.linear_sum /\n self.sum_of_weights) ** 2))\n else:\n return float('nan')\n\n def center(self):\n return self.linear_sum / self.sum_of_weights\n\nmc1 = MicroCluster(1)\nmc2 = MicroClusterBad(1)\n\n# The bad micro cluster works fine for small numbers\nfor i in range(0, 100):\n mc1.insert_sample(np.array([i, i]), i)\n mc2.insert_sample(np.array([i, i]), i)\n print(f\"Good MicroCluster radius is {mc1.radius()}\")\n print(f\"Good MicroCluster center is {mc1.center()}\")\n print(f\"Bad MicroCluster radius is {mc2.radius()}\")\n print(f\"Bad MicroCluster center is {mc2.center()}\")\n print(\"\")\n\n# However, it fails for large numbers\nfor i in range(10000000000, 10000000100):\n mc1.insert_sample(np.array([i, i]), i)\n mc2.insert_sample(np.array([i, i]), i)\n print(f\"Good MicroCluster radius is {mc1.radius()}\")\n print(f\"Good MicroCluster center is {mc1.center()}\")\n print(f\"Bad MicroCluster radius is {mc2.radius()}\")\n print(f\"Bad MicroCluster center is {mc2.center()}\")\n print(\"\")\n" ]
[ [ "numpy.array", "numpy.sqrt" ] ]
stvreumi/ray
[ "40c4148d4f065802f7888017ef26c2213b45341b" ]
[ "python/ray/rllib/models/catalog.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport gym\nimport numpy as np\nimport tensorflow as tf\nfrom functools import partial\n\nfrom ray.tune.registry import RLLIB_MODEL, RLLIB_PREPROCESSOR, \\\n _global_registry\n\nfrom ray.rllib.env.async_vector_env import _ServingEnvToAsync\nfrom ray.rllib.env.serving_env import ServingEnv\nfrom ray.rllib.env.vector_env import VectorEnv\nfrom ray.rllib.models.action_dist import (\n Categorical, Deterministic, DiagGaussian, MultiActionDistribution,\n squash_to_range)\nfrom ray.rllib.models.preprocessors import get_preprocessor\nfrom ray.rllib.models.fcnet import FullyConnectedNetwork\nfrom ray.rllib.models.visionnet import VisionNetwork\nfrom ray.rllib.models.lstm import LSTM\n\n# __sphinx_doc_begin__\nMODEL_DEFAULTS = {\n # === Built-in options ===\n # Filter config. List of [out_channels, kernel, stride] for each filter\n \"conv_filters\": None,\n # Nonlinearity for built-in convnet\n \"conv_activation\": \"relu\",\n # Nonlinearity for fully connected net (tanh, relu)\n \"fcnet_activation\": \"tanh\",\n # Number of hidden layers for fully connected net\n \"fcnet_hiddens\": [256, 256],\n # For control envs, documented in ray.rllib.models.Model\n \"free_log_std\": False,\n # Whether to squash the action output to space range\n \"squash_to_range\": False,\n\n # == LSTM ==\n # Whether to wrap the model with a LSTM\n \"use_lstm\": False,\n # Max seq len for training the LSTM, defaults to 20\n \"max_seq_len\": 20,\n # Size of the LSTM cell\n \"lstm_cell_size\": 256,\n # Whether to feed a_{t-1}, r_{t-1} to LSTM\n \"lstm_use_prev_action_reward\": False,\n\n # == Atari ==\n # Whether to enable framestack for Atari envs\n \"framestack\": True,\n # Final resized frame dimension\n \"dim\": 84,\n # Pytorch conv requires images to be channel-major\n \"channel_major\": False,\n # (deprecated) Converts ATARI frame to 1 Channel Grayscale image\n \"grayscale\": False,\n # (deprecated) Changes frame to range from [-1, 1] if true\n \"zero_mean\": True,\n\n # === Options for custom models ===\n # Name of a custom preprocessor to use\n \"custom_preprocessor\": None,\n # Name of a custom model to use\n \"custom_model\": None,\n # Extra options to pass to the custom classes\n \"custom_options\": {},\n}\n\n# __sphinx_doc_end__\n\n\nclass ModelCatalog(object):\n \"\"\"Registry of models, preprocessors, and action distributions for envs.\n\n Examples:\n >>> prep = ModelCatalog.get_preprocessor(env)\n >>> observation = prep.transform(raw_observation)\n\n >>> dist_cls, dist_dim = ModelCatalog.get_action_dist(\n env.action_space, {})\n >>> model = ModelCatalog.get_model(inputs, dist_dim, options)\n >>> dist = dist_cls(model.outputs)\n >>> action = dist.sample()\n \"\"\"\n\n @staticmethod\n def get_action_dist(action_space, config, dist_type=None):\n \"\"\"Returns action distribution class and size for the given action space.\n\n Args:\n action_space (Space): Action space of the target gym env.\n config (dict): Optional model config.\n dist_type (str): Optional identifier of the action distribution.\n\n Returns:\n dist_class (ActionDistribution): Python class of the distribution.\n dist_dim (int): The size of the input vector to the distribution.\n \"\"\"\n\n config = config or MODEL_DEFAULTS\n if isinstance(action_space, gym.spaces.Box):\n if dist_type is None:\n dist = DiagGaussian\n if config.get(\"squash_to_range\"):\n dist = squash_to_range(dist, action_space.low,\n action_space.high)\n return dist, action_space.shape[0] * 2\n elif dist_type == \"deterministic\":\n return Deterministic, action_space.shape[0]\n elif isinstance(action_space, gym.spaces.Discrete):\n return Categorical, action_space.n\n elif isinstance(action_space, gym.spaces.Tuple):\n child_dist = []\n input_lens = []\n for action in action_space.spaces:\n dist, action_size = ModelCatalog.get_action_dist(\n action, config)\n child_dist.append(dist)\n input_lens.append(action_size)\n return partial(\n MultiActionDistribution,\n child_distributions=child_dist,\n action_space=action_space,\n input_lens=input_lens), sum(input_lens)\n\n raise NotImplementedError(\"Unsupported args: {} {}\".format(\n action_space, dist_type))\n\n @staticmethod\n def get_action_placeholder(action_space):\n \"\"\"Returns an action placeholder that is consistent with the action space\n\n Args:\n action_space (Space): Action space of the target gym env.\n Returns:\n action_placeholder (Tensor): A placeholder for the actions\n \"\"\"\n\n if isinstance(action_space, gym.spaces.Box):\n return tf.placeholder(\n tf.float32, shape=(None, action_space.shape[0]), name=\"action\")\n elif isinstance(action_space, gym.spaces.Discrete):\n return tf.placeholder(tf.int64, shape=(None, ), name=\"action\")\n elif isinstance(action_space, gym.spaces.Tuple):\n size = 0\n all_discrete = True\n for i in range(len(action_space.spaces)):\n if isinstance(action_space.spaces[i], gym.spaces.Discrete):\n size += 1\n else:\n all_discrete = False\n size += np.product(action_space.spaces[i].shape)\n return tf.placeholder(\n tf.int64 if all_discrete else tf.float32,\n shape=(None, size),\n name=\"action\")\n else:\n raise NotImplementedError(\"action space {}\"\n \" not supported\".format(action_space))\n\n @staticmethod\n def get_model(input_dict,\n obs_space,\n num_outputs,\n options,\n state_in=None,\n seq_lens=None):\n \"\"\"Returns a suitable model conforming to given input and output specs.\n\n Args:\n input_dict (dict): Dict of input tensors to the model, including\n the observation under the \"obs\" key.\n obs_space (Space): Observation space of the target gym env.\n num_outputs (int): The size of the output vector of the model.\n options (dict): Optional args to pass to the model constructor.\n state_in (list): Optional RNN state in tensors.\n seq_in (Tensor): Optional RNN sequence length tensor.\n\n Returns:\n model (Model): Neural network model.\n \"\"\"\n\n assert isinstance(input_dict, dict)\n options = options or MODEL_DEFAULTS\n model = ModelCatalog._get_model(input_dict, obs_space, num_outputs,\n options, state_in, seq_lens)\n\n if options.get(\"use_lstm\"):\n copy = dict(input_dict)\n copy[\"obs\"] = model.last_layer\n model = LSTM(copy, obs_space, num_outputs, options, state_in,\n seq_lens)\n\n return model\n\n @staticmethod\n def _get_model(input_dict, obs_space, num_outputs, options, state_in,\n seq_lens):\n if options.get(\"custom_model\"):\n model = options[\"custom_model\"]\n print(\"Using custom model {}\".format(model))\n return _global_registry.get(RLLIB_MODEL, model)(\n input_dict,\n obs_space,\n num_outputs,\n options,\n state_in=state_in,\n seq_lens=seq_lens)\n\n obs_rank = len(input_dict[\"obs\"].shape) - 1\n\n if obs_rank > 1:\n return VisionNetwork(input_dict, obs_space, num_outputs, options)\n\n return FullyConnectedNetwork(input_dict, obs_space, num_outputs,\n options)\n\n @staticmethod\n def get_torch_model(input_shape, num_outputs, options=None):\n \"\"\"Returns a PyTorch suitable model. This is currently only supported\n in A3C.\n\n Args:\n input_shape (tuple): The input shape to the model.\n num_outputs (int): The size of the output vector of the model.\n options (dict): Optional args to pass to the model constructor.\n\n Returns:\n model (Model): Neural network model.\n \"\"\"\n from ray.rllib.models.pytorch.fcnet import (FullyConnectedNetwork as\n PyTorchFCNet)\n from ray.rllib.models.pytorch.visionnet import (VisionNetwork as\n PyTorchVisionNet)\n\n options = options or MODEL_DEFAULTS\n if options.get(\"custom_model\"):\n model = options[\"custom_model\"]\n print(\"Using custom torch model {}\".format(model))\n return _global_registry.get(RLLIB_MODEL, model)(\n input_shape, num_outputs, options)\n\n # TODO(alok): fix to handle Discrete(n) state spaces\n obs_rank = len(input_shape) - 1\n\n if obs_rank > 1:\n return PyTorchVisionNet(input_shape, num_outputs, options)\n\n # TODO(alok): overhaul PyTorchFCNet so it can just\n # take input shape directly\n return PyTorchFCNet(input_shape[0], num_outputs, options)\n\n @staticmethod\n def get_preprocessor(env, options=None):\n \"\"\"Returns a suitable processor for the given environment.\n\n Args:\n env (gym.Env|VectorEnv|ServingEnv): The environment to wrap.\n options (dict): Options to pass to the preprocessor.\n\n Returns:\n preprocessor (Preprocessor): Preprocessor for the env observations.\n \"\"\"\n options = options or MODEL_DEFAULTS\n for k in options.keys():\n if k not in MODEL_DEFAULTS:\n raise Exception(\"Unknown config key `{}`, all keys: {}\".format(\n k, list(MODEL_DEFAULTS)))\n\n if options.get(\"custom_preprocessor\"):\n preprocessor = options[\"custom_preprocessor\"]\n print(\"Using custom preprocessor {}\".format(preprocessor))\n return _global_registry.get(RLLIB_PREPROCESSOR, preprocessor)(\n env.observation_space, options)\n\n preprocessor = get_preprocessor(env.observation_space)\n return preprocessor(env.observation_space, options)\n\n @staticmethod\n def get_preprocessor_as_wrapper(env, options=None):\n \"\"\"Returns a preprocessor as a gym observation wrapper.\n\n Args:\n env (gym.Env|VectorEnv|ServingEnv): The environment to wrap.\n options (dict): Options to pass to the preprocessor.\n\n Returns:\n env (RLlib env): Wrapped environment\n \"\"\"\n\n options = options or MODEL_DEFAULTS\n preprocessor = ModelCatalog.get_preprocessor(env, options)\n if isinstance(env, gym.Env):\n return _RLlibPreprocessorWrapper(env, preprocessor)\n elif isinstance(env, VectorEnv):\n return _RLlibVectorPreprocessorWrapper(env, preprocessor)\n elif isinstance(env, ServingEnv):\n return _ServingEnvToAsync(env, preprocessor)\n else:\n raise ValueError(\"Don't know how to wrap {}\".format(env))\n\n @staticmethod\n def register_custom_preprocessor(preprocessor_name, preprocessor_class):\n \"\"\"Register a custom preprocessor class by name.\n\n The preprocessor can be later used by specifying\n {\"custom_preprocessor\": preprocesor_name} in the model config.\n\n Args:\n preprocessor_name (str): Name to register the preprocessor under.\n preprocessor_class (type): Python class of the preprocessor.\n \"\"\"\n _global_registry.register(RLLIB_PREPROCESSOR, preprocessor_name,\n preprocessor_class)\n\n @staticmethod\n def register_custom_model(model_name, model_class):\n \"\"\"Register a custom model class by name.\n\n The model can be later used by specifying {\"custom_model\": model_name}\n in the model config.\n\n Args:\n model_name (str): Name to register the model under.\n model_class (type): Python class of the model.\n \"\"\"\n _global_registry.register(RLLIB_MODEL, model_name, model_class)\n\n\nclass _RLlibPreprocessorWrapper(gym.ObservationWrapper):\n \"\"\"Adapts a RLlib preprocessor for use as an observation wrapper.\"\"\"\n\n def __init__(self, env, preprocessor):\n super(_RLlibPreprocessorWrapper, self).__init__(env)\n self.preprocessor = preprocessor\n self.observation_space = preprocessor.observation_space\n\n def observation(self, observation):\n return self.preprocessor.transform(observation)\n\n\nclass _RLlibVectorPreprocessorWrapper(VectorEnv):\n \"\"\"Preprocessing wrapper for vector envs.\"\"\"\n\n def __init__(self, env, preprocessor):\n self.env = env\n self.prep = preprocessor\n self.action_space = env.action_space\n self.observation_space = preprocessor.observation_space\n self.num_envs = env.num_envs\n\n def vector_reset(self):\n return [self.prep.transform(obs) for obs in self.env.vector_reset()]\n\n def reset_at(self, index):\n return self.prep.transform(self.env.reset_at(index))\n\n def vector_step(self, actions):\n obs, rewards, dones, infos = self.env.vector_step(actions)\n obs = [self.prep.transform(o) for o in obs]\n return obs, rewards, dones, infos\n\n def get_unwrapped(self):\n return self.env.get_unwrapped()\n" ]
[ [ "numpy.product", "tensorflow.placeholder" ] ]
julesberman/chunkflow
[ "c6af0d036bc2f308c64c591d49c94c414c569241" ]
[ "chunkflow/flow/view.py" ]
[ "import numpy as np\n\nfrom cloudvolume import view, hyperview\nfrom .base import OperatorBase\n\n\nclass ViewOperator(OperatorBase):\n def __init__(self, name: str = 'view'):\n super().__init__(name=name)\n\n def __call__(self, chunk, seg=None):\n \"\"\"view chunk using cloudvolume view\"\"\"\n # cloudvolume use fortran order\n chunk = chunk.transpose()\n if seg:\n seg = seg.transpose()\n hyperview(chunk, seg)\n elif np.issubdtype(chunk.dtype,\n np.floating) or chunk.dtype == np.uint8:\n # this is an image\n view(chunk)\n else:\n view(chunk, segmentation=True)\n" ]
[ [ "numpy.issubdtype" ] ]
kctsiolis/RepDistiller
[ "ce88f6e53fcf8ef81c5bac2d20ad31628dd279ac" ]
[ "distiller_zoo/SimBased.py" ]
[ "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass SimBasedLoss(nn.Module):\n def __init__(self):\n super(SimBasedLoss, self).__init__()\n\n def forward(self, y_s, y_t):\n y_s = F.normalize(y_s, p=2, dim=1)\n y_t = F.normalize(y_t, p=2, dim=1)\n student_sims = torch.matmul(y_s, y_s.T)\n teacher_sims = torch.matmul(y_t, y_t.T)\n\n loss = F.mse_loss(student_sims, teacher_sims)\n return loss" ]
[ [ "torch.nn.functional.normalize", "torch.matmul", "torch.nn.functional.mse_loss" ] ]
fierval/EigenSiNN
[ "4ed01b47d4b13b9c9e29622475d821868499942d" ]
[ "python/layers/relu3d.py" ]
[ "import os\nfrom utils import to_cpp\nimport commondata4d as cd\nimport torch.nn as nn\n\n############ ReLU ############################\ninp = cd.inp_with_neg\nfakeloss = cd.convloss\n\nrl = nn.ReLU()\noutput = rl(inp)\noutput.backward(cd.inp)\nprint(f\"RELU output: {to_cpp(output)}\")\nprint(f\"RELU grad: {to_cpp(inp.grad.data)}\")\n\n############# Leaky ReLU #####################\ninp.grad.zero_()\nlrl = nn.LeakyReLU(negative_slope=1e-2)\noutput = lrl(inp)\noutput.backward(cd.inp)\n\nprint(f\"LeakyRELU output: {to_cpp(output)}\")\nprint(f\"LeakyRELU grad: {to_cpp(inp.grad.data)}\")\n" ]
[ [ "torch.nn.ReLU", "torch.nn.LeakyReLU" ] ]
Oadegbite/OpenCanadaData
[ "232d71d5721baf4eee848387c4addc9d7b00bc89" ]
[ "tests/TestDataset.py" ]
[ "import unittest\nfrom ocandata.repo import IdAndLocale, Dataset\nimport pandas as pd\n\npd.set_option(\"display.max_colwidth\", 80)\n\n\nclass DatasetTestCase(unittest.TestCase):\n def test_create_dataset(self):\n dataset = IdAndLocale(id=\"winter\")\n self.assertEqual(\"winter\", dataset.id)\n\n dataset = IdAndLocale(id=\"winter\", locale=\"en\")\n self.assertEqual(\"winter\", dataset.id)\n self.assertEqual(\"en\", dataset.locale)\n\n def test_locale(self):\n dataset = IdAndLocale(id=\"winter\", locale=\"en\")\n self.assertEqual(\"en\", dataset.locale)\n\n dataset = IdAndLocale(id=\"winter\", locale=\"fr\")\n self.assertEqual(\"fr\", dataset.locale)\n\n dataset = IdAndLocale(id=\"winter\")\n self.assertEqual(\"en\", dataset.locale)\n\n def test_dataset_path(self):\n dataset = IdAndLocale(id=\"winter\", locale=\"en\")\n self.assertEqual(\"en/dataset/winter\", dataset.path())\n\n def test_inventory_dataset(self):\n COLS = [\"portal_url_en\", \"portal_url_en\", \"title_en\"]\n inventory = pd.read_csv(\"../data/inventory.csv\", usecols=COLS)\n print(inventory[COLS])\n\n def test_parse_dataset_url(self):\n url = \"https://open.canada.ca/data/en/dataset/6adaeb1f-438b-4d74-b72b-d1b554f3a316\"\n dataset = IdAndLocale.parse(url)\n print(dataset)\n\n def test_dataset_from_csv(self):\n inventory = pd.read_csv(\"../data/inventory.csv\")\n ids = inventory.apply(\n lambda d: Dataset(d.ref_number, d.title_en, d.description_en), axis=1\n )\n print(ids)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" ]
[ [ "pandas.set_option", "pandas.read_csv" ] ]
Lavoiec/Project-Overlay-Data-Process
[ "e5c03db8567b085e3c8ca5e317b53474d70ddaa5" ]
[ "VectorSpaceModel.py" ]
[ "import pandas as pd\nimport utility_funcs as uf\nimport ProjectOverlayDataProcess as data\nimport code\n\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import Normalizer\n\ndef import_data():\n return data.import_dataframe(\"relevantgroups\"), data.import_dataframe(\"mandates\")\n\ndef groups_to_vector(df, columns_to_clean):\n \"\"\"\n df: Dataframe\n columns_to_clean: List of columns inside df\n \"\"\"\n groups_vector = uf.text_cleaning_pipe(df[columns_to_clean].dropna())\n groups_vector = (groups_vector\n .dropna()\n .drop_duplicates()\n .loc[(groups_vector.name != '') & (groups_vector.description != '')]\n )\n\n return groups_vector\n\ndef process_mandates(df, titlecol, descriptioncol ):\n mandates_vector = (df[[titlecol, descriptioncol]]\n .drop_duplicates()\n .groupby(titlecol)[descriptioncol]\n .apply(list)\n .apply(lambda x: ' '.join(x))\n .reset_index())\n\n return mandates_vector\n\n\ndef create_vectors(group_data, mandate_data):\n return list(group_data) + list(mandate_data)\n\ndef fit_transform_tfidf(data):\n \"\"\"\n The main transforming functions for the Vector Space Model\n \"\"\"\n #source https://github.com/chrisjmccormick/LSA_Classification/blob/master/inspect_LSA.py\n # Tfidf vectorizer:\n # - Strips out “stop words”\n # - Filters out terms that occur in more than half of the docs (max_df=0.5)\n # - Filters out terms that occur in only one document (min_df=2).\n # - Selects the 10,000 most frequently occuring words in the corpus.\n # - Normalizes the vector (L2 norm of 1.0) to normalize the effect of \n # document length on the tf-idf values. \n vectorizer = TfidfVectorizer(max_df=0.5, max_features=10000,\n min_df=2, stop_words='english',\n use_idf=True)\n # Build the tfidf vectorizer from the training data (\"fit\"), and apply it \n # (\"transform\").\n vectorized_matrix = vectorizer.fit_transform(data).toarray()\n # Project the tfidf vectors onto the first N principal components.\n # Though this is significantly fewer features than the original tfidf vector,\n # they are stronger features, and the accuracy is higher.\n # make_pipeline is a wrapper around the class that allows you to compose\n # transformers and estimators without specifying a name for each one. Could be\n # written as two seperate parts (see example in https://signal-to-noise.xyz/post/sklearn-pipeline/)\n # but make_pipeline improves readability and clarity\n svd = TruncatedSVD(100)\n lsa = make_pipeline(svd, Normalizer(copy=False)) \n # Run SVD on the training data, then project the training data.\n tf_matrix = (lsa.fit_transform(vectorized_matrix))\n return tf_matrix\n\n\ndef create_cosine_similarity_dataframe(data, column_names):\n \n similarity_matrix = cosine_similarity(data)\n similarity_df = pd.DataFrame(similarity_matrix)\n\n if isinstance(column_names, list):\n column_names = pd.Series(column_names)\n\n similarity_df.columns = column_names\n similarity_df.index = column_names\n \n return similarity_df\n\n\n# Running the file\ndef main():\n groups, mandates = import_data()\n\n groups = data.process_groups_for_vsm(groups, description_min = 10)\n\n groups_vector = groups_to_vector(groups, ['guid', 'name', 'description'])\n\n mandates_vector = process_mandates(mandates, 'Priority', 'words')\n\n names_vectors = create_vectors(groups_vector.guid, mandates_vector.Priority)\n \n desc_vectors = create_vectors(groups_vector.description, mandates_vector.words)\n\n tf_idf_matrix = fit_transform_tfidf(desc_vectors)\n\n similarity_dataframe = create_cosine_similarity_dataframe(tf_idf_matrix, names_vectors)\n\n similarity_dataframe.to_csv(\"cosine_similarities.csv\")\n\nif __name__ == \"__main__\":\n\n main()\n code.interact(local=locals())\n" ]
[ [ "sklearn.decomposition.TruncatedSVD", "pandas.Series", "sklearn.metrics.pairwise.cosine_similarity", "pandas.DataFrame", "sklearn.preprocessing.Normalizer", "sklearn.feature_extraction.text.TfidfVectorizer" ] ]
lcopey/node_editor
[ "04d56ae4c7f2149e46903d5dd2e46f3906ef69e6" ]
[ "code_samples/combobox_header.py" ]
[ "from PyQt5 import QtCore, QtWidgets\nfrom PyQt5.QtCore import QEvent, QObject\nimport numpy as np\n\n\nclass HeaderViewFilter(QObject):\n def __init__(self, header, parent=None, *args):\n super(HeaderViewFilter, self).__init__(parent, *args)\n self.header = header\n\n def eventFilter(self, object, event):\n if event.type() == QEvent.MouseMove:\n logicalIndex = self.header.logicalIndexAt(event.pos())\n print(logicalIndex)\n\n\nclass HorizontalHeader(QtWidgets.QHeaderView):\n def __init__(self, values, parent=None):\n super(HorizontalHeader, self).__init__(QtCore.Qt.Horizontal, parent)\n self.setSectionsMovable(True)\n # self.setStretchLastSection(True)\n self._padding = 4\n self.line_edits = []\n self.sectionResized.connect(self.handleSectionResized)\n self.sectionMoved.connect(self.handleSectionMoved)\n self.setSectionsMovable(True)\n self.setSectionsClickable(True)\n\n self.setSortIndicatorShown(True)\n\n # try:\n # self.evenFilter = HeaderViewFilter(self)\n # self.setMouseTracking(True)\n #\n # self.installEventFilter(self.evenFilter)\n # except Exception as e:\n # print(e)\n\n def showEvent(self, event):\n for i in range(self.count()):\n if i < len(self.line_edits):\n edit = self.line_edits[i]\n edit.clear()\n edit.addItems([\"Variable\", \"Timestamp\"])\n else:\n edit = QtWidgets.QLineEdit(self)\n # dtypesCombo.setEditable(True)\n # dtypesCombo.addItems([\"Variable\", \"Timestamp\"])\n self.line_edits.append(edit)\n\n # if i == 0:\n edit.setGeometry(*self.getInnerWidgetGeometry(i))\n edit.show()\n\n if len(self.line_edits) > self.count():\n for i in range(self.count(), len(self.line_edits)):\n self.line_edits[i].deleteLater()\n\n super(HorizontalHeader, self).showEvent(event)\n\n def sizeHint(self):\n size = super().sizeHint()\n if self.line_edits:\n height = self.line_edits[0].sizeHint().height()\n size.setHeight(size.height() + height + self._padding)\n return size\n\n def getInnerWidgetGeometry(self, i):\n height = self.line_edits[i].sizeHint().height()\n return self.sectionViewportPosition(i), self.height(), self.sectionSize(i) - 5, self.height() + height\n\n def fixComboPositions(self):\n for i in range(self.count()):\n self.line_edits[i].setGeometry(*self.getInnerWidgetGeometry(i))\n\n def handleSectionResized(self, i):\n for i in range(self.count()):\n j = self.visualIndex(i)\n logical = self.logicalIndex(j)\n self.line_edits[i].setGeometry(self.sectionViewportPosition(logical), 0, self.sectionSize(logical) - 4,\n self.height())\n\n def handleSectionMoved(self, i, oldVisualIndex, newVisualIndex):\n for i in range(min(oldVisualIndex, newVisualIndex), self.count()):\n logical = self.logicalIndex(i)\n self.line_edits[i].setGeometry(self.sectionViewportPosition(logical), 0, self.sectionSize(logical) - 5,\n self.height())\n\n\nclass TableWidget(QtWidgets.QTableWidget):\n def __init__(self, *args, **kwargs):\n super(TableWidget, self).__init__(*args, **kwargs)\n header = HorizontalHeader(self)\n self.setHorizontalHeader(header)\n\n def scrollContentsBy(self, dx, dy):\n super(TableWidget, self).scrollContentsBy(dx, dy)\n if dx != 0:\n self.horizontalHeader().fixComboPositions()\n\n\nclass App(QtWidgets.QWidget):\n def __init__(self):\n super(App, self).__init__()\n self.data = np.random.rand(10, 10)\n self.createTable()\n layout = QtWidgets.QVBoxLayout(self)\n layout.addWidget(self.table)\n self.show()\n\n def createTable(self):\n self.header = []\n self.table = TableWidget(*self.data.shape)\n for i, row_values in enumerate(self.data):\n for j, value in enumerate(row_values):\n self.table.setItem(i, j, QtWidgets.QTableWidgetItem(str(value)))\n\n\nif __name__ == '__main__':\n import sys\n\n app = QtWidgets.QApplication(sys.argv)\n ex = App()\n sys.exit(app.exec_())\n" ]
[ [ "numpy.random.rand" ] ]
dthadi3/XlsxWriter
[ "f1801e82240aa9c746ce14948ef95990b83162cf" ]
[ "examples/pandas_chart_line.py" ]
[ "##############################################################################\n#\n# An example of converting a Pandas dataframe to an xlsx file with a line\n# chart using Pandas and XlsxWriter.\n#\n# Copyright 2013-2020, John McNamara, [email protected]\n#\n\nimport pandas as pd\nimport random\n\n# Create some sample data to plot.\nmax_row = 21\ncategories = ['Node 1', 'Node 2', 'Node 3', 'Node 4']\nindex_1 = range(0, max_row, 1)\nmulti_iter1 = {'index': index_1}\n\nfor category in categories:\n multi_iter1[category] = [random.randint(10, 100) for x in index_1]\n\n# Create a Pandas dataframe from the data.\nindex_2 = multi_iter1.pop('index')\ndf = pd.DataFrame(multi_iter1, index=index_2)\ndf = df.reindex(columns=sorted(df.columns))\n\n# Create a Pandas Excel writer using XlsxWriter as the engine.\nsheet_name = 'Sheet1'\nwriter = pd.ExcelWriter('pandas_chart_line.xlsx', engine='xlsxwriter')\ndf.to_excel(writer, sheet_name=sheet_name)\n\n# Access the XlsxWriter workbook and worksheet objects from the dataframe.\nworkbook = writer.book\nworksheet = writer.sheets[sheet_name]\n\n# Create a chart object.\nchart = workbook.add_chart({'type': 'line'})\n\n# Configure the series of the chart from the dataframe data.\nfor i in range(len(categories)):\n col = i + 1\n chart.add_series({\n 'name': ['Sheet1', 0, col],\n 'categories': ['Sheet1', 1, 0, max_row, 0],\n 'values': ['Sheet1', 1, col, max_row, col],\n })\n\n# Configure the chart axes.\nchart.set_x_axis({'name': 'Index'})\nchart.set_y_axis({'name': 'Value', 'major_gridlines': {'visible': False}})\n\n# Insert the chart into the worksheet.\nworksheet.insert_chart('G2', chart)\n\n# Close the Pandas Excel writer and output the Excel file.\nwriter.save()\n" ]
[ [ "pandas.DataFrame", "pandas.ExcelWriter" ] ]
serge-sans-paille/mmcv
[ "46a2916d7b4d7a597f8558b16f700a798616ec87" ]
[ "tests/test_cnn/test_conv_module.py" ]
[ "from unittest.mock import patch\n\nimport pytest\nimport torch\nimport torch.nn as nn\n\nfrom mmcv.cnn.bricks import CONV_LAYERS, ConvModule\n\n\n@CONV_LAYERS.register_module()\nclass ExampleConv(nn.Module):\n\n def __init__(self,\n in_channels,\n out_channels,\n kernel_size,\n stride=1,\n padding=0,\n dilation=1,\n groups=1,\n bias=True,\n norm_cfg=None):\n super(ExampleConv, self).__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.kernel_size = kernel_size\n self.stride = stride\n self.padding = padding\n self.dilation = dilation\n self.groups = groups\n self.bias = bias\n self.norm_cfg = norm_cfg\n self.output_padding = (0, 0, 0)\n self.transposed = False\n\n self.conv0 = nn.Conv2d(in_channels, out_channels, kernel_size)\n self.init_weights()\n\n def forward(self, x):\n x = self.conv0(x)\n return x\n\n def init_weights(self):\n nn.init.constant_(self.conv0.weight, 0)\n\n\ndef test_conv_module():\n with pytest.raises(AssertionError):\n # conv_cfg must be a dict or None\n conv_cfg = 'conv'\n ConvModule(3, 8, 2, conv_cfg=conv_cfg)\n\n with pytest.raises(AssertionError):\n # norm_cfg must be a dict or None\n norm_cfg = 'norm'\n ConvModule(3, 8, 2, norm_cfg=norm_cfg)\n\n with pytest.raises(KeyError):\n # softmax is not supported\n act_cfg = dict(type='softmax')\n ConvModule(3, 8, 2, act_cfg=act_cfg)\n\n # conv + norm + act\n conv = ConvModule(3, 8, 2, norm_cfg=dict(type='BN'))\n assert conv.with_activation\n assert hasattr(conv, 'activate')\n assert conv.with_norm\n assert hasattr(conv, 'norm')\n x = torch.rand(1, 3, 256, 256)\n output = conv(x)\n assert output.shape == (1, 8, 255, 255)\n\n # conv + act\n conv = ConvModule(3, 8, 2)\n assert conv.with_activation\n assert hasattr(conv, 'activate')\n assert not conv.with_norm\n assert not hasattr(conv, 'norm')\n x = torch.rand(1, 3, 256, 256)\n output = conv(x)\n assert output.shape == (1, 8, 255, 255)\n\n # conv\n conv = ConvModule(3, 8, 2, act_cfg=None)\n assert not conv.with_norm\n assert not hasattr(conv, 'norm')\n assert not conv.with_activation\n assert not hasattr(conv, 'activate')\n x = torch.rand(1, 3, 256, 256)\n output = conv(x)\n assert output.shape == (1, 8, 255, 255)\n\n # conv with its own `init_weights` method\n conv_module = ConvModule(\n 3, 8, 2, conv_cfg=dict(type='ExampleConv'), act_cfg=None)\n assert torch.equal(conv_module.conv.conv0.weight, torch.zeros(8, 3, 2, 2))\n\n # with_spectral_norm=True\n conv = ConvModule(3, 8, 3, padding=1, with_spectral_norm=True)\n assert hasattr(conv.conv, 'weight_orig')\n output = conv(x)\n assert output.shape == (1, 8, 256, 256)\n\n # padding_mode='reflect'\n conv = ConvModule(3, 8, 3, padding=1, padding_mode='reflect')\n assert isinstance(conv.padding_layer, nn.ReflectionPad2d)\n output = conv(x)\n assert output.shape == (1, 8, 256, 256)\n\n # non-existing padding mode\n with pytest.raises(KeyError):\n conv = ConvModule(3, 8, 3, padding=1, padding_mode='non_exists')\n\n # leaky relu\n conv = ConvModule(3, 8, 3, padding=1, act_cfg=dict(type='LeakyReLU'))\n assert isinstance(conv.activate, nn.LeakyReLU)\n output = conv(x)\n assert output.shape == (1, 8, 256, 256)\n\n # tanh\n conv = ConvModule(3, 8, 3, padding=1, act_cfg=dict(type='Tanh'))\n assert isinstance(conv.activate, nn.Tanh)\n output = conv(x)\n assert output.shape == (1, 8, 256, 256)\n\n\ndef test_bias():\n # bias: auto, without norm\n conv = ConvModule(3, 8, 2)\n assert conv.conv.bias is not None\n\n # bias: auto, with norm\n conv = ConvModule(3, 8, 2, norm_cfg=dict(type='BN'))\n assert conv.conv.bias is None\n\n # bias: False, without norm\n conv = ConvModule(3, 8, 2, bias=False)\n assert conv.conv.bias is None\n\n # bias: True, with norm\n with pytest.warns(UserWarning) as record:\n ConvModule(3, 8, 2, bias=True, norm_cfg=dict(type='BN'))\n assert len(record) == 1\n assert record[0].message.args[\n 0] == 'ConvModule has norm and bias at the same time'\n\n\ndef conv_forward(self, x):\n return x + '_conv'\n\n\ndef bn_forward(self, x):\n return x + '_bn'\n\n\ndef relu_forward(self, x):\n return x + '_relu'\n\n\n@patch('torch.nn.ReLU.forward', relu_forward)\n@patch('torch.nn.BatchNorm2d.forward', bn_forward)\n@patch('torch.nn.Conv2d.forward', conv_forward)\ndef test_order():\n\n with pytest.raises(AssertionError):\n # order must be a tuple\n order = ['conv', 'norm', 'act']\n ConvModule(3, 8, 2, order=order)\n\n with pytest.raises(AssertionError):\n # length of order must be 3\n order = ('conv', 'norm')\n ConvModule(3, 8, 2, order=order)\n\n with pytest.raises(AssertionError):\n # order must be an order of 'conv', 'norm', 'act'\n order = ('conv', 'norm', 'norm')\n ConvModule(3, 8, 2, order=order)\n\n with pytest.raises(AssertionError):\n # order must be an order of 'conv', 'norm', 'act'\n order = ('conv', 'norm', 'something')\n ConvModule(3, 8, 2, order=order)\n\n # ('conv', 'norm', 'act')\n conv = ConvModule(3, 8, 2, norm_cfg=dict(type='BN'))\n out = conv('input')\n assert out == 'input_conv_bn_relu'\n\n # ('norm', 'conv', 'act')\n conv = ConvModule(\n 3, 8, 2, norm_cfg=dict(type='BN'), order=('norm', 'conv', 'act'))\n out = conv('input')\n assert out == 'input_bn_conv_relu'\n\n # ('conv', 'norm', 'act'), activate=False\n conv = ConvModule(3, 8, 2, norm_cfg=dict(type='BN'))\n out = conv('input', activate=False)\n assert out == 'input_conv_bn'\n\n # ('conv', 'norm', 'act'), activate=False\n conv = ConvModule(3, 8, 2, norm_cfg=dict(type='BN'))\n out = conv('input', norm=False)\n assert out == 'input_conv_relu'\n" ]
[ [ "torch.nn.init.constant_", "torch.nn.Conv2d", "torch.rand", "torch.zeros" ] ]
harrisonzhu508/MVBAgg
[ "ad2781af7faffeb18ca3613f0b619461291037d2" ]
[ "src/posteriors.py" ]
[ "import tensorflow as tf\nimport gpflow\nfrom gpflow import covariances\nfrom gpflow.posteriors import IndependentPosteriorSingleOutput\nfrom gpflow.config import default_jitter\nfrom gpflow.conditionals.util import base_conditional\n\nclass MVBAggPosterior(IndependentPosteriorSingleOutput):\n def __init__(self, num_resolution, **kwargs):\n super().__init__(**kwargs)\n self.num_resolution = num_resolution\n if not isinstance(self.mean_function, gpflow.mean_functions.Zero):\n raise NotImplementedError()\n # could almost be the same as IndependentPosteriorMultiOutput ...\n \n def _conditional_aggregated_fused(\n self, data, full_cov: bool = False, full_output_cov: bool = False\n ):\n \"\"\"Used in self.fused_predict_f()\n\n data being a minibatch\n \n \"\"\"\n Kmm = covariances.Kuu(self.X_data, self.kernel, jitter=default_jitter()) # [M, M]\n Knn_agg = 0\n Kmn_agg = 0\n # same as IndependentPosteriorMultiOutput, Shared~/Shared~ branch, except for following line:\n for i in range(self.num_resolution):\n w = data[self.num_resolution + i]\n X = data[self.num_resolution * 2 + i]\n if len(tf.shape(w)) == 2 and len(tf.shape(X)) == 2:\n w = tf.expand_dims(w, axis=0)\n X = tf.expand_dims(X, axis=0)\n Knn = self.kernel.kernels[i].K(X)\n Knn = tf.einsum(\"bji, bjk -> bk\", w, Knn)\n Knn = tf.einsum(\"bij, bi -> b\", w, Knn) # (num_batch,)\n\n Kmn = self.kernel.kernels[i].K(tf.gather(self.X_data.Z, indices=self.kernel.kernels[i].active_dims, axis=1), X) \n Kmn = tf.transpose(Kmn, perm=[1,0,2]) # (num_batch x num_inducing x num_data)\n Kmn = tf.einsum(\"bij, bjk -> ib\", Kmn, w)\n\n Kmn_agg += Kmn\n Knn_agg += Knn\n\n fmean, fvar = base_conditional(\n Kmn_agg, Kmm, Knn_agg, self.q_mu, full_cov=full_cov, q_sqrt=self.q_sqrt, white=self.whiten\n ) # [N, P], [P, N, N] or [N, P]\n return self._post_process_mean_and_cov(fmean, fvar, full_cov, full_output_cov)\n\n def fused_predict_aggregated(\n self, data, full_cov: bool = False, full_output_cov: bool = False\n ):\n \"\"\"\n Computes predictive mean and (co)variance at Xnew, including mean_function\n Does not make use of caching\n \"\"\"\n mean, cov = self._conditional_aggregated_fused(\n data, full_cov=full_cov, full_output_cov=full_output_cov\n )\n return mean, cov\n\n def _conditional_aggregated_fused_i(\n self, w, X, i, full_cov: bool = False, full_output_cov: bool = False\n ):\n \"\"\"Used in self.fused_predict_f()\n\n data being a minibatch\n \n \"\"\"\n Kmm = covariances.Kuu(self.X_data, self.kernel, jitter=default_jitter()) # [M, M]\n if len(tf.shape(w)) == 2 and len(tf.shape(X)) == 2:\n w = tf.expand_dims(w, axis=0)\n X = tf.expand_dims(X, axis=0)\n Knn = self.kernel.kernels[i].K(X)\n Knn = tf.einsum(\"bji, bjk -> bk\", w, Knn)\n Knn = tf.einsum(\"bij, bi -> b\", w, Knn) # (num_batch,)\n\n Kmn = self.kernel.kernels[i].K(tf.gather(self.X_data.Z, indices=self.kernel.kernels[i].active_dims, axis=1), X) \n Kmn = tf.transpose(Kmn, perm=[1,0,2]) # (num_inducing x num_batch)\n Kmn = tf.einsum(\"bij, bjk -> ib\", Kmn, w)\n\n fmean, fvar = base_conditional(\n Kmn, Kmm, Knn, self.q_mu, full_cov=full_cov, q_sqrt=self.q_sqrt, white=self.whiten\n ) # [N, P], [P, N, N] or [N, P]\n return self._post_process_mean_and_cov(fmean, fvar, full_cov, full_output_cov)\n\n def fused_predict_aggregated_i(\n self, w, X, i, full_cov: bool = False, full_output_cov: bool = False\n ):\n \"\"\"\n Computes predictive mean and (co)variance at Xnew, including mean_function\n Does not make use of caching\n \"\"\"\n mean, cov = self._conditional_aggregated_fused_i(\n w, X, i, full_cov=full_cov, full_output_cov=full_output_cov\n )\n return mean, cov\n\n def fused_predict_f(\n self, X, full_cov: bool = False, full_output_cov: bool = False\n ):\n \"\"\"\n Computes predictive mean and (co)variance at Xnew, including mean_function\n Does not make use of caching\n \"\"\"\n mean, cov = self._conditional_fused(\n X, full_cov=full_cov, full_output_cov=full_output_cov\n )\n return mean, cov\n\n def _conditional_fused_i(\n self, Xnew, i, full_cov: bool = False, full_output_cov: bool = False\n ):\n assert len(tf.shape(Xnew)) == 2, \"Input array X has to have shape 2 (non-batched)\"\n # same as IndependentPosteriorMultiOutput, Shared~/Shared~ branch, except for following line:\n Knn = self.kernel.kernels[i].K_diag(Xnew)\n\n Kmm = covariances.Kuu(self.X_data, self.kernel, jitter=default_jitter()) # [M, M]\n Kmn = self.kernel.kernels[i].K(tf.gather(self.X_data.Z, indices=self.kernel.kernels[i].active_dims, axis=1), Xnew) \n\n fmean, fvar = base_conditional(\n Kmn, Kmm, Knn, self.q_mu, full_cov=full_cov, q_sqrt=self.q_sqrt, white=self.whiten\n ) # [N, P], [P, N, N] or [N, P]\n return self._post_process_mean_and_cov(fmean, fvar, full_cov, full_output_cov)\n\n def fused_predict_f_i(\n self, X, i, full_cov: bool = False, full_output_cov: bool = False\n ):\n \"\"\"\n Computes predictive mean and (co)variance at Xnew, including mean_function\n Does not make use of caching\n \"\"\"\n mean, cov = self._conditional_fused_i(\n X, i, full_cov=full_cov, full_output_cov=full_output_cov\n )\n return mean, cov\n\n\n\nclass VBAggPosterior(IndependentPosteriorSingleOutput):\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n if not isinstance(self.mean_function, gpflow.mean_functions.Zero):\n raise NotImplementedError()\n # could almost be the same as IndependentPosteriorMultiOutput ...\n \n def _conditional_aggregated_fused(\n self, w, X, full_cov: bool = False, full_output_cov: bool = False\n ):\n \"\"\"Used in self.fused_predict_f()\n\n data being a minibatch\n \n \"\"\"\n Kmm = covariances.Kuu(self.X_data, self.kernel, jitter=default_jitter()) # [M, M]\n if len(tf.shape(w)) == 2 and len(tf.shape(X)) == 2:\n w = tf.expand_dims(w, axis=0)\n X = tf.expand_dims(X, axis=0)\n Knn = self.kernel(X)\n Knn = tf.einsum(\"bji, bjk -> bk\", w, Knn)\n Knn = tf.einsum(\"bij, bi -> b\", w, Knn) # (num_batch,)\n\n Kmn = covariances.Kuf(self.X_data, self.kernel, X)\n Kmn = tf.transpose(Kmn, perm=[1,0,2]) # (num_inducing x num_batch)\n Kmn = tf.einsum(\"bij, bjk -> ib\", Kmn, w)\n\n fmean, fvar = base_conditional(\n Kmn, Kmm, Knn, self.q_mu, full_cov=full_cov, q_sqrt=self.q_sqrt, white=self.whiten\n ) # [N, P], [P, N, N] or [N, P]\n return self._post_process_mean_and_cov(fmean, fvar, full_cov, full_output_cov)\n\n def fused_predict_aggregated(\n self, w, X, full_cov: bool = False, full_output_cov: bool = False\n ):\n \"\"\"\n Computes predictive mean and (co)variance at Xnew, including mean_function\n Does not make use of caching\n \"\"\"\n mean, cov = self._conditional_aggregated_fused(\n w, X, full_cov=full_cov, full_output_cov=full_output_cov\n )\n return mean, cov\n\n def _conditional_aggregated_fused_i(\n self, w, X, i, full_cov: bool = False, full_output_cov: bool = False\n ):\n \"\"\"Used in self.fused_predict_f()\n\n data being a minibatch\n \n \"\"\"\n Kmm = covariances.Kuu(self.X_data, self.kernel, jitter=default_jitter()) # [M, M]\n if len(tf.shape(w)) == 2 and len(tf.shape(X)) == 2:\n w = tf.expand_dims(w, axis=0)\n X = tf.expand_dims(X, axis=0)\n Knn = self.kernel.kernels[i].K(X)\n Knn = tf.einsum(\"bji, bjk -> bk\", w, Knn)\n Knn = tf.einsum(\"bij, bi -> b\", w, Knn) # (num_batch,)\n\n Kmn = self.kernel.kernels[i].K(tf.gather(self.X_data.Z, indices=self.kernel.kernels[i].active_dims, axis=1), X) \n Kmn = tf.transpose(Kmn, perm=[1,0,2]) # (num_inducing x num_batch)\n Kmn = tf.einsum(\"bij, bjk -> ib\", Kmn, w)\n\n fmean, fvar = base_conditional(\n Kmn, Kmm, Knn, self.q_mu, full_cov=full_cov, q_sqrt=self.q_sqrt, white=self.whiten\n ) # [N, P], [P, N, N] or [N, P]\n return self._post_process_mean_and_cov(fmean, fvar, full_cov, full_output_cov)\n\n def fused_predict_aggregated_i(\n self, w, X, i, full_cov: bool = False, full_output_cov: bool = False\n ):\n \"\"\"\n Computes predictive mean and (co)variance at Xnew, including mean_function\n Does not make use of caching\n \"\"\"\n mean, cov = self._conditional_aggregated_fused_i(\n w, X, i, full_cov=full_cov, full_output_cov=full_output_cov\n )\n return mean, cov\n\n def fused_predict_f(\n self, X, full_cov: bool = False, full_output_cov: bool = False\n ):\n \"\"\"\n Computes predictive mean and (co)variance at Xnew, including mean_function\n Does not make use of caching\n \"\"\"\n mean, cov = self._conditional_fused(\n X, full_cov=full_cov, full_output_cov=full_output_cov\n )\n return mean, cov\n\n def _conditional_fused_i(\n self, Xnew, i, full_cov: bool = False, full_output_cov: bool = False\n ):\n assert len(tf.shape(Xnew)) == 2, \"Input array X has to have shape 2 (non-batched)\"\n # same as IndependentPosteriorMultiOutput, Shared~/Shared~ branch, except for following line:\n Knn = self.kernel.kernels[i].K_diag(Xnew)\n\n Kmm = covariances.Kuu(self.X_data, self.kernel, jitter=default_jitter()) # [M, M]\n Kmn = self.kernel.kernels[i].K(tf.gather(self.X_data.Z, indices=self.kernel.kernels[i].active_dims, axis=1), Xnew) \n\n fmean, fvar = base_conditional(\n Kmn, Kmm, Knn, self.q_mu, full_cov=full_cov, q_sqrt=self.q_sqrt, white=self.whiten\n ) # [N, P], [P, N, N] or [N, P]\n return self._post_process_mean_and_cov(fmean, fvar, full_cov, full_output_cov)\n\n def fused_predict_f_i(\n self, X, i, full_cov: bool = False, full_output_cov: bool = False\n ):\n \"\"\"\n Computes predictive mean and (co)variance at Xnew, including mean_function\n Does not make use of caching\n \"\"\"\n mean, cov = self._conditional_fused_i(\n X, i, full_cov=full_cov, full_output_cov=full_output_cov\n )\n return mean, cov" ]
[ [ "tensorflow.transpose", "tensorflow.shape", "tensorflow.expand_dims", "tensorflow.einsum", "tensorflow.gather" ] ]
thomas-marquis/nlp-tools-py-lib
[ "f944172ec48544d09362ddcb0564813add42ae89" ]
[ "nlp_tools/representations.py" ]
[ "import pandas as pd\nimport numpy as np\nimport typing as t\n\nfrom nlp_tools import utils\nfrom nlp_tools.dump import dump_word_index, dump_merged_word_matrix\n\n\nclass IndexedRepresentation:\n index_columns: t.List[str] = ['lem', 'index']\n index: pd.DataFrame\n index_len: int\n data: t.Dict[str, np.array]\n data_merged: t.Dict[str, np.array]\n\n def __init__(self, data):\n self.index = self.build_index(data)\n self.index_len = self.index.shape[0]\n\n def build_index(self, data) -> pd.DataFrame:\n index = dict()\n idx = 0\n for intent in data:\n for example in data[intent]:\n for lem in example:\n if index.get(lem) is None:\n index[lem] = idx\n idx += 1\n index_dict = [{self.index_columns[0]: k, self.index_columns[1]: index[k]} for k in index]\n dump_word_index(index_dict)\n\n return pd.DataFrame(index_dict, columns=self.index_columns)\n\n def get_index_from_lem(self, lem) -> int:\n idx = self.index.loc[self.index[self.index_columns[0]] == lem, self.index_columns[1]]\n if idx.empty:\n return None\n else:\n return idx.values[0]\n\n def get_matrix_from_index(self, idx) -> np.array:\n matrix = np.zeros(self.index_len)\n matrix[idx] = 1\n return matrix\n\n def get_matrix_from_lem(self, lem) -> np.array:\n idx = self.get_index_from_lem(lem)\n if idx is None:\n return idx\n else:\n return self.get_matrix_from_index(idx)\n\n def process_words_matrix(self, example) -> np.array:\n return np.array(\n [self.get_matrix_from_lem(l) for l in example if not self.get_matrix_from_lem(l) is None])\n\n\nclass MatrixRepresentation(IndexedRepresentation):\n data: t.Dict[str, np.array]\n\n def __init__(self, data):\n IndexedRepresentation.__init__(self, data)\n self.data = self.process_words_matrix_for_all(data)\n\n def process_words_matrix_for_all(self, data) -> t.Dict[str, np.array]:\n get_matrix = lambda examples: np.array(\n [self.process_words_matrix(ex) for ex in examples])\n return utils.apply_for_each_key(data, get_matrix)\n\n def process_new_data(self, lems) -> np.array:\n return self.process_words_matrix(lems)\n\n\nclass MergedMatrixRepresentation(IndexedRepresentation):\n data: t.Dict[str, np.array]\n\n def __init__(self, data):\n IndexedRepresentation.__init__(self, data)\n self.data = self.process_merged_sentences_for_all(data)\n self.save_merged_matrix(self.data)\n\n def save_merged_matrix(self, matrix):\n as_list = lambda np_array: np_array.tolist()\n serializable_matrix = utils.apply_for_each_key(matrix, as_list)\n dump_merged_word_matrix(serializable_matrix)\n\n def process_words_merged_matrix(self, example) -> np.array:\n matrix = self.process_words_matrix(example)\n return sum(list(matrix))\n\n def process_merged_sentences_for_all(self, data) -> t.Dict[str, np.array]:\n get_matrix = lambda examples: np.array(\n [self.process_words_merged_matrix(ex) for ex in examples])\n return utils.apply_for_each_key(data, get_matrix)\n\n def process_new_data(self, lems) -> np.array:\n return self.process_words_merged_matrix(lems)\n" ]
[ [ "numpy.zeros", "pandas.DataFrame" ] ]
hchang000/delta
[ "89320bd538e360d939c50d9f303e81554f6ce7ac" ]
[ "delta/layers/common_layers.py" ]
[ "# Copyright (C) 2017 Beijing Didi Infinity Technology and Development Co.,Ltd.\n# 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\"\"\"Common layers.\"\"\"\n\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim #pylint: disable=no-name-in-module\n\n#pylint: disable=invalid-name\n\n\ndef depthwise_separable_conv(inputs,\n num_pwc_filters,\n width_multiplier,\n scope,\n downsample=False):\n \"\"\"Depth-wise separable convolution.\"\"\"\n num_pwc_filters = round(num_pwc_filters * width_multiplier)\n _stride = 2 if downsample else 1\n\n # skip pointwise by setting num_outputs=None\n depthwise_conv = slim.separable_convolution2d(\n inputs,\n num_outputs=None,\n stride=_stride,\n depth_multiplier=1,\n kernel_size=[3, 3],\n scope=scope + '/depthwise_conv')\n\n bn = slim.batch_norm(depthwise_conv, scope=scope + '/dw_batch_norm')\n pointwise_conv = slim.convolution2d(\n bn, num_pwc_filters, kernel_size=[1, 1], scope=scope + '/pointwise_conv')\n bn = slim.batch_norm(pointwise_conv, scope=scope + '/pw_batch_norm')\n return bn\n\n\n#pylint: disable=too-many-arguments\ndef tdnn(x, name, in_dim, in_context, out_dim, has_bias=True):\n ''' Implemented using conv1d which in turn is a conv2d. '''\n with tf.variable_scope(name):\n kernel = tf.get_variable(\n name='DW',\n shape=[in_context, in_dim, out_dim],\n dtype=tf.float32,\n initializer=tf.contrib.layers.xavier_initializer())\n tdnn_op = tf.nn.conv1d(x, kernel, stride=1, padding='SAME')\n if has_bias:\n b = tf.get_variable(\n name='bias',\n shape=[out_dim],\n dtype=tf.float32,\n initializer=tf.constant_initializer(0.0))\n return tf.nn.bias_add(tdnn_op, b)\n return tdnn_op\n\n\ndef conv2d(x, name, filter_size, in_channels, out_channels, strides):\n \"\"\"2D convolution.\"\"\"\n with tf.variable_scope(name):\n kernel = tf.get_variable(\n name='DW',\n shape=[filter_size[0], filter_size[1], in_channels, out_channels],\n dtype=tf.float32,\n initializer=tf.contrib.layers.xavier_initializer())\n b = tf.get_variable(\n name='bais',\n shape=[out_channels],\n dtype=tf.float32,\n initializer=tf.constant_initializer(0.0))\n con2d_op = tf.nn.conv2d(\n x, kernel, [1, strides[0], strides[1], 1], padding='SAME')\n return tf.nn.bias_add(con2d_op, b)\n\n\ndef max_pool(x, ksize, strides):\n \"\"\"Max Pooling.\"\"\"\n return tf.nn.max_pool(\n x,\n ksize=[1, ksize[0], ksize[1], 1],\n strides=[1, strides[0], strides[1], 1],\n padding='VALID',\n name='max_pool')\n\n\ndef linear(x, names, shapes):\n \"\"\"Linear Layer.\"\"\"\n with tf.variable_scope(names):\n weights = tf.get_variable(\n name='weights',\n shape=shapes,\n initializer=tf.truncated_normal_initializer(stddev=0.1))\n bias = tf.get_variable(\n name='bias', shape=shapes[1], initializer=tf.constant_initializer(0.0))\n return tf.matmul(x, weights) + bias\n\n\ndef attention(inputs, attention_size, time_major=False, return_alphas=False):\n \"\"\"Attention layer.\"\"\"\n if isinstance(inputs, tuple):\n # In case of Bi-RNN, concatenate the forward and the backward RNN outputs.\n inputs = tf.concat(inputs, 2)\n\n if time_major:\n # (T,B,D) => (B,T,D)\n inputs = tf.transpose(inputs, [1, 0, 2])\n\n time_size = inputs.shape[1].value # T value - time size of the RNN layer\n hidden_size = inputs.shape[2].value # D value - hidden size of the RNN layer\n\n # Trainable parameters\n W_omega = tf.get_variable(\n tf.random_normal([hidden_size, attention_size], stddev=0.1))\n b_omega = tf.get_variable(tf.random_normal([attention_size], stddev=0.1))\n u_omega = tf.get_variable(tf.random_normal([attention_size, 1], stddev=0.1))\n\n # Applying fully connected layer with non-linear activation to each of the B*T timestamps;\n # the shape of `v` is (B,T,D)*(D,A)=(B,T,A), where A=attention_size\n #v = tf.tanh(tf.tensordot(inputs, W_omega, axes=1) + b_omega)\n #v = tf.sigmoid(tf.tensordot(inputs, W_omega, axes=1) + b_omega)\n # (B, T, D) dot (D, Atten)\n\n print('attention inputs', inputs.shape)\n inputs_reshaped = tf.reshape(inputs, [-1, hidden_size])\n dot = tf.matmul(inputs_reshaped, W_omega)\n dot = tf.reshape(dot, [-1, time_size, attention_size])\n v = tf.sigmoid(dot + b_omega)\n print('attention vector', v.shape)\n # For each of the timestamps its vector of size A from `v` is reduced with `u` vector\n # (B, T, Atten) dot (Atten)\n #vu = tf.tensordot(v, u_omega, axes=1) # (B,T) shape\n v = tf.reshape(v, [-1, attention_size])\n vu = tf.matmul(v, u_omega) # (B,T) shape\n vu = tf.squeeze(vu, axis=-1)\n vu = tf.reshape(vu, [-1, time_size])\n print('attention energe', vu.shape)\n alphas = tf.nn.softmax(vu) # (B,T) shape also\n\n # Output of (Bi-)RNN is reduced with attention vector; the result has (B,D) shape\n # [batch, time] -> [batch, time, 1]\n alphas = tf.expand_dims(alphas, -1)\n # [batch, time, dim] -> [batch, dim]\n output = tf.reduce_sum(inputs * alphas, 1)\n\n if not return_alphas:\n return output\n\n return output, alphas\n\n\ndef embedding_look_up(text_inputs, vocab_size, embedding_size):\n \"\"\"Embedding layer.\"\"\"\n with tf.variable_scope(\"embedding\"):\n W = tf.get_variable(\n tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0), \"W\")\n embedding_chars = tf.nn.embedding_lookup(W, text_inputs)\n embedding_chars_expanded = tf.expand_dims(embedding_chars, -1)\n return embedding_chars_expanded\n\n\n#pylint: disable=too-many-locals\ndef conv_pool(embedded_chars_expanded, filter_sizes, embedding_size,\n num_filters, sequence_length):\n \"\"\"\n text conv and max pooling to get one-dimension vector to representation of text\n :param filter_sizes:\n :return:\n \"\"\"\n pooled_outputs = []\n for _, filter_size in enumerate(filter_sizes):\n with tf.variable_scope(\"conv-maxpool-%s\" % filter_size):\n # Convolution Layer\n filter_shape = [filter_size, embedding_size, 1, num_filters]\n W = tf.get_variable(tf.truncated_normal(filter_shape, stddev=0.1), \"W\")\n b = tf.get_variable(tf.constant(0.1, shape=[num_filters]), \"b\")\n conv = tf.nn.conv2d(\n embedded_chars_expanded,\n W,\n strides=[1, 1, 1, 1],\n padding=\"VALID\",\n name=\"conv\")\n # Apply nonlinearity\n h = tf.nn.relu(tf.nn.bias_add(conv, b), name=\"relu\")\n # Maxpooling over the outputs\n pooled = tf.nn.max_pool(\n h,\n ksize=[1, sequence_length - filter_size + 1, 1, 1],\n strides=[1, 1, 1, 1],\n padding='VALID',\n name=\"pool\")\n pooled_outputs.append(pooled)\n # Combine all the pooled features\n num_filters_total = num_filters * len(filter_sizes)\n\n h_pool = tf.concat(pooled_outputs, 3)\n\n h_pool_flat = tf.reshape(h_pool, [-1, num_filters_total])\n return h_pool_flat\n" ]
[ [ "tensorflow.concat", "tensorflow.nn.max_pool", "tensorflow.reduce_sum", "tensorflow.contrib.slim.separable_convolution2d", "tensorflow.nn.conv1d", "tensorflow.nn.conv2d", "tensorflow.squeeze", "tensorflow.truncated_normal_initializer", "tensorflow.contrib.layers.xavier_initializer", "tensorflow.matmul", "tensorflow.truncated_normal", "tensorflow.nn.embedding_lookup", "tensorflow.contrib.slim.batch_norm", "tensorflow.nn.bias_add", "tensorflow.nn.softmax", "tensorflow.transpose", "tensorflow.constant", "tensorflow.reshape", "tensorflow.sigmoid", "tensorflow.expand_dims", "tensorflow.constant_initializer", "tensorflow.contrib.slim.convolution2d", "tensorflow.variable_scope", "tensorflow.random_uniform", "tensorflow.random_normal" ] ]
arimakaoru/CameraSystem
[ "790170da9d0e3b3b8243d7abaccf510f052663fd" ]
[ "source/PointList.py" ]
[ "# https://qiita.com/otakoma/items/04e525ac74b7191dffe6 より参照\n\nimport sys\n\nimport numpy as np\nimport cv2\n\n\nclass PointList:\n def __init__(self, npoints=4):\n self.npoints = npoints\n self.ptlist = np.empty((npoints, 2), dtype=int)\n self.pos = 0\n self.named_points = {\"l_top\": None, \"l_btm\": None, \"r_top\": None, \"r_btm\": None}\n\n def add(self, x, y):\n if self.pos < self.npoints:\n self.ptlist[self.pos, :] = [x, y]\n self.pos += 1\n return True\n return False\n\n def trans(self):\n sum_list = np.sum(self.ptlist, axis=1)\n x_list = self.ptlist[:, 0]\n y_list = self.ptlist[:, 1]\n self.named_points[\"r_btm\"] = self.ptlist[np.argmax(x_list)]\n self.named_points[\"l_top\"] = self.ptlist[np.argmin(x_list)]\n self.named_points[\"r_top\"] = self.ptlist[np.argmin(y_list)]\n self.named_points[\"l_btm\"] = self.ptlist[np.argmax(y_list)]\n print(self.named_points)\n\n @staticmethod\n def add_point(event, x, y, flag, params):\n wname, img, ptlist = params\n if event == cv2.EVENT_MOUSEMOVE: # マウスが移動したときにx線とy線を更新する\n img2 = np.copy(img)\n h, w = img2.shape[0], img2.shape[1]\n cv2.line(img2, (x, 0), (x, h - 1), (255, 0, 0))\n cv2.line(img2, (0, y), (w - 1, y), (255, 0, 0))\n cv2.imshow(wname, img2)\n\n if event == cv2.EVENT_LBUTTONDOWN: # レフトボタンをクリックしたとき、ptlist配列にx,y座標を格納する\n if ptlist.add(x, y):\n print('[%d] ( %d, %d )' % (ptlist.pos - 1, x, y))\n cv2.circle(img, (x, y), 3, (0, 0, 255), 3)\n cv2.imshow(wname, img)\n else:\n print('All points have selected. Press ESC-key.')\n if ptlist.pos == ptlist.npoints:\n print(ptlist.ptlist)\n cv2.line(img, (ptlist.ptlist[0][0], ptlist.ptlist[0][1]),\n (ptlist.ptlist[1][0], ptlist.ptlist[1][1]), (0, 255, 0), 3)\n cv2.line(img, (ptlist.ptlist[1][0], ptlist.ptlist[1][1]),\n (ptlist.ptlist[2][0], ptlist.ptlist[2][1]), (0, 255, 0), 3)\n cv2.line(img, (ptlist.ptlist[2][0], ptlist.ptlist[2][1]),\n (ptlist.ptlist[3][0], ptlist.ptlist[3][1]), (0, 255, 0), 3)\n cv2.line(img, (ptlist.ptlist[3][0], ptlist.ptlist[3][1]),\n (ptlist.ptlist[0][0], ptlist.ptlist[0][1]), (0, 255, 0), 3)\n\n\ndef main():\n url = \"http://raspberrypi.local/?action=stream\"\n # VideoCaptureのインスタンスを作成する。\n cap = cv2.VideoCapture(url) # カメラシステムを使う場合\n if not cap.isOpened():\n print(\"画像のキャプチャに失敗しました\")\n sys.exit()\n\n # 画像をキャプチャ\n ret, img = cap.read()\n wname = \"MouseEvent\"\n cv2.namedWindow(wname)\n ptlist = PointList()\n ptlist.add_point()\n ptlist.trans()\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.copy", "numpy.argmax", "numpy.argmin", "numpy.sum", "numpy.empty" ] ]
zju3dv/NIID-Net
[ "9d60cfd1b01873ddc15da167d8cbb90783408950" ]
[ "data/intrinsics/aligned_data_loader.py" ]
[ "import random\nimport numpy as np\nimport torch.utils.data\nfrom torch.utils.data.sampler import Sampler\nfrom data.intrinsics.base_data_loader import BaseDataLoader\nfrom data.intrinsics.image_folder import *\nimport scipy.io as sio\n# from builtins import object\nimport sys\nimport h5py\n\nclass IIWTestData(object):\n def __init__(self, data_loader):\n self.data_loader = data_loader\n\n def __iter__(self):\n self.data_loader_iter = iter(self.data_loader)\n self.iter = 0\n return self\n\n def __next__(self):\n self.iter += 1\n final_img, target_1, sparse_path_1s = next(self.data_loader_iter)\n return {'img_1': final_img, 'target_1': target_1}\n\n\nclass SAWData(object):\n def __init__(self, data_loader):\n self.data_loader = data_loader\n\n def __iter__(self):\n self.data_loader_iter = iter(self.data_loader)\n self.iter = 0\n return self\n\n def sparse_loader(self, sparse_path, num_features):\n # print(\"sparse_path \", sparse_path)\n # sys.exit()\n hdf5_file_sparse = h5py.File(sparse_path,'r')\n B_arr = []\n data_whole = hdf5_file_sparse.get('/sparse/mn')\n mn = np.array(data_whole)\n mn = np.transpose(mn, (1,0))\n m = int(mn[0][0])\n n = int(mn[1][0])\n # print(m, n)\n data_whole = hdf5_file_sparse.get('/sparse/S')\n S_coo = np.array(data_whole)\n S_coo = np.transpose(S_coo, (1,0))\n S_coo = torch.transpose(torch.from_numpy(S_coo),0,1)\n\n # print(S_coo[:,0:2])\n # print(torch.FloatTensor([3, 4]))\n S_i = S_coo[0:2,:].long()\n S_v = S_coo[2,:].float()\n S = torch.sparse.FloatTensor(S_i, S_v, torch.Size([m+2,n]))\n\n for i in range(num_features+1):\n data_whole = hdf5_file_sparse.get('/sparse/B'+str(i) )\n B_coo = np.array(data_whole)\n B_coo = np.transpose(B_coo, (1,0))\n B_coo = torch.transpose(torch.from_numpy(B_coo),0,1)\n B_i = B_coo[0:2,:].long()\n B_v = B_coo[2,:].float()\n\n B_mat = torch.sparse.FloatTensor(B_i, B_v, torch.Size([m+2,m+2]))\n B_arr.append(B_mat)\n\n\n data_whole = hdf5_file_sparse.get('/sparse/N')\n N = np.array(data_whole)\n N = np.transpose(N, (1,0))\n N = torch.from_numpy(N)\n\n hdf5_file_sparse.close()\n return S, B_arr, N \n\n\n def __next__(self):\n self.iter += 1\n final_img, target_1, sparse_path_1s = next(self.data_loader_iter)\n\n target_1['SS'] = []\n target_1['SB_list'] = [] \n target_1['SN'] = []\n\n SS_1, SB_list_1, SN_1 = self.sparse_loader(sparse_path_1s[0], 2)\n\n for i in range(len(sparse_path_1s)):\n target_1['SS'].append(SS_1)\n target_1['SB_list'].append(SB_list_1)\n target_1['SN'].append(SN_1)\n\n return {'img_1': final_img, 'target_1': target_1}\n\n\nclass CGIntrinsicsData(object):\n def __init__(self, data_loader, root):\n self.data_loader = data_loader\n # self.fineSize = fineSize\n # self.max_dataset_size = max_dataset_size\n self.root = root\n # st()\n self.npixels = (256 * 256* 29)\n\n def __iter__(self):\n self.data_loader_iter = iter(self.data_loader)\n self.iter = 0\n return self\n\n def sparse_loader(self, sparse_path, num_features):\n # print(\"sparse_path \", sparse_path)\n # sys.exit()\n hdf5_file_sparse = h5py.File(sparse_path,'r')\n B_arr = []\n data_whole = hdf5_file_sparse.get('/sparse/mn')\n mn = np.array(data_whole)\n mn = np.transpose(mn, (1,0))\n m = int(mn[0][0])\n n = int(mn[1][0])\n # print(m, n)\n data_whole = hdf5_file_sparse.get('/sparse/S')\n S_coo = np.array(data_whole)\n S_coo = np.transpose(S_coo, (1,0))\n S_coo = torch.transpose(torch.from_numpy(S_coo),0,1)\n\n # print(S_coo[:,0:2])\n # print(torch.FloatTensor([3, 4]))\n S_i = S_coo[0:2,:].long()\n S_v = S_coo[2,:].float()\n S = torch.sparse.FloatTensor(S_i, S_v, torch.Size([m+2,n]))\n\n for i in range(num_features+1):\n data_whole = hdf5_file_sparse.get('/sparse/B'+str(i) )\n B_coo = np.array(data_whole)\n B_coo = np.transpose(B_coo, (1,0))\n B_coo = torch.transpose(torch.from_numpy(B_coo),0,1)\n B_i = B_coo[0:2,:].long()\n B_v = B_coo[2,:].float()\n\n B_mat = torch.sparse.FloatTensor(B_i, B_v, torch.Size([m+2,m+2]))\n B_arr.append(B_mat)\n\n\n data_whole = hdf5_file_sparse.get('/sparse/N')\n N = np.array(data_whole)\n N = np.transpose(N, (1,0))\n N = torch.from_numpy(N)\n\n hdf5_file_sparse.close()\n return S, B_arr, N \n\n\n def create_CGIntrinsics_pair(self, path, gt_albedo, random_filp):\n\n super_pixel_path = self.root + \"/CGIntrinsics/intrinsics_final/superpixels/\" + path + \".mat\"\n super_pixel_mat = sio.loadmat(super_pixel_path)\n super_pixel_mat = super_pixel_mat['data']\n \n final_list = []\n\n for i in range(len(super_pixel_mat)):\n pos =super_pixel_mat[i][0]\n\n if pos.shape[0] < 2:\n continue\n\n rad_idx = random.randint(0, pos.shape[0]-1) \n final_list.append( (pos[rad_idx,0], pos[rad_idx,1]) )\n\n eq_list = []\n ineq_list = []\n\n row = gt_albedo.shape[0]\n col = gt_albedo.shape[1]\n\n for i in range(0,len(final_list)-1):\n for j in range(i+1, len(final_list)):\n y_1, x_1 = final_list[i]\n y_2, x_2 = final_list[j]\n\n y_1 = int(y_1*row)\n x_1 = int(x_1*col)\n y_2 = int(y_2*row)\n x_2 = int(x_2*col)\n\n # if image is flip\n if random_filp:\n x_1 = col - 1 - x_1\n x_2 = col - 1 - x_2\n\n if gt_albedo[y_1, x_1] < 2e-4 or gt_albedo[y_2, x_2] < 2e-4:\n continue\n\n ratio = gt_albedo[y_1, x_1]/gt_albedo[y_2, x_2]\n\n if ratio < 1.05 and ratio > 1./1.05:\n eq_list.append([y_1, x_1, y_2, x_2])\n elif ratio > 1.5:\n ineq_list.append([y_1, x_1, y_2, x_2]) \n elif ratio < 1./1.5:\n ineq_list.append([y_2, x_2, y_1, x_1]) \n\n eq_mat = np.asarray(eq_list)\n ineq_mat = np.asarray(ineq_list)\n\n if eq_mat.shape[0] > 0:\n eq_mat = torch.from_numpy(eq_mat).contiguous().float()\n else:\n eq_mat = torch.Tensor(1,1)\n\n\n if ineq_mat.shape[0] > 0:\n ineq_mat = torch.from_numpy(ineq_mat).contiguous().float()\n else:\n ineq_mat = torch.Tensor(1,1)\n\n\n return eq_mat, ineq_mat\n\n\n def __next__(self):\n self.iter += 1\n self.iter += 1\n scale =4 \n\n final_img, target_1, sparse_path_1s = next(self.data_loader_iter)\n return {'img_1': final_img, 'target_1': target_1}\n\n target_1['eq_mat'] = []\n target_1['ineq_mat'] = []\n\n # This part will make training much slower, but it will improve performance\n for i in range(len(target_1[\"CGIntrinsics_ordinal_path\"])):\n mat_path = target_1[\"CGIntrinsics_ordinal_path\"][i]\n gt_R = target_1['gt_R'][i,0,:,:].numpy()\n random_filp = target_1['random_filp'][i]\n\n eq_mat, ineq_mat = self.create_CGIntrinsics_pair(mat_path, gt_R, random_filp)\n target_1['eq_mat'].append(eq_mat)\n target_1['ineq_mat'].append(ineq_mat)\n\n\n target_1['SS'] = []\n target_1['SB_list'] = []\n target_1['SN'] = []\n\n SS_1, SB_list_1, SN_1 = self.sparse_loader(sparse_path_1s[0], 2)\n\n for i in range(len(sparse_path_1s)):\n target_1['SS'].append(SS_1)\n target_1['SB_list'].append(SB_list_1)\n target_1['SN'].append(SN_1)\n\n return {'img_1': final_img, 'target_1': target_1}\n\n\nclass IIWData(object):\n def __init__(self, data_loader, flip):\n self.data_loader = data_loader\n # self.fineSize = fineSize\n # self.max_dataset_size = max_dataset_size\n self.flip = flip\n # st()\n self.npixels = (256 * 256* 29)\n\n def __iter__(self):\n self.data_loader_iter = iter(self.data_loader)\n self.iter = 0\n return self\n\n def sparse_loader(self, sparse_path, num_features):\n # print(\"sparse_path \", sparse_path)\n # sys.exit()\n hdf5_file_sparse = h5py.File(sparse_path,'r')\n B_arr = []\n data_whole = hdf5_file_sparse.get('/sparse/mn')\n mn = np.array(data_whole)\n mn = np.transpose(mn, (1,0))\n m = int(mn[0][0])\n n = int(mn[1][0])\n # print(m, n)\n data_whole = hdf5_file_sparse.get('/sparse/S')\n S_coo = np.array(data_whole)\n S_coo = np.transpose(S_coo, (1,0))\n S_coo = torch.transpose(torch.from_numpy(S_coo),0,1)\n\n # print(S_coo[:,0:2])\n # print(torch.FloatTensor([3, 4]))\n S_i = S_coo[0:2,:].long()\n S_v = S_coo[2,:].float()\n S = torch.sparse.FloatTensor(S_i, S_v, torch.Size([m+2,n]))\n\n for i in range(num_features+1):\n data_whole = hdf5_file_sparse.get('/sparse/B'+str(i) )\n B_coo = np.array(data_whole)\n B_coo = np.transpose(B_coo, (1,0))\n B_coo = torch.transpose(torch.from_numpy(B_coo),0,1)\n B_i = B_coo[0:2,:].long()\n B_v = B_coo[2,:].float()\n\n B_mat = torch.sparse.FloatTensor(B_i, B_v, torch.Size([m+2,m+2]))\n B_arr.append(B_mat)\n\n\n data_whole = hdf5_file_sparse.get('/sparse/N')\n N = np.array(data_whole)\n N = np.transpose(N, (1,0))\n N = torch.from_numpy(N)\n\n hdf5_file_sparse.close()\n return S, B_arr, N \n\n def long_range_loader(self, h5_path):\n hdf5_file_read_img = h5py.File(h5_path,'r') \n num_eq = hdf5_file_read_img.get('/info/num_eq')\n num_eq = np.float32(np.array(num_eq))\n num_eq = int(num_eq[0][0])\n\n\n if num_eq > 0:\n equal_mat = hdf5_file_read_img.get('/info/equal')\n equal_mat = np.float32(np.array(equal_mat))\n equal_mat = np.transpose(equal_mat, (1, 0))\n equal_mat = torch.from_numpy(equal_mat).contiguous().float()\n else:\n equal_mat = torch.Tensor(1,1)\n \n num_ineq = hdf5_file_read_img.get('/info/num_ineq')\n num_ineq = np.float32(np.array(num_ineq))\n num_ineq = int(num_ineq[0][0])\n\n if num_ineq > 0:\n ineq_mat = hdf5_file_read_img.get('/info/inequal')\n ineq_mat = np.float32(np.array(ineq_mat))\n ineq_mat = np.transpose(ineq_mat, (1, 0))\n ineq_mat = torch.from_numpy(ineq_mat).contiguous().float()\n else:\n ineq_mat = torch.Tensor(1,1)\n\n\n hdf5_file_read_img.close()\n\n return equal_mat, ineq_mat\n\n def __next__(self):\n self.iter += 1\n self.iter += 1\n scale =4 \n\n final_img, target_1, sparse_path_1s = next(self.data_loader_iter)\n\n target_1['eq_mat'] = []\n target_1['ineq_mat'] = []\n\n for i in range(len(target_1[\"mat_path\"])):\n mat_path = target_1[\"mat_path\"][i]\n eq_mat, ineq_mat = self.long_range_loader(mat_path)\n target_1['eq_mat'].append(eq_mat)\n target_1['ineq_mat'].append(ineq_mat)\n\n\n target_1['SS'] = []\n target_1['SB_list'] = [] \n target_1['SN'] = []\n\n SS_1, SB_list_1, SN_1 = self.sparse_loader(sparse_path_1s[0], 2)\n\n for i in range(len(sparse_path_1s)):\n target_1['SS'].append(SS_1)\n target_1['SB_list'].append(SB_list_1)\n target_1['SN'].append(SN_1)\n\n return {'img_1': final_img, 'target_1': target_1}\n\n\nclass CGIntrinsics_DataLoader(BaseDataLoader):\n def __init__(self,_root, _list_dir, _batch_size, _num_workers):\n transform = None\n dataset = CGIntrinsicsImageFolder(root=_root, \\\n list_dir =_list_dir)\n\n self.data_loader = torch.utils.data.DataLoader(dataset, batch_size=_batch_size, shuffle= True, num_workers=_num_workers)\n self.dataset = dataset\n flip = False \n self.paired_data = CGIntrinsicsData(self.data_loader, _root)\n\n def name(self):\n return 'CGIntrinsics_DataLoader'\n\n def load_data(self):\n return self.paired_data\n\n def __len__(self):\n return len(self.dataset)\n\n\nclass SAWDataLoader(BaseDataLoader):\n def __init__(self,_root, _list_dir, mode, _batch_size, _num_workers):\n # BaseDataLoader.initialize(self)\n # self.fineSize = opt.fineSize\n\n transform = None\n \n dataset = SAW_ImageFolder(root=_root, \\\n list_dir =_list_dir, mode = mode, is_flip = True, transform=transform)\n\n data_loader = torch.utils.data.DataLoader(dataset, batch_size=_batch_size, shuffle= True, num_workers=_num_workers)\n\n self.dataset = dataset\n # flip = False\n self.saw_data = SAWData(data_loader)\n\n def name(self):\n return 'sawDataLoader'\n\n def load_data(self):\n return self.saw_data\n\n def __len__(self):\n return len(self.dataset)\n\n\nclass IIWDataLoader(BaseDataLoader):\n def __init__(self,_root, _list_dir, mode, _batch_size, _num_workers):\n # BaseDataLoader.initialize(self)\n # self.fineSize = opt.fineSize\n\n # transformations = [\n # TODO: Scale\n #transforms.CenterCrop((600,800)),\n # transforms.Scale(256, Image.BICUBIC),\n # transforms.ToTensor() ]\n transform = None\n # transform = transforms.Compose(transformations)\n\n # Dataset A\n # dataset = ImageFolder(root='/phoenix/S6/zl548/AMOS/test/', \\\n # list_dir = '/phoenix/S6/zl548/AMOS/test/list/',transform=transform)\n # testset \n dataset = IIW_ImageFolder(root=_root, \\\n list_dir =_list_dir, mode = mode, is_flip = True, transform=transform)\n\n data_loader = torch.utils.data.DataLoader(dataset, batch_size=_batch_size, shuffle= True, num_workers=_num_workers)\n\n self.dataset = dataset\n flip = False\n self.iiw_data = IIWData(data_loader, flip)\n\n def name(self):\n return 'iiwDataLoader'\n\n def load_data(self):\n return self.iiw_data\n\n def __len__(self):\n return len(self.dataset)\n\n\nclass RenderDataLoader(BaseDataLoader):\n def __init__(self,_root, _list_dir, _batch_size, _num_workers):\n # BaseDataLoader.initialize(self)\n transform = None\n\n dataset = Render_ImageFolder(root=_root, \\\n list_dir =_list_dir, transform=transform)\n\n self.data_loader = torch.utils.data.DataLoader(dataset, batch_size=_batch_size, shuffle= True, num_workers=_num_workers)\n self.dataset = dataset\n\n def name(self):\n return 'renderDataLoader'\n\n def load_data(self):\n return self.data_loader\n\n def __len__(self):\n return len(self.dataset)\n\n\nclass SubsetSampler(Sampler):\n \"\"\"Samples elements from a given list of indices, without replacement.\n\n Arguments:\n indices (list): a list of indices\n \"\"\"\n\n def __init__(self, indices):\n self.indices = indices\n\n def __iter__(self):\n return iter(self.indices)\n\n def __len__(self):\n return len(self.indices)\n\n\nclass IIWTESTDataLoader(BaseDataLoader):\n def __init__(self,_root, _list_dir, mode, _batch_size, _num_workers, use_subset):\n\n transform = None\n dataset = IIW_ImageFolder(root=_root, \\\n list_dir =_list_dir, mode= mode, is_flip = False, transform=transform)\n if use_subset:\n subset_sampler = SubsetSampler(list(range(0, len(dataset), 5)))\n data_loader = torch.utils.data.DataLoader(dataset, batch_size=_batch_size, shuffle= False, \n num_workers=_num_workers, sampler=subset_sampler)\n else:\n data_loader = torch.utils.data.DataLoader(dataset, batch_size=_batch_size, shuffle= False, num_workers=_num_workers)\n self.dataset = dataset\n self.iiw_data = IIWTestData(data_loader)\n\n def name(self):\n return 'IIWTESTDataLoader'\n\n def load_data(self):\n return self.iiw_data\n\n def __len__(self):\n return len(self.dataset)\n\n" ]
[ [ "numpy.asarray", "numpy.array", "scipy.io.loadmat", "numpy.transpose" ] ]
wtrenker/glucose-chart
[ "15f153415cfae6550fb6a2ff5c42646993fb3ad7" ]
[ "Chart.py" ]
[ "'''\nCopyright 2020 William Trenker\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n'''\n\nfrom bottle import route, default_app, HTTPResponse, run, jinja2_view, url, get, post, request, html_escape,\\\n response, redirect, debug, jinja2_template, MultiDict, post\nfrom pony.orm import Database, Optional, Required, PrimaryKey, db_session, sql_debug, select\nimport matplotlib as mpl\nmpl.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mpd\nimport numpy as np\nfrom datetime import datetime\nfrom General import verify_password, decimalAverage, dateTimeStr, dbFileName\nimport pytz\nfrom io import BytesIO\nfrom pathlib import Path\n# import Sessions, HTTPCookie, System\nimport System\n\ndbPath = Path(f'./db/{dbFileName}')\n# dbPath = Path(dbFile)\ndb = Database()\n\nclass Readings(db.Entity):\n date = PrimaryKey(str)\n am = Required(float)\n pm = Optional(float)\n comment = Optional(str)\n average = Optional(float)\n\nDAtE = 0\nAM = 1\nPM = 2\nCOMMENT = 3\nAVERAGE = 4\n\ndb.bind(provider='sqlite', filename=str(dbPath), create_db=False)\ndb.generate_mapping(create_tables=False)\n\n# zulu = pytz.timezone('UTC')\npst = pytz.timezone(\"America/Vancouver\")\n\ndef renderChart(request):\n\n DateCombined = []\n CommentDateCombined = []\n DailyAverageCombined = []\n CommentCombined = []\n CommentAverageCombined = []\n\n dATE = 0\n aM = 1\n pM = 2\n cOMMENT = 3\n aVERAGE = 4\n\n with db_session:\n qry = select((r.date, r.am, r.pm, r.comment, r.average) for r in Readings).order_by(1)\n # xx = qry.get_sql()\n try:\n recs = qry.fetch()\n except Exception as e:\n print(e)\n for rec in recs:\n if rec[aM] is None and rec[pM] is None: # Use the old method based on the recorded average\n if rec[aVERAGE]: # if average reading is Null, skip over partial readings\n dtdate = rec[dATE]\n dtdate = datetime.strptime(dtdate, \"%Y-%m-%d\")\n DateCombined.append(dtdate)\n DailyAverageCombined.append(rec[aVERAGE])\n if rec[cOMMENT]:\n CommentDateCombined.append(dtdate)\n CommentAverageCombined.append(rec[aVERAGE])\n CommentCombined.append(rec[cOMMENT])\n else: # use the new method based on a computed average\n if rec[pM]: # if no evening reading, skip over this reading\n dtdate = rec[dATE]\n dtdate = datetime.strptime(dtdate, \"%Y-%m-%d\")\n DateCombined.append(dtdate)\n DailyAVerage = float(decimalAverage(rec[aM], rec[pM]))\n DailyAverageCombined.append(DailyAVerage)\n if rec[cOMMENT]:\n CommentDateCombined.append(dtdate)\n CommentAverageCombined.append(DailyAVerage)\n CommentCombined.append(rec[cOMMENT])\n\n DateCombined = mpd.date2num(DateCombined)\n CommentDateCombined = mpd.date2num(CommentDateCombined)\n\n fig, ax1 = plt.subplots()\n\n lineTarg = ax1.axhline(y=6, linewidth=4, color='k', label='Glucose Target Range')\n ax1.axhline(y=9, linewidth=4, color='k')\n\n background = 0.30\n\n lineCombined, = ax1.plot_date(DateCombined, DailyAverageCombined, label='Daily Blood Glucose', linestyle='-',\n linewidth=1, color='r', marker=None, tz=pst) #\n\n ax1.yaxis.grid(True, linewidth=1)\n\n for i in range(len(CommentDateCombined)):\n text = f'<---{(CommentCombined[i], CommentDateCombined[i])}'\n text = f'<---{CommentCombined[i]}'\n # return pprint.pformat((text, CommentDateCombined[i], CommentAverageCombined[i]))\n ax1.annotate(text, (CommentDateCombined[i], CommentAverageCombined[i]), fontsize=12,\n color='b', weight='bold') # , rotation=0,\n\n DateRange = np.concatenate((DateCombined,))\n minDate = min(DateRange)\n maxDate = max(DateRange)\n ax1.set_xlim(minDate, maxDate)\n\n df = mpl.dates.DateFormatter('%b-%d', tz=pst)\n ax1.xaxis.set_major_formatter(df)\n ax1.tick_params(which='major', width=2.0, length=4.0) # , labelsize=10)\n xlocator = mpl.dates.DayLocator(tz=pst)\n ax1.xaxis.set_minor_locator(xlocator)\n\n plt.gcf().autofmt_xdate()\n\n z = np.polyfit(DateCombined, DailyAverageCombined, 2)\n # z = np.polynomial.chebyshev.chebfit(DateCombined, DailyAverageCombined, 2)\n p = np.poly1d(z)\n trendLine, = ax1.plot_date(DateCombined, p(DateCombined), 'k--', label='Trend Line')\n\n # ax1.legend(handles=[lineCombined, trendLine, lineTarg], loc='upper left') # , loc='lower right' 'best'\n ax1.legend(handles=[lineCombined, lineTarg, trendLine], loc='upper right') # , loc='lower right' 'best'\n\n plt.title('Average Daily Blood Glucose (Jardiance Trial)', loc='left')\n plt.title('William Trenker')\n #\n # sessionID = HTTPCookie.getSessionCookie(request)\n nowstr = System.getLastReadingDateStr()\n # nowstr = dateTimeStr(datetime.now(), \"America/Vancouver\")\n dbNow = f'({dbFileName}) last updated: {nowstr}'\n plt.title(dbNow, fontsize=10, loc='right')\n #\n ax1.set_xlabel('Date') # Note that this won't work on plt or ax2\n ax1.set_ylabel('Blood Glucose (mmol/L)')\n\n fig.set_size_inches(16, 8.5)\n # fig.tight_layout()\n\n img = BytesIO()\n fig.savefig(img)\n img.seek(0)\n return img\n # return send_file(img, mimetype='image/png')\n\n@get('/', name='home')\n@get('/chart', name='chart')\ndef chart():\n # log('chart', 'HTTPResponse')\n img = renderChart(request)\n resp = HTTPResponse(body=img, status=200)\n resp.set_header('content_type', 'image/png')\n return resp\n\napp = default_app()\n\[email protected](404)\ndef error404handler(error):\n f = request.fullpath\n respData = MultiDict(dict(f=f))\n return jinja2_template('405.jinja2', respData, template_lookup=['templates'])\n\[email protected](405)\ndef error405handler(error):\n f = request.fullpath\n respData = MultiDict(dict(f=f))\n return jinja2_template('405.jinja2', respData, template_lookup=['templates'])\n\[email protected](500)\ndef error500handler(error):\n f = request.fullpath\n respData = MultiDict(dict(f=f))\n return jinja2_template('500.jinja2', template_lookup=['templates'])\n\n\n\nif __name__ == '__main__':\n run(host='localhost', port=8081, debug=True)\n\n" ]
[ [ "matplotlib.dates.DateFormatter", "numpy.polyfit", "numpy.poly1d", "matplotlib.pyplot.title", "matplotlib.use", "matplotlib.pyplot.subplots", "matplotlib.pyplot.gcf", "numpy.concatenate", "matplotlib.dates.date2num", "matplotlib.dates.DayLocator" ] ]
crmin/looord
[ "a7a0c5846ebdd62ecf9c62991b9ffce533a6bf25" ]
[ "looord/commands/functions.py" ]
[ "import os\n\nimport discord\nfrom numpy import random\n\nfrom commands import constants\nfrom commands.bot_status import get_num_command, get_num_chat, get_start_time, get_uptime\nfrom commands.crawler import r6stats, r6s_server\nfrom commands.define import commands, prefix\nfrom commands.utils import get_online_members\n\n\nasync def bot_help(client, message, params, *args, **kwargs):\n embed = discord.Embed(\n title='**How to use looord bot?**',\n color=0x93263f\n )\n for comm_func, comm_v in commands.items():\n embed.add_field(\n name='{prefix}({commands})'.format(prefix=prefix, commands='|'.join(comm_v['message'])),\n value='{desc}'.format(desc=comm_v['help']),\n inline=False\n )\n return await client.send_message(message.channel, embed=embed)\n\n\nasync def leader(client, message, params, *args, **kwargs):\n online_members = get_online_members(message.channel)\n today_leader = random.choice(online_members)\n embed = discord.Embed(\n title='오늘의 분대장은?',\n description='{}'.format(today_leader.mention),\n color=0x93263f\n )\n return await client.send_message(message.channel, embed=embed)\n\n\nasync def ack(client, message, params, *args, **kwargs):\n return await client.send_message(message.channel, 'ack')\n\n\nasync def history(client, message, params, *args, **kwargs):\n uuid = r6stats.get_uuid(params[0])[0]\n simple_info = r6stats.get_simple_info(uuid)\n embed = discord.Embed(\n title='R6Stats: `{}`'.format(simple_info['username']),\n description=simple_info['url'],\n color=0x93263f,\n )\n embed.add_field(\n name='Recent Rank',\n value='{}'.format(simple_info['rank']),\n inline=False\n )\n embed.add_field(\n name='[Rank] Kills/Match',\n value='{}'.format(simple_info['ranked_stats']['kills/match']),\n inline=True\n )\n embed.add_field(\n name='[Casual] Kills/Match',\n value='{}'.format(simple_info['casual_stats']['kills/match']),\n inline=True\n )\n embed.add_field(\n name='[Rank] K/D Ratio',\n value='{}'.format(simple_info['ranked_stats']['k/d ratio']),\n inline=True\n )\n embed.add_field(\n name='[Casual] K/D Ratio',\n value='{}'.format(simple_info['casual_stats']['k/d ratio']),\n inline=True\n )\n embed.add_field(\n name='[Rank] W/L Ratio',\n value='{}'.format(simple_info['ranked_stats']['w/l ratio']),\n inline=True\n )\n embed.add_field(\n name='[Casual] W/L Ratio',\n value='{}'.format(simple_info['casual_stats']['w/l ratio']),\n inline=True\n )\n embed.set_thumbnail(url=simple_info['profile_img'])\n return await client.send_message(message.channel, embed=embed)\n\n\nasync def random_ops(client, message, params, *args, **kwargs):\n random.shuffle(constants.defenders)\n random.shuffle(constants.attackers)\n def_sample = '\\n'.join(['* {}'.format(each) for each in constants.defenders[:3]])\n atk_sample = '\\n'.join(['* {}'.format(each) for each in constants.attackers[:3]])\n embed = discord.Embed(\n title='Random Ops',\n description='*아래 오퍼 중 순서대로 골라주세요. 앞에 있는 오퍼의 우선순위가 높습니다.*',\n color=0x93263f\n )\n embed.add_field(name='Attacker :gun:', value='{}'.format(atk_sample), inline=True)\n embed.add_field(name='Defender :shield:', value='{}'.format(def_sample), inline=True)\n return await client.send_message(message.channel, embed=embed)\n\n\nasync def muzzle(client, message, params, *args, **kwargs):\n gun_name = params[0]\n is_found = False\n embed = discord.Embed(\n title='총구 부착물 :gun:',\n description='{}이(가) 포함되는 총에 대한 부착물을 보여줍니다'.format(gun_name),\n color=0x93263f\n )\n if len(gun_name) < 2:\n embed.add_field(\n name='Error: Too short gun name',\n value='두 글자 이상 검색해주세요'.format(gun_name),\n inline=False\n )\n else:\n for gun, attachment in constants.gun2attachment.items():\n if gun_name.lower() in gun.lower():\n embed.add_field(\n name=gun,\n value='{att} ({att_kor})'.format(att=attachment, att_kor=constants.attachment_kor[attachment]),\n inline=True\n )\n is_found = True\n if not is_found:\n embed.add_field(\n name='Error: Not found',\n value='{}가 포함되는 총기를 찾을 수 없습니다'.format(gun_name),\n inline=False\n )\n return await client.send_message(message.channel, embed=embed)\n\n\nasync def magical_conch(client, message, params, *args, **kwargs):\n pick_item = random.choice(params)\n embed = discord.Embed(\n title='마법의 소라고둥님',\n description='{} 중 어떤걸 선택할까요?'.format(', '.join(params)),\n color=0x93263f\n )\n embed.add_field(name='마법의 소라고둥께서 말하시길', value='||{}||'.format(pick_item), inline=False)\n embed.set_thumbnail(url='https://i.imgur.com/U6BsF6K.png')\n return await client.send_message(message.channel, embed=embed)\n\n\nasync def server_status(client, message, *args, **kwargs):\n error_num = r6s_server.get_error_num()\n normal, warning, error = 0x17a2b8, 0xffc107, 0xdc3545\n status = normal\n if error_num >= 5:\n status = error\n elif error_num >= 3:\n status = warning\n embed = discord.Embed(\n title='r6s server status',\n description='{} (Reports in last 20 minutes)'.format(error_num),\n url='https://outage.report/rainbow-six',\n color=status\n )\n return await client.send_message(message.channel, embed=embed)\n\n\nasync def bot_status(client, message, *args, **kwargs):\n embed = discord.Embed(\n title='지금 봇 상태는?',\n description=':robot: :question:',\n color=0x93263f\n )\n embed.add_field(\n name='When start? :alarm_clock:',\n value='Bot run from {start_time} ({uptime})'.format(\n start_time=get_start_time(message.channel.server),\n uptime=get_uptime(message.channel.server)\n ),\n inline=False\n )\n embed.add_field(\n name='# of chats',\n value='{}'.format(get_num_chat(message.channel)),\n inline=True\n )\n embed.add_field(\n name='# of commands',\n value='{}'.format(get_num_command(message.channel)),\n inline=True\n )\n return await client.send_message(message.channel, embed=embed)\n" ]
[ [ "numpy.random.shuffle", "numpy.random.choice" ] ]
MohamedWaelBishr/Quran-Sentiment-Analysis
[ "c0f90da6b0afde307a36b8cbd32311eb76bc035b" ]
[ "Quran Analysis.py" ]
[ "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Oct 28 01:50:11 2019\r\n\r\n@author: Mohamed Wael Bishr\r\n\"\"\"\r\nimport numpy as np # linear algebra\r\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nfrom textblob import TextBlob\r\nimport nltk\r\nnltk.download('stopwords')\r\nfrom nltk.corpus import stopwords \r\nfrom nltk.tokenize import word_tokenize \r\nimport collections\r\nfrom collections import Counter \r\nfrom wordcloud import WordCloud, STOPWORDS \r\n\r\n\r\nnltk.download('punkt')\r\n\r\n# Input data files are available in the \"../input/\" directory.\r\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\r\n# import warnings\r\nimport warnings\r\nS =[]\r\nl=[]\r\nnum=0\r\nAll=[]\r\nsent=0.0\r\nPos=0\r\nNeg=0\r\nNat=0\r\nWords=''\r\nword_counter=0\r\nPOS_LST=[]\r\nNEG_LST=[]\r\nNAT_LST=[]\r\nCloudPOS='';CloudNEG='';CloudNAT=''\r\nCLOUDS=[CloudPOS,CloudNEG,CloudNAT]\r\n# ignore warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\ndf = pd.read_csv('Quran.csv')\r\nprint(plt.style.available) # look at available plot styles\r\nplt.style.use('ggplot')\r\ndf.describe()\r\n\r\ndata= df.drop(columns=['OrignalArabicText', 'ArabicText','ArabicWordCount','ArabicLetterCount'],axis=1)\r\n\r\nfor i in data['SurahNo']:\r\n if i not in l:\r\n l.append(i)\r\n\r\nfor x in range(1,len(l)+1):\r\n for m in data['SurahNo']:\r\n if m == x:\r\n num +=1\r\n S.append([x,num])\r\n num=0\r\n \r\nfor j in range(len(S)):\r\n surah = S[j][0]\r\n aya = S[j][1]\r\n ayas = []\r\n for a in range(len(data['SurahNo'])):\r\n if data['SurahNo'][a] == surah:\r\n ayas.append(data['EnglishTranslation'][a])\r\n All.append([surah,ayas])\r\n ayas=[]\r\n\r\n\r\nfor s in All:\r\n for a in s[1]:\r\n obj = TextBlob(a)\r\n sent = sent + obj.sentiment.polarity\r\n Words+=''+a\r\n result = sent/(len(s[1]))*100\r\n if result > 0:\r\n Pos+=1\r\n elif result < 0:\r\n Neg+=1\r\n else:\r\n Nat+=1\r\n sent=0 \r\nprint(f'''\r\n ==========================\r\n Happy Surahs => {Pos}\r\n Sad Surahs => {Neg}\r\n Natural Surhas => {Nat}\r\n ==========================\r\n ''')\r\n\r\nstoplist = set(stopwords.words('english')) \r\n \r\nword_tokens = word_tokenize(Words) \r\n \r\nfiltered_sentence = [w for w in word_tokens if not w in stoplist] \r\n\r\nimport string\r\ncleanList = []\r\nstring.punctuation\r\nfor i in filtered_sentence:\r\n cleanList.append(i.translate(str.maketrans('','',string.punctuation)))\r\n \r\nfor i in cleanList:\r\n if i=='':\r\n cleanList.remove(i)\r\n \r\n\r\n# Pass the split_it list to instance of Counter class. \r\n\r\n\r\nfor word in cleanList:\r\n obj = TextBlob(word)\r\n sent = obj.sentiment.polarity\r\n if sent >0: POS_LST.append(word)\r\n elif sent < 0 : NEG_LST.append(word)\r\n else: NAT_LST.append(word)\r\n \r\n\r\nC_POS = Counter(POS_LST)\r\nmost_occurPOS = C_POS.most_common(50)\r\ndfPOS = pd.DataFrame(most_occurPOS, columns = ['Word', 'Count'])\r\ndfPOS.plot.bar(x='Word',y='Count')\r\nC_NEG = Counter(NEG_LST)\r\nmost_occurNEG = C_NEG.most_common(50)\r\ndfNEG = pd.DataFrame(most_occurNEG, columns = ['Word', 'Count'])\r\ndfNEG.plot.bar(x='Word',y='Count')\r\nC_NAT = Counter(NAT_LST)\r\nmost_occurNAT = C_NAT.most_common(50)\r\ndfNAT = pd.DataFrame(most_occurNAT, columns = ['Word', 'Count'])\r\ndfNAT.plot.bar(x='Word',y='Count')\r\n# most_common() produces k frequently encountered \r\n# input values and their respective counts. \r\nprint(f'''Pos: {len(POS_LST)} [{len(POS_LST)/len(word_tokens)*100}%]\r\n Neg: {len(NEG_LST)} [{len(NEG_LST)/len(word_tokens)*100}%] \r\n Nat: {len(NAT_LST)} [{len(NAT_LST)/len(word_tokens)*100}%]''')\r\n\r\nfor word in POS_LST:\r\n CloudPOS +=word+' '\r\n \r\nfor word in NEG_LST:\r\n CloudNEG +=word+' '\r\n \r\nfor word in NAT_LST:\r\n CloudNAT +=word+' '\r\nfor cloud in CLOUDS: \r\n wordcloud = WordCloud(width = 800, height = 800, \r\n background_color ='white', \r\n stopwords = stopwords.words(), \r\n min_font_size = 10).generate(cloud) \r\n plt.figure(figsize = (8, 8), facecolor = None) \r\n plt.imshow(wordcloud) \r\n plt.axis(\"off\") \r\n plt.tight_layout(pad = 0) \r\n plt.show() \r\n\r\n" ]
[ [ "matplotlib.pyplot.imshow", "pandas.read_csv", "matplotlib.pyplot.tight_layout", "pandas.DataFrame", "matplotlib.pyplot.axis", "matplotlib.pyplot.show", "matplotlib.pyplot.style.use", "matplotlib.pyplot.figure" ] ]
LeviMatus/roleML
[ "80f5d37b171ed117eaa944da17fca69cc5b85512" ]
[ "roleml/roleml_tests.py" ]
[ "import unittest\nfrom sklearn.externals import joblib\nfrom roleml import roleml\n\n\nclass TestRoleML(unittest.TestCase):\n # This is a list of 50 tuples containing responses from match-v4.\n # Position 0 is the game, position 1 is its timeline, position 2 is the result\n games_timelines_results = joblib.load('games_timelines_results.pkl.z')\n\n def test_predict(self):\n for game, timeline, result in self.games_timelines_results:\n self.assertDictEqual(roleml.predict(game, timeline), result)\n\n def test_fix_game_and_timeline(self):\n # Doing an existence test to test that the new values are properly here\n for game, timeline, result in self.games_timelines_results:\n game_fixed, timeline_fixed = roleml.fix_and_augment_game_and_timeline(game, timeline)\n\n for participant in game_fixed['participants']:\n self.assertIsNotNone(participant['role'])\n\n for frame in timeline_fixed['frames']:\n for participantFrame in frame['participantFrames'].values():\n self.assertIsNotNone(participantFrame['totalGoldDiff'])\n self.assertIsNotNone(participantFrame['xpDiff'])\n self.assertIsNotNone(participantFrame['minionsKilledDiff'])\n self.assertIsNotNone(participantFrame['totalGoldDiff'])\n\n\nif __name__ == '__main__':\n unittest.main()\n\n" ]
[ [ "sklearn.externals.joblib.load" ] ]
iAmCorey/IMP
[ "d7e89a330c999ed3ed2885aeea99c5aa47980feb" ]
[ "mpdemo.py" ]
[ "# -*- coding: utf-8 -*-\n# written by mark zeng 2018-11-14\nfrom multiprocessing import Process, Queue\nimport time\nimport sys\nimport numpy as np\n\nN=10000\n\nclass Worker(Process):\n def __init__(self, inQ, outQ, random_seed):\n super(Worker, self).__init__(target=self.start)\n self.inQ = inQ\n self.outQ = outQ\n # 如果子进程的任务是有随机性的,一定要给每个子进程不同的随机数种子,否则就在重复相同的结果了\n np.random.seed(random_seed)\n\n def run(self):\n while True:\n task = self.inQ.get() # 取出任务, 如果队列为空, 这一步会阻塞直到队列有元素\n res = 0\n for i in range(100):\n res += i\n self.outQ.put(res)\n\ndef create_worker(num,worker):\n for i in range(num):\n worker.append(Worker(Queue(), Queue(), np.random.randint(0, 10 ** 9)))\n worker[i].start()\n\n\ndef finish_worker(worker):\n for w in worker:\n w.terminate()\n\n\nif __name__ == '__main__':\n now = time.time()\n worker = []\n worker_num = 8\n create_worker(worker_num,worker)\n for i in range(N):\n worker[i % worker_num].inQ.put(i)\n result = 0\n for i in range(N):\n print(i)\n result += worker[i % worker_num].inQ.get()\n print(result)\n finish_worker(worker)\n print(time.time()- now)\n" ]
[ [ "numpy.random.seed", "numpy.random.randint" ] ]
AbdulSamadSethi/Intelligent-Personal-Trainer
[ "c6266cb4bfca9d12e09966b69e43ecd856134d21" ]
[ "DTW.py" ]
[ "import pandas as pd\r\nimport math\r\nimport numpy as np\r\n\r\nfrom dtaidistance import dtw\r\nfrom dtaidistance import dtw_visualisation as dtwvis\r\nimport random\r\n\r\ndf_expert = pd.read_csv('workout_coor/out_shoulderpress_expert.csv')\r\ndf_beginner = pd.read_csv('workout_coor/out_shoulderpress_beginner_v2.csv')\r\ndf_bad = pd.read_csv('workout_coor/out_shoulderpress_bad.csv')\r\n\r\ndef getXY(data):\r\n\tx = []\r\n\ty = []\r\n\tfor i in range(len(data)):\r\n\t\tx.append(float(data[i].split(' ')[0]))\r\n\t\ty.append(float(data[i].split(' ')[1]))\r\n\r\n\treturn x, y\r\n\r\ndef angle3pt(ax,ay, bx,by, cx,cy):\r\n # Counterclockwise angle in degrees by turning from a to c around b Returns a float between 0.0 and 360.0\r\n ang = math.degrees(math.atan2(cy-by, cx-bx) - math.atan2(ay-by, ax-bx))\r\n #ang = ang + 360 if ang < 0 else ang\r\n\r\n return abs(ang)\r\n\r\nrshoul_eX, rshoul_eY = getXY(df_expert['RShoulder']) \r\nrelbow_eX, relbow_eY = getXY(df_expert['RElbow'])\r\nrwrist_eX, rwrist_eY = getXY(df_expert['RWrist'])\r\n\r\nrshoul_bX, rshoul_bY = getXY(df_beginner['RShoulder']) \r\nrelbow_bX, relbow_bY = getXY(df_beginner['RElbow'])\r\nrwrist_bX, rwrist_bY = getXY(df_beginner['RWrist'])\r\n\r\nrshoul_bdX, rshoul_bdY = getXY(df_bad['RShoulder']) \r\nrelbow_bdX, relbow_bdY = getXY(df_bad['RElbow'])\r\nrwrist_bdX, rwrist_bdY = getXY(df_bad['RWrist'])\r\n\r\nlshoul_eX, lshoul_eY = getXY(df_expert['LShoulder']) \r\nlelbow_eX, lelbow_eY = getXY(df_expert['LElbow'])\r\nlwrist_eX, lwrist_eY = getXY(df_expert['LWrist'])\r\n\r\nlshoul_bX, lshoul_bY = getXY(df_beginner['LShoulder']) \r\nlelbow_bX, lelbow_bY = getXY(df_beginner['LElbow'])\r\nlwrist_bX, lwrist_bY = getXY(df_beginner['LWrist'])\r\n\r\nlshoul_bdX, lshoul_bdY = getXY(df_bad['LShoulder']) \r\nlelbow_bdX, lelbow_bdY = getXY(df_bad['LElbow'])\r\nlwrist_bdX, lwrist_bdY = getXY(df_bad['LWrist'])\r\n\r\nrightArm_eangles = []\r\nrightArm_bangles = []\r\nrightArm_bdangles = []\r\n\r\nleftArm_eangles = []\r\nleftArm_bangles = []\r\nleftArm_bdangles = []\r\n\r\nfor i in range(len(rshoul_eY)):\r\n\trightArm_eangles.append(angle3pt(rshoul_eX[i],rshoul_eY[i], relbow_eX[i], relbow_eY[i], rwrist_eX[i], rwrist_eY[i]))\r\n\r\nfor i in range(len(rshoul_bY)):\r\n\trightArm_bangles.append(angle3pt(rshoul_bX[i],rshoul_bY[i], relbow_bX[i], relbow_bY[i], rwrist_bX[i], rwrist_bY[i]))\r\n\r\nfor i in range(len(rshoul_bdY)):\r\n\trightArm_bdangles.append(angle3pt(rshoul_bdX[i],rshoul_bdY[i], relbow_bdX[i], relbow_bdY[i], rwrist_bdX[i], rwrist_bdY[i]))\r\n\r\nfor i in range(len(lshoul_eY)):\r\n\tleftArm_eangles.append(angle3pt(lshoul_eX[i],lshoul_eY[i], lelbow_eX[i], lelbow_eY[i], lwrist_eX[i], lwrist_eY[i]))\r\n\r\nfor i in range(len(lshoul_bY)):\r\n\tleftArm_bangles.append(angle3pt(lshoul_bX[i],lshoul_bY[i], lelbow_bX[i], lelbow_bY[i], lwrist_bX[i], lwrist_bY[i]))\r\n\r\nfor i in range(len(lshoul_bdY)):\r\n\tleftArm_bdangles.append(angle3pt(lshoul_bdX[i],lshoul_bdY[i], lelbow_bdX[i], lelbow_bdY[i], lwrist_bdX[i], lwrist_bdY[i]))\r\n\r\nleftArm_b = np.asarray(leftArm_bangles, dtype = np.float32)\r\nleftArm_e = np.asarray(leftArm_eangles, dtype = np.float32)\r\n\r\n#distance = dtw.distance(leftArm_eangles[:250], leftArm_bangles[:250])\r\n#print(distance)\r\n\r\nd, path = dtw.warping_paths(leftArm_b, leftArm_e)\r\nbest_path = dtw.best_path(paths)\r\ndtwvis.plot_warping(leftArm_b, leftArm_e, best_path, filename = \"test11.png\")\r\n#print(paths)\r\n#dtwvis.plot_warpingpaths(leftArm_e, leftArm_b, paths, path = best_path, filename = \"Graphs/bestpath_window100+psi5.png\") \r\n" ]
[ [ "numpy.asarray", "pandas.read_csv" ] ]
zelros/cinnamon
[ "9fbac281ed3ab2a1ce61fb48d845f3a6e97d1221" ]
[ "src/cinnamon/common/dev_utils.py" ]
[ "import sys\nimport numpy as np\n\n\ndef safe_isinstance(obj, class_path_str):\n # this function is copy-paste from the code of the SHAP Python library\n # Copyright (c) 2018 Scott Lundberg\n\n \"\"\"\n Acts as a safe version of isinstance without having to explicitly\n import packages which may not exist in the users environment.\n Checks if obj is an instance of type specified by class_path_str.\n Parameters\n ----------\n obj: Any\n Some object you want to test against\n class_path_str: str or list\n A string or list of strings specifying full class paths\n Example: `sklearn.ensemble.RandomForestRegressor`\n Returns\n --------\n bool: True if isinstance is true and the package exists, False otherwise\n \"\"\"\n if isinstance(class_path_str, str):\n class_path_strs = [class_path_str]\n elif isinstance(class_path_str, list) or isinstance(class_path_str, tuple):\n class_path_strs = class_path_str\n else:\n class_path_strs = ['']\n\n # try each module path in order\n for class_path_str in class_path_strs:\n if \".\" not in class_path_str:\n raise ValueError(\"class_path_str must be a string or list of strings specifying a full \\\n module path to a class. Eg, 'sklearn.ensemble.RandomForestRegressor'\")\n\n # Splits on last occurence of \".\"\n module_name, class_name = class_path_str.rsplit(\".\", 1)\n\n # here we don't check further if the model is not imported, since we shouldn't have\n # an object of that types passed to us if the model the type is from has never been\n # imported. (and we don't want to import lots of new modules for no reason)\n if module_name not in sys.modules:\n continue\n\n module = sys.modules[module_name]\n\n #Get class\n _class = getattr(module, class_name, None)\n\n if _class is None:\n continue\n\n if isinstance(obj, _class):\n return True\n\n return False\n\n\ndef find_uniques(*arrays: np.array):\n uniques = set()\n for a in arrays:\n for x in np.unique(a):\n uniques.add(x)\n uniques.discard(None)\n return list(uniques)\n" ]
[ [ "numpy.unique" ] ]
MakowToms/GeneticTree
[ "c39288c7689a41e169bb876b1ee0aa7fac43d8ec" ]
[ "tests/set_up_variables_and_imports.py" ]
[ "from tree.tree import Tree, Observation\nfrom tree.builder import Builder, FullTreeBuilder\nfrom tree.forest import Forest\nfrom tree.crosser import TreeCrosser\n\nfrom sklearn import datasets\nimport numpy as np\nimport pytest\n\nfrom sklearn.utils._testing import assert_allclose\nfrom sklearn.utils._testing import assert_array_equal\nfrom sklearn.utils._testing import assert_array_almost_equal\nfrom sklearn.utils._testing import assert_almost_equal\nfrom sklearn.utils._testing import assert_warns\nfrom sklearn.utils._testing import assert_warns_message\nfrom sklearn.utils._testing import create_memmap_backed_data\nfrom sklearn.utils._testing import ignore_warnings\n\n# load iris dataset and randomly permute it (example from sklearn.tree.test.test_tree)\niris = datasets.load_iris()\nrng = np.random.RandomState(1)\nperm = rng.permutation(iris.target.size)\niris.data = iris.data[perm]\niris.target = iris.target[perm]\n\nX = iris.data\ny = iris.target\n" ]
[ [ "numpy.random.RandomState", "sklearn.datasets.load_iris" ] ]
ECNU-ICA/ECNU-SenseMaker
[ "24f829c3dfefccea5fecbbe75904858ec1fefffb" ]
[ "optimizer.py" ]
[ "import math\nimport torch\nfrom torch.optim.optimizer import Optimizer\n\n\nclass Adam_GCC(Optimizer):\n \"\"\"\n 参考链接:https://zhuanlan.zhihu.com/p/128553061\n \"\"\"\n\n def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8,\n weight_decay=0, amsgrad=False):\n if not 0.0 <= lr:\n raise ValueError(\"Invalid learning rate: {}\".format(lr))\n if not 0.0 <= eps:\n raise ValueError(\"Invalid epsilon value: {}\".format(eps))\n if not 0.0 <= betas[0] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 0: {}\".format(betas[0]))\n if not 0.0 <= betas[1] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 1: {}\".format(betas[1]))\n defaults = dict(lr=lr, betas=betas, eps=eps,\n weight_decay=weight_decay, amsgrad=amsgrad)\n super(Adam_GCC, self).__init__(params, defaults)\n\n def __setstate__(self, state):\n super(Adam_GCC, self).__setstate__(state)\n for group in self.param_groups:\n group.setdefault('amsgrad', False)\n\n def step(self, closure=None):\n \"\"\"Performs a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n loss = closure()\n\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n if grad.is_sparse:\n raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead')\n amsgrad = group['amsgrad']\n\n state = self.state[p]\n\n # State initialization\n if len(state) == 0:\n state['step'] = 0\n # Exponential moving average of gradient values\n state['exp_avg'] = torch.zeros_like(p.data)\n # Exponential moving average of squared gradient values\n state['exp_avg_sq'] = torch.zeros_like(p.data)\n if amsgrad:\n # Maintains max of all exp. moving avg. of sq. grad. values\n state['max_exp_avg_sq'] = torch.zeros_like(p.data)\n\n exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n if amsgrad:\n max_exp_avg_sq = state['max_exp_avg_sq']\n beta1, beta2 = group['betas']\n\n state['step'] += 1\n bias_correction1 = 1 - beta1 ** state['step']\n bias_correction2 = 1 - beta2 ** state['step']\n\n if group['weight_decay'] != 0:\n grad.add_(group['weight_decay'], p.data)\n\n # GC operation for Conv layers\n if len(list(grad.size())) > 3:\n grad.add_(-grad.mean(dim=tuple(range(1, len(list(grad.size())))), keepdim=True))\n\n # Decay the first and second moment running average coefficient\n exp_avg.mul_(beta1).add_(1 - beta1, grad)\n exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n if amsgrad:\n # Maintains the maximum of all 2nd moment running avg. till now\n torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)\n # Use the max. for normalizing running avg. of gradient\n denom = (max_exp_avg_sq.sqrt() / math.sqrt(bias_correction2)).add_(group['eps'])\n else:\n denom = (exp_avg_sq.sqrt() / math.sqrt(bias_correction2)).add_(group['eps'])\n\n step_size = group['lr'] / bias_correction1\n\n p.data.addcdiv_(-step_size, exp_avg, denom)\n\n return loss\n\n\nclass Adam_GCC2(Optimizer):\n def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8,\n weight_decay=0, amsgrad=False):\n if not 0.0 <= lr:\n raise ValueError(\"Invalid learning rate: {}\".format(lr))\n if not 0.0 <= eps:\n raise ValueError(\"Invalid epsilon value: {}\".format(eps))\n if not 0.0 <= betas[0] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 0: {}\".format(betas[0]))\n if not 0.0 <= betas[1] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 1: {}\".format(betas[1]))\n defaults = dict(lr=lr, betas=betas, eps=eps,\n weight_decay=weight_decay, amsgrad=amsgrad)\n super(Adam_GCC2, self).__init__(params, defaults)\n\n def __setstate__(self, state):\n super(Adam_GCC2, self).__setstate__(state)\n for group in self.param_groups:\n group.setdefault('amsgrad', False)\n\n def step(self, closure=None):\n \"\"\"Performs a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n loss = closure()\n\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n if grad.is_sparse:\n raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead')\n amsgrad = group['amsgrad']\n\n state = self.state[p]\n\n # State initialization\n if len(state) == 0:\n state['step'] = 0\n # Exponential moving average of gradient values\n state['exp_avg'] = torch.zeros_like(p.data)\n # Exponential moving average of squared gradient values\n state['exp_avg_sq'] = torch.zeros_like(p.data)\n if amsgrad:\n # Maintains max of all exp. moving avg. of sq. grad. values\n state['max_exp_avg_sq'] = torch.zeros_like(p.data)\n\n exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n if amsgrad:\n max_exp_avg_sq = state['max_exp_avg_sq']\n beta1, beta2 = group['betas']\n\n state['step'] += 1\n bias_correction1 = 1 - beta1 ** state['step']\n bias_correction2 = 1 - beta2 ** state['step']\n\n if group['weight_decay'] != 0:\n grad.add_(group['weight_decay'], p.data)\n\n # GC operation for Conv layers\n if len(list(p.data.size())) == 4:\n weight_mean = p.data.mean(dim=tuple(range(1, len(list(grad.size())))), keepdim=True)\n grad.add_(-grad.mean(dim=1, keepdim=True).mean(dim=2, keepdim=True).mean(dim=3, keepdim=True))\n\n # Decay the first and second moment running average coefficient\n exp_avg.mul_(beta1).add_(1 - beta1, grad)\n exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n if amsgrad:\n # Maintains the maximum of all 2nd moment running avg. till now\n torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)\n # Use the max. for normalizing running avg. of gradient\n denom = (max_exp_avg_sq.sqrt() / math.sqrt(bias_correction2)).add_(group['eps'])\n else:\n denom = (exp_avg_sq.sqrt() / math.sqrt(bias_correction2)).add_(group['eps'])\n\n step_size = group['lr'] / bias_correction1\n\n p.data.addcdiv_(-step_size, exp_avg, denom)\n # keep mean unchanged\n if len(list(grad.size())) == 4:\n p.data.add_(-p.data.mean(dim=tuple(range(1, len(list(grad.size())))), keepdim=True)).add_(\n weight_mean)\n return loss\n\n\nclass Adam_GC(Optimizer):\n r\"\"\"Implements Adam algorithm.\n\n It has been proposed in `Adam: A Method for Stochastic Optimization`_.\n\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n lr (float, optional): learning rate (default: 1e-3)\n betas (Tuple[float, float], optional): coefficients used for computing\n running averages of gradient and its square (default: (0.9, 0.999))\n eps (float, optional): term added to the denominator to improve\n numerical stability (default: 1e-8)\n weight_decay (float, optional): weight decay (L2 penalty) (default: 0)\n amsgrad (boolean, optional): whether to use the AMSGrad variant of this\n algorithm from the paper `On the Convergence of Adam and Beyond`_\n (default: False)\n\n .. _Adam\\: A Method for Stochastic Optimization:\n https://arxiv.org/abs/1412.6980\n .. _On the Convergence of Adam and Beyond:\n https://openreview.net/forum?id=ryQu7f-RZ\n \"\"\"\n\n def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8,\n weight_decay=0, amsgrad=False):\n if not 0.0 <= lr:\n raise ValueError(\"Invalid learning rate: {}\".format(lr))\n if not 0.0 <= eps:\n raise ValueError(\"Invalid epsilon value: {}\".format(eps))\n if not 0.0 <= betas[0] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 0: {}\".format(betas[0]))\n if not 0.0 <= betas[1] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 1: {}\".format(betas[1]))\n defaults = dict(lr=lr, betas=betas, eps=eps,\n weight_decay=weight_decay, amsgrad=amsgrad)\n super(Adam_GC, self).__init__(params, defaults)\n\n def __setstate__(self, state):\n super(Adam_GC, self).__setstate__(state)\n for group in self.param_groups:\n group.setdefault('amsgrad', False)\n\n def step(self, closure=None):\n \"\"\"Performs a single optimization step.\n\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n loss = closure()\n\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n if grad.is_sparse:\n raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead')\n amsgrad = group['amsgrad']\n\n state = self.state[p]\n\n # State initialization\n if len(state) == 0:\n state['step'] = 0\n # Exponential moving average of gradient values\n state['exp_avg'] = torch.zeros_like(p.data)\n # Exponential moving average of squared gradient values\n state['exp_avg_sq'] = torch.zeros_like(p.data)\n if amsgrad:\n # Maintains max of all exp. moving avg. of sq. grad. values\n state['max_exp_avg_sq'] = torch.zeros_like(p.data)\n\n exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n if amsgrad:\n max_exp_avg_sq = state['max_exp_avg_sq']\n beta1, beta2 = group['betas']\n\n state['step'] += 1\n bias_correction1 = 1 - beta1 ** state['step']\n bias_correction2 = 1 - beta2 ** state['step']\n\n if group['weight_decay'] != 0:\n grad.add_(group['weight_decay'], p.data)\n\n # GC operation for Conv layers and FC layers\n if len(list(grad.size())) > 1:\n grad.add_(-grad.mean(dim=tuple(range(1, len(list(grad.size())))), keepdim=True))\n\n # Decay the first and second moment running average coefficient\n exp_avg.mul_(beta1).add_(1 - beta1, grad)\n exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n if amsgrad:\n # Maintains the maximum of all 2nd moment running avg. till now\n torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)\n # Use the max. for normalizing running avg. of gradient\n denom = (max_exp_avg_sq.sqrt() / math.sqrt(bias_correction2)).add_(group['eps'])\n else:\n denom = (exp_avg_sq.sqrt() / math.sqrt(bias_correction2)).add_(group['eps'])\n\n step_size = group['lr'] / bias_correction1\n\n p.data.addcdiv_(-step_size, exp_avg, denom)\n\n return loss\n\n\nclass AdamW(Optimizer):\n \"\"\"Implements Adam algorithm.\n It has been proposed in `Adam: A Method for Stochastic Optimization`_.\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n lr (float, optional): learning rate (default: 1e-3)\n betas (Tuple[float, float], optional): coefficients used for computing\n running averages of gradient and its square (default: (0.9, 0.999))\n eps (float, optional): term added to the denominator to improve\n numerical stability (default: 1e-8)\n weight_decay (float, optional): weight decay (L2 penalty) (default: 0)\n amsgrad (boolean, optional): whether to use the AMSGrad variant of this\n algorithm from the paper `On the Convergence of Adam and Beyond`_\n .. _Adam\\: A Method for Stochastic Optimization:\n https://arxiv.org/abs/1412.6980\n .. _On the Convergence of Adam and Beyond:\n https://openreview.net/forum?id=ryQu7f-RZ\n \"\"\"\n\n def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8,\n weight_decay=0, amsgrad=False):\n if not 0.0 <= lr:\n raise ValueError(\"Invalid learning rate: {}\".format(lr))\n if not 0.0 <= eps:\n raise ValueError(\"Invalid epsilon value: {}\".format(eps))\n if not 0.0 <= betas[0] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 0: {}\".format(betas[0]))\n if not 0.0 <= betas[1] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 1: {}\".format(betas[1]))\n defaults = dict(lr=lr, betas=betas, eps=eps,\n weight_decay=weight_decay, amsgrad=amsgrad)\n super(AdamW, self).__init__(params, defaults)\n\n def __setstate__(self, state):\n super(AdamW, self).__setstate__(state)\n for group in self.param_groups:\n group.setdefault('amsgrad', False)\n\n def step(self, closure=None):\n \"\"\"Performs a single optimization step.\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n loss = closure()\n\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n if grad.is_sparse:\n raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead')\n amsgrad = group['amsgrad']\n\n state = self.state[p]\n\n # State initialization\n if len(state) == 0:\n state['step'] = 0\n # Exponential moving average of gradient values\n state['exp_avg'] = torch.zeros_like(p.data)\n # Exponential moving average of squared gradient values\n state['exp_avg_sq'] = torch.zeros_like(p.data)\n if amsgrad:\n # Maintains max of all exp. moving avg. of sq. grad. values\n state['max_exp_avg_sq'] = torch.zeros_like(p.data)\n\n exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n if amsgrad:\n max_exp_avg_sq = state['max_exp_avg_sq']\n beta1, beta2 = group['betas']\n\n state['step'] += 1\n\n # if group['weight_decay'] != 0:\n # grad = grad.add(group['weight_decay'], p.data)\n\n # Decay the first and second moment running average coefficient\n exp_avg.mul_(beta1).add_(1 - beta1, grad)\n exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n if amsgrad:\n # Maintains the maximum of all 2nd moment running avg. till now\n torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)\n # Use the max. for normalizing running avg. of gradient\n denom = max_exp_avg_sq.sqrt().add_(group['eps'])\n else:\n denom = exp_avg_sq.sqrt().add_(group['eps'])\n\n bias_correction1 = 1 - beta1 ** state['step']\n bias_correction2 = 1 - beta2 ** state['step']\n step_size = group['lr'] * math.sqrt(bias_correction2) / bias_correction1\n\n # p.data.addcdiv_(-step_size, exp_avg, denom)\n p.data.add_(-step_size, torch.mul(p.data, group['weight_decay']).addcdiv_(1, exp_avg, denom))\n\n return loss\n\n\nclass AdamW_GCC(Optimizer):\n \"\"\"Implements Adam algorithm.\n It has been proposed in `Adam: A Method for Stochastic Optimization`_.\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n lr (float, optional): learning rate (default: 1e-3)\n betas (Tuple[float, float], optional): coefficients used for computing\n running averages of gradient and its square (default: (0.9, 0.999))\n eps (float, optional): term added to the denominator to improve\n numerical stability (default: 1e-8)\n weight_decay (float, optional): weight decay (L2 penalty) (default: 0)\n amsgrad (boolean, optional): whether to use the AMSGrad variant of this\n algorithm from the paper `On the Convergence of Adam and Beyond`_\n .. _Adam\\: A Method for Stochastic Optimization:\n https://arxiv.org/abs/1412.6980\n .. _On the Convergence of Adam and Beyond:\n https://openreview.net/forum?id=ryQu7f-RZ\n \"\"\"\n\n def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8,\n weight_decay=0, amsgrad=False):\n if not 0.0 <= lr:\n raise ValueError(\"Invalid learning rate: {}\".format(lr))\n if not 0.0 <= eps:\n raise ValueError(\"Invalid epsilon value: {}\".format(eps))\n if not 0.0 <= betas[0] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 0: {}\".format(betas[0]))\n if not 0.0 <= betas[1] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 1: {}\".format(betas[1]))\n defaults = dict(lr=lr, betas=betas, eps=eps,\n weight_decay=weight_decay, amsgrad=amsgrad)\n super(AdamW_GCC, self).__init__(params, defaults)\n\n def __setstate__(self, state):\n super(AdamW_GCC, self).__setstate__(state)\n for group in self.param_groups:\n group.setdefault('amsgrad', False)\n\n def step(self, closure=None):\n \"\"\"Performs a single optimization step.\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n loss = closure()\n\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n if grad.is_sparse:\n raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead')\n amsgrad = group['amsgrad']\n\n state = self.state[p]\n\n # State initialization\n if len(state) == 0:\n state['step'] = 0\n # Exponential moving average of gradient values\n state['exp_avg'] = torch.zeros_like(p.data)\n # Exponential moving average of squared gradient values\n state['exp_avg_sq'] = torch.zeros_like(p.data)\n if amsgrad:\n # Maintains max of all exp. moving avg. of sq. grad. values\n state['max_exp_avg_sq'] = torch.zeros_like(p.data)\n\n exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n if amsgrad:\n max_exp_avg_sq = state['max_exp_avg_sq']\n beta1, beta2 = group['betas']\n\n # GC operation for Conv layers\n if len(list(grad.size())) > 3:\n grad.add_(-grad.mean(dim=tuple(range(1, len(list(grad.size())))), keepdim=True))\n\n state['step'] += 1\n\n # if group['weight_decay'] != 0:\n # grad = grad.add(group['weight_decay'], p.data)\n\n # Decay the first and second moment running average coefficient\n exp_avg.mul_(beta1).add_(1 - beta1, grad)\n exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n if amsgrad:\n # Maintains the maximum of all 2nd moment running avg. till now\n torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)\n # Use the max. for normalizing running avg. of gradient\n denom = max_exp_avg_sq.sqrt().add_(group['eps'])\n else:\n denom = exp_avg_sq.sqrt().add_(group['eps'])\n\n bias_correction1 = 1 - beta1 ** state['step']\n bias_correction2 = 1 - beta2 ** state['step']\n step_size = group['lr'] * math.sqrt(bias_correction2) / bias_correction1\n\n # p.data.addcdiv_(-step_size, exp_avg, denom)\n p.data.add_(-step_size, torch.mul(p.data, group['weight_decay']).addcdiv_(1, exp_avg, denom))\n\n return loss\n\n\nclass AdamW_GCC2(Optimizer):\n \"\"\"Implements Adam algorithm.\n It has been proposed in `Adam: A Method for Stochastic Optimization`_.\n Arguments:\n params (iterable): iterable of parameters to optimize or dicts defining\n parameter groups\n lr (float, optional): learning rate (default: 1e-3)\n betas (Tuple[float, float], optional): coefficients used for computing\n running averages of gradient and its square (default: (0.9, 0.999))\n eps (float, optional): term added to the denominator to improve\n numerical stability (default: 1e-8)\n weight_decay (float, optional): weight decay (L2 penalty) (default: 0)\n amsgrad (boolean, optional): whether to use the AMSGrad variant of this\n algorithm from the paper `On the Convergence of Adam and Beyond`_\n .. _Adam\\: A Method for Stochastic Optimization:\n https://arxiv.org/abs/1412.6980\n .. _On the Convergence of Adam and Beyond:\n https://openreview.net/forum?id=ryQu7f-RZ\n \"\"\"\n\n def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8,\n weight_decay=0, amsgrad=False):\n if not 0.0 <= lr:\n raise ValueError(\"Invalid learning rate: {}\".format(lr))\n if not 0.0 <= eps:\n raise ValueError(\"Invalid epsilon value: {}\".format(eps))\n if not 0.0 <= betas[0] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 0: {}\".format(betas[0]))\n if not 0.0 <= betas[1] < 1.0:\n raise ValueError(\"Invalid beta parameter at index 1: {}\".format(betas[1]))\n defaults = dict(lr=lr, betas=betas, eps=eps,\n weight_decay=weight_decay, amsgrad=amsgrad)\n super(AdamW_GCC2, self).__init__(params, defaults)\n\n def __setstate__(self, state):\n super(AdamW_GCC2, self).__setstate__(state)\n for group in self.param_groups:\n group.setdefault('amsgrad', False)\n\n def step(self, closure=None):\n \"\"\"Performs a single optimization step.\n Arguments:\n closure (callable, optional): A closure that reevaluates the model\n and returns the loss.\n \"\"\"\n loss = None\n if closure is not None:\n loss = closure()\n\n for group in self.param_groups:\n for p in group['params']:\n if p.grad is None:\n continue\n grad = p.grad.data\n if grad.is_sparse:\n raise RuntimeError('Adam does not support sparse gradients, please consider SparseAdam instead')\n amsgrad = group['amsgrad']\n\n state = self.state[p]\n\n # State initialization\n if len(state) == 0:\n state['step'] = 0\n # Exponential moving average of gradient values\n state['exp_avg'] = torch.zeros_like(p.data)\n # Exponential moving average of squared gradient values\n state['exp_avg_sq'] = torch.zeros_like(p.data)\n if amsgrad:\n # Maintains max of all exp. moving avg. of sq. grad. values\n state['max_exp_avg_sq'] = torch.zeros_like(p.data)\n\n exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n if amsgrad:\n max_exp_avg_sq = state['max_exp_avg_sq']\n beta1, beta2 = group['betas']\n\n # GC operation for Conv layers\n if len(list(grad.size())) > 3:\n weight_mean = p.data.mean(dim=tuple(range(1, len(list(grad.size())))), keepdim=True)\n grad.add_(-grad.mean(dim=tuple(range(1, len(list(grad.size())))), keepdim=True))\n\n state['step'] += 1\n\n # if group['weight_decay'] != 0:\n # grad = grad.add(group['weight_decay'], p.data)\n\n # Decay the first and second moment running average coefficient\n exp_avg.mul_(beta1).add_(1 - beta1, grad)\n exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n if amsgrad:\n # Maintains the maximum of all 2nd moment running avg. till now\n torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq)\n # Use the max. for normalizing running avg. of gradient\n denom = max_exp_avg_sq.sqrt().add_(group['eps'])\n else:\n denom = exp_avg_sq.sqrt().add_(group['eps'])\n\n bias_correction1 = 1 - beta1 ** state['step']\n bias_correction2 = 1 - beta2 ** state['step']\n step_size = group['lr'] * math.sqrt(bias_correction2) / bias_correction1\n\n # p.data.addcdiv_(-step_size, exp_avg, denom)\n p.data.add_(-step_size, torch.mul(p.data, group['weight_decay']).addcdiv_(1, exp_avg, denom))\n if len(list(grad.size())) > 3:\n p.data.add_(-p.data.mean(dim=tuple(range(1, len(list(grad.size())))), keepdim=True)).add_(\n weight_mean)\n return loss\n" ]
[ [ "torch.mul", "torch.zeros_like", "torch.max" ] ]
danielbraithwt/University
[ "50c6a904e1c53c03bce9928975607c35fd741e33" ]
[ "Undergraduate/COMP312/Assignment5/q5.py" ]
[ "\"\"\"(q3.py) M/M/c queueing system with monitor\n and multiple replications\"\"\"\n\nfrom SimPy.Simulation import *\nimport random\nimport numpy\nimport math\n\n## Useful extras ----------\ndef conf(L):\n \"\"\"confidence interval\"\"\"\n lower = numpy.mean(L) - 1.96*numpy.std(L)/math.sqrt(len(L))\n upper = numpy.mean(L) + 1.96*numpy.std(L)/math.sqrt(len(L))\n return (lower,upper)\n\n## Model ----------\nclass Source(Process):\n \"\"\"generate random arrivals\"\"\"\n def run(self, N, lamb, mu):\n for i in range(N):\n a = Arrival(str(i))\n activate(a, a.run(mu))\n t = random.expovariate(lamb)\n yield hold, self, t\n\nclass Arrival(Process):\n n = 0\n \n \"\"\"an arrival\"\"\"\n def run(self, mu):\n arrivetime = now()\n \n Arrival.n += 1\n if Arrival.n < len(G.custmon):\n G.custmon[Arrival.n].observe(now())\n \n yield request, self, G.server\n t = random.expovariate(mu)\n yield hold, self, t\n yield release, self, G.server\n delay = now()-arrivetime\n G.delaymon.observe(delay)\n\n Arrival.n -= 1\n if Arrival.n < len(G.custmon):\n G.custmon[Arrival.n].observe(now())\n\n\n\nclass G:\n server = 'dummy'\n delaymon = 'Monitor'\n custmon = 'Monitor'\n\ndef model(c, N, K, lamb, mu, maxtime, rvseed):\n # setup\n initialize()\n random.seed(rvseed)\n G.server = Resource(c)\n G.delaymon = Monitor()\n custmon = []\n for i in range(K):\n custmon.append(Monitor())\n \n # simulate\n s = Source('Source')\n activate(s, s.run(N, lamb, mu))\n simulate(until=maxtime)\n \n # gather performance measures\n W = G.delaymon.mean()\n return(W)\n\n## Experiment ----------\nallW = []\nfor k in range(50):\n seed = 123*k\n result = model(c=1, N=10000, K=10, lamb=0.96, mu=1.00,\n maxtime=2000000, rvseed=seed)\n allW.append(result)\nprint (allW)\nprint (\"\")\nprint (\"Estimate of W:\",numpy.mean(allW))\nprint (\"Conf int of W:\",conf(allW))\n\n\n" ]
[ [ "numpy.std", "numpy.mean" ] ]
alfredtorres/SRN-Pytorch
[ "fa9ece3d08bfddf05822815cfc62c946664cbcd7" ]
[ "pointnet2/data/data_utils.py" ]
[ "from __future__ import (\n division,\n absolute_import,\n with_statement,\n print_function,\n unicode_literals,\n)\nimport torch\nimport numpy as np\n\n\ndef angle_axis(angle, axis):\n # type: (float, np.ndarray) -> float\n r\"\"\"Returns a 4x4 rotation matrix that performs a rotation around axis by angle\n\n Parameters\n ----------\n angle : float\n Angle to rotate by\n axis: np.ndarray\n Axis to rotate about\n\n Returns\n -------\n torch.Tensor\n 3x3 rotation matrix\n \"\"\"\n u = axis / np.linalg.norm(axis)\n cosval, sinval = np.cos(angle), np.sin(angle)\n\n # yapf: disable\n cross_prod_mat = np.array([[0.0, -u[2], u[1]],\n [u[2], 0.0, -u[0]],\n [-u[1], u[0], 0.0]])\n\n R = torch.from_numpy(\n cosval * np.eye(3)\n + sinval * cross_prod_mat\n + (1.0 - cosval) * np.outer(u, u)\n )\n # yapf: enable\n return R.float()\n\n\nclass PointcloudScale(object):\n def __init__(self, lo=0.8, hi=1.25):\n self.lo, self.hi = lo, hi\n\n def __call__(self, points):\n scaler = np.random.uniform(self.lo, self.hi)\n points[:, 0:3] *= scaler\n return points\n\n\nclass PointcloudRotate(object):\n def __init__(self, axis=np.array([0.0, 1.0, 0.0])):\n self.axis = axis\n\n def __call__(self, points):\n rotation_angle = np.random.uniform() * 2 * np.pi\n rotation_matrix = angle_axis(rotation_angle, self.axis)\n\n normals = points.size(1) > 3\n\n if not normals:\n return torch.matmul(points, rotation_matrix.t())\n else:\n pc_xyz = points[:, 0:3]\n pc_normals = points[:, 3:]\n points[:, 0:3] = torch.matmul(pc_xyz, rotation_matrix.t())\n points[:, 3:] = torch.matmul(pc_normals, rotation_matrix.t())\n\n return points\n\nclass PointcloudRotatebyAngle(object):\n def __init__(self, rotation_angle, axis=np.array([0.0, 1.0, 0.0])):\n self.axis = axis\n self.rotation_angle = rotation_angle\n\n def __call__(self, points):\n# rotation_angle = np.random.uniform() * 2 * np.pi\n rotation_matrix = angle_axis(self.rotation_angle, self.axis)\n\n normals = points.size(1) > 3\n if points.is_cuda:\n rotation_matrix = rotation_matrix.cuda()\n if not normals:\n return torch.matmul(points, rotation_matrix.t())\n else:\n pc_xyz = points[:, 0:3]\n pc_normals = points[:, 3:]\n points[:, 0:3] = torch.matmul(pc_xyz, rotation_matrix.t())\n points[:, 3:] = torch.matmul(pc_normals, rotation_matrix.t())\n\n return points\n\nclass PointcloudRotatePerturbation(object):\n def __init__(self, angle_sigma=0.06, angle_clip=0.18):\n self.angle_sigma, self.angle_clip = angle_sigma, angle_clip\n\n def _get_angles(self):\n angles = np.clip(\n self.angle_sigma * np.random.randn(3), -self.angle_clip, self.angle_clip\n )\n\n return angles\n\n def __call__(self, points):\n angles = self._get_angles()\n Rx = angle_axis(angles[0], np.array([1.0, 0.0, 0.0]))\n Ry = angle_axis(angles[1], np.array([0.0, 1.0, 0.0]))\n Rz = angle_axis(angles[2], np.array([0.0, 0.0, 1.0]))\n\n rotation_matrix = torch.matmul(torch.matmul(Rz, Ry), Rx)\n\n normals = points.size(1) > 3\n if not normals:\n return torch.matmul(points, rotation_matrix.t())\n else:\n pc_xyz = points[:, 0:3]\n pc_normals = points[:, 3:]\n points[:, 0:3] = torch.matmul(pc_xyz, rotation_matrix.t())\n points[:, 3:] = torch.matmul(pc_normals, rotation_matrix.t())\n\n return points\n\n\nclass PointcloudJitter(object):\n def __init__(self, std=0.01, clip=0.05):\n self.std, self.clip = std, clip\n\n def __call__(self, points):\n jittered_data = (\n points.new(points.size(0), 3)\n .normal_(mean=0.0, std=self.std)\n .clamp_(-self.clip, self.clip)\n )\n points[:, 0:3] += jittered_data\n return points\n\n\nclass PointcloudTranslate(object):\n def __init__(self, translate_range=0.1):\n self.translate_range = translate_range\n\n def __call__(self, points):\n translation = np.random.uniform(-self.translate_range, self.translate_range)\n points[:, 0:3] += translation\n return points\n\n\nclass PointcloudToTensor(object):\n def __call__(self, points):\n return torch.from_numpy(points).float()\n\n\nclass PointcloudRandomInputDropout(object):\n def __init__(self, max_dropout_ratio=0.875):\n assert max_dropout_ratio >= 0 and max_dropout_ratio < 1\n self.max_dropout_ratio = max_dropout_ratio\n\n def __call__(self, points):\n pc = points.numpy()\n\n dropout_ratio = np.random.random() * self.max_dropout_ratio # 0~0.875\n drop_idx = np.where(np.random.random((pc.shape[0])) <= dropout_ratio)[0]\n if len(drop_idx) > 0:\n pc[drop_idx] = pc[0] # set to the first point\n\n return torch.from_numpy(pc).float()\n" ]
[ [ "numpy.random.random", "numpy.eye", "numpy.cos", "numpy.linalg.norm", "numpy.sin", "torch.from_numpy", "torch.matmul", "numpy.random.randn", "numpy.random.uniform", "numpy.array", "numpy.outer" ] ]
Xtuden-com/motion_imitation
[ "d04b1d1cc59bcfb2781cb399f1a3aeec9b3b3562" ]
[ "motion_imitation/robots/minitaur.py" ]
[ "# coding=utf-8\n# Copyright 2020 The Google Research 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\"\"\"This file implements the functionalities of a minitaur using pybullet.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport inspect\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(os.path.dirname(currentdir))\nos.sys.path.insert(0, parentdir)\n\nimport collections\nimport copy\nimport math\nimport re\nimport numpy as np\nfrom motion_imitation.robots import minitaur_constants\nfrom motion_imitation.robots import minitaur_motor\nfrom motion_imitation.robots import robot_config\nfrom motion_imitation.robots import action_filter\nfrom motion_imitation.robots import kinematics\n\nINIT_POSITION = [0, 0, .2]\nINIT_RACK_POSITION = [0, 0, 1]\nINIT_ORIENTATION = [0, 0, 0, 1]\nKNEE_CONSTRAINT_POINT_RIGHT = [0, 0.005, 0.2]\nKNEE_CONSTRAINT_POINT_LEFT = [0, 0.01, 0.2]\nOVERHEAT_SHUTDOWN_TORQUE = 2.45\nOVERHEAT_SHUTDOWN_TIME = 1.0\nLEG_POSITION = [\"front_left\", \"back_left\", \"front_right\", \"back_right\"]\nMOTOR_NAMES = [\n \"motor_front_leftL_joint\", \"motor_front_leftR_joint\",\n \"motor_back_leftL_joint\", \"motor_back_leftR_joint\",\n \"motor_front_rightL_joint\", \"motor_front_rightR_joint\",\n \"motor_back_rightL_joint\", \"motor_back_rightR_joint\"\n]\n_CHASSIS_NAME_PATTERN = re.compile(r\"chassis\\D*center\")\n_MOTOR_NAME_PATTERN = re.compile(r\"motor\\D*joint\")\n_KNEE_NAME_PATTERN = re.compile(r\"knee\\D*\")\n_BRACKET_NAME_PATTERN = re.compile(r\"motor\\D*_bracket_joint\")\n_LEG_NAME_PATTERN1 = re.compile(r\"hip\\D*joint\")\n_LEG_NAME_PATTERN2 = re.compile(r\"hip\\D*link\")\n_LEG_NAME_PATTERN3 = re.compile(r\"motor\\D*link\")\nSENSOR_NOISE_STDDEV = (0.0, 0.0, 0.0, 0.0, 0.0)\nMINITAUR_DEFAULT_MOTOR_DIRECTIONS = (-1, -1, -1, -1, 1, 1, 1, 1)\nMINITAUR_DEFAULT_MOTOR_OFFSETS = (0, 0, 0, 0, 0, 0, 0, 0)\nMINITAUR_NUM_MOTORS = 8\nTWO_PI = 2 * math.pi\nMINITAUR_DOFS_PER_LEG = 2\n\n\ndef MapToMinusPiToPi(angles):\n \"\"\"Maps a list of angles to [-pi, pi].\n\n Args:\n angles: A list of angles in rad.\n\n Returns:\n A list of angle mapped to [-pi, pi].\n \"\"\"\n mapped_angles = copy.deepcopy(angles)\n for i in range(len(angles)):\n mapped_angles[i] = math.fmod(angles[i], TWO_PI)\n if mapped_angles[i] >= math.pi:\n mapped_angles[i] -= TWO_PI\n elif mapped_angles[i] < -math.pi:\n mapped_angles[i] += TWO_PI\n return mapped_angles\n\n\nclass Minitaur(object):\n \"\"\"The minitaur class that simulates a quadruped robot from Ghost Robotics.\"\"\"\n def __init__(self,\n pybullet_client,\n num_motors=MINITAUR_NUM_MOTORS,\n dofs_per_leg=MINITAUR_DOFS_PER_LEG,\n time_step=0.01,\n action_repeat=1,\n self_collision_enabled=False,\n motor_control_mode=robot_config.MotorControlMode.POSITION,\n motor_model_class=minitaur_motor.MotorModel,\n motor_kp=1.0,\n motor_kd=0.02,\n motor_torque_limits=None,\n pd_latency=0.0,\n control_latency=0.0,\n observation_noise_stdev=SENSOR_NOISE_STDDEV,\n motor_overheat_protection=False,\n motor_direction=MINITAUR_DEFAULT_MOTOR_DIRECTIONS,\n motor_offset=MINITAUR_DEFAULT_MOTOR_OFFSETS,\n on_rack=False,\n reset_at_current_position=False,\n sensors=None,\n enable_action_interpolation=False,\n enable_action_filter=False,\n reset_time=-1):\n \"\"\"Constructs a minitaur and reset it to the initial states.\n\n Args:\n pybullet_client: The instance of BulletClient to manage different\n simulations.\n num_motors: The number of the motors on the robot.\n dofs_per_leg: The number of degrees of freedom for each leg.\n time_step: The time step of the simulation.\n action_repeat: The number of ApplyAction() for each control step.\n self_collision_enabled: Whether to enable self collision.\n motor_control_mode: Enum. Can either be POSITION, TORQUE, or HYBRID.\n motor_model_class: We can choose from simple pd model to more accureate DC\n motor models.\n motor_kp: proportional gain for the motors.\n motor_kd: derivative gain for the motors.\n motor_torque_limits: Torque limits for the motors. Can be a single float\n or a list of floats specifying different limits for different robots. If\n not provided, the default limit of the robot is used.\n pd_latency: The latency of the observations (in seconds) used to calculate\n PD control. On the real hardware, it is the latency between the\n microcontroller and the motor controller.\n control_latency: The latency of the observations (in second) used to\n calculate action. On the real hardware, it is the latency from the motor\n controller, the microcontroller to the host (Nvidia TX2).\n observation_noise_stdev: The standard deviation of a Gaussian noise model\n for the sensor. It should be an array for separate sensors in the\n following order [motor_angle, motor_velocity, motor_torque,\n base_roll_pitch_yaw, base_angular_velocity]\n motor_overheat_protection: Whether to shutdown the motor that has exerted\n large torque (OVERHEAT_SHUTDOWN_TORQUE) for an extended amount of time\n (OVERHEAT_SHUTDOWN_TIME). See ApplyAction() in minitaur.py for more\n details.\n motor_direction: A list of direction values, either 1 or -1, to compensate\n the axis difference of motors between the simulation and the real robot.\n motor_offset: A list of offset value for the motor angles. This is used to\n compensate the angle difference between the simulation and the real\n robot.\n on_rack: Whether to place the minitaur on rack. This is only used to debug\n the walking gait. In this mode, the minitaur's base is hanged midair so\n that its walking gait is clearer to visualize.\n reset_at_current_position: Whether to reset the minitaur at the current\n position and orientation. This is for simulating the reset behavior in\n the real world.\n sensors: a list of sensors that are attached to the robot.\n enable_action_interpolation: Whether to interpolate the current action\n with the previous action in order to produce smoother motions\n enable_action_filter: Boolean specifying if a lowpass filter should be\n used to smooth actions.\n \"\"\"\n\n self.num_motors = num_motors\n self.num_legs = self.num_motors // dofs_per_leg\n self._pybullet_client = pybullet_client\n self._action_repeat = action_repeat\n self._self_collision_enabled = self_collision_enabled\n self._motor_direction = motor_direction\n self._motor_offset = motor_offset\n self._observed_motor_torques = np.zeros(self.num_motors)\n self._applied_motor_torques = np.zeros(self.num_motors)\n self._max_force = 3.5\n self._pd_latency = pd_latency\n self._control_latency = control_latency\n self._observation_noise_stdev = observation_noise_stdev\n self._observation_history = collections.deque(maxlen=100)\n self._control_observation = []\n self._chassis_link_ids = [-1]\n self._leg_link_ids = []\n self._motor_link_ids = []\n self._foot_link_ids = []\n\n self._motor_overheat_protection = motor_overheat_protection\n self._on_rack = on_rack\n self._reset_at_current_position = reset_at_current_position\n self.SetAllSensors(sensors if sensors is not None else list())\n self._is_safe = True\n\n self._enable_action_interpolation = enable_action_interpolation\n self._enable_action_filter = enable_action_filter\n self._last_action = None\n\n if not motor_model_class:\n raise ValueError(\"Must provide a motor model class!\")\n\n if self._on_rack and self._reset_at_current_position:\n raise ValueError(\"on_rack and reset_at_current_position \"\n \"cannot be enabled together\")\n\n if isinstance(motor_kp, (collections.Sequence, np.ndarray)):\n self._motor_kps = np.asarray(motor_kp)\n else:\n self._motor_kps = np.full(num_motors, motor_kp)\n\n if isinstance(motor_kd, (collections.Sequence, np.ndarray)):\n self._motor_kds = np.asarray(motor_kd)\n else:\n self._motor_kds = np.full(num_motors, motor_kd)\n\n if isinstance(motor_torque_limits, (collections.Sequence, np.ndarray)):\n self._motor_torque_limits = np.asarray(motor_torque_limits)\n elif motor_torque_limits is None:\n self._motor_torque_limits = None\n else:\n self._motor_torque_limits = motor_torque_limits\n\n self._motor_control_mode = motor_control_mode\n self._motor_model = motor_model_class(\n kp=motor_kp,\n kd=motor_kd,\n torque_limits=self._motor_torque_limits,\n motor_control_mode=motor_control_mode)\n\n self.time_step = time_step\n self._step_counter = 0\n\n # This also includes the time spent during the Reset motion.\n self._state_action_counter = 0\n _, self._init_orientation_inv = self._pybullet_client.invertTransform(\n position=[0, 0, 0], orientation=self._GetDefaultInitOrientation())\n\n if self._enable_action_filter:\n self._action_filter = self._BuildActionFilter()\n\n # reset_time=-1.0 means skipping the reset motion.\n # See Reset for more details.\n self.Reset(reset_time=reset_time)\n self.ReceiveObservation()\n\n def GetTimeSinceReset(self):\n return self._step_counter * self.time_step\n\n def _StepInternal(self, action, motor_control_mode):\n self.ApplyAction(action, motor_control_mode)\n self._pybullet_client.stepSimulation()\n self.ReceiveObservation()\n self._state_action_counter += 1\n\n def Step(self, action, control_mode=None):\n \"\"\"Steps simulation.\"\"\"\n if self._enable_action_filter:\n action = self._FilterAction(action)\n if control_mode==None:\n control_mode = self._motor_control_mode\n for i in range(self._action_repeat):\n proc_action = self.ProcessAction(action, i)\n self._StepInternal(proc_action, control_mode)\n self._step_counter += 1\n\n self._last_action = action\n\n def Terminate(self):\n pass\n\n def GetFootLinkIDs(self):\n \"\"\"Get list of IDs for all foot links.\"\"\"\n return self._foot_link_ids\n\n def _RecordMassInfoFromURDF(self):\n \"\"\"Records the mass information from the URDF file.\"\"\"\n self._base_mass_urdf = []\n for chassis_id in self._chassis_link_ids:\n self._base_mass_urdf.append(\n self._pybullet_client.getDynamicsInfo(self.quadruped, chassis_id)[0])\n self._leg_masses_urdf = []\n for leg_id in self._leg_link_ids:\n self._leg_masses_urdf.append(\n self._pybullet_client.getDynamicsInfo(self.quadruped, leg_id)[0])\n for motor_id in self._motor_link_ids:\n self._leg_masses_urdf.append(\n self._pybullet_client.getDynamicsInfo(self.quadruped, motor_id)[0])\n\n def _RecordInertiaInfoFromURDF(self):\n \"\"\"Record the inertia of each body from URDF file.\"\"\"\n self._link_urdf = []\n num_bodies = self._pybullet_client.getNumJoints(self.quadruped)\n for body_id in range(-1, num_bodies): # -1 is for the base link.\n inertia = self._pybullet_client.getDynamicsInfo(self.quadruped,\n body_id)[2]\n self._link_urdf.append(inertia)\n # We need to use id+1 to index self._link_urdf because it has the base\n # (index = -1) at the first element.\n self._base_inertia_urdf = [\n self._link_urdf[chassis_id + 1]\n for chassis_id in self._chassis_link_ids\n ]\n self._leg_inertia_urdf = [\n self._link_urdf[leg_id + 1] for leg_id in self._leg_link_ids\n ]\n self._leg_inertia_urdf.extend(\n [self._link_urdf[motor_id + 1] for motor_id in self._motor_link_ids])\n\n def _BuildJointNameToIdDict(self):\n num_joints = self._pybullet_client.getNumJoints(self.quadruped)\n self._joint_name_to_id = {}\n for i in range(num_joints):\n joint_info = self._pybullet_client.getJointInfo(self.quadruped, i)\n self._joint_name_to_id[joint_info[1].decode(\"UTF-8\")] = joint_info[0]\n\n def _BuildUrdfIds(self):\n \"\"\"Build the link Ids from its name in the URDF file.\n\n Raises:\n ValueError: Unknown category of the joint name.\n \"\"\"\n num_joints = self._pybullet_client.getNumJoints(self.quadruped)\n self._chassis_link_ids = [-1]\n # The self._leg_link_ids include both the upper and lower links of the leg.\n self._leg_link_ids = []\n self._motor_link_ids = []\n self._foot_link_ids = []\n\n self._bracket_link_ids = []\n for i in range(num_joints):\n joint_info = self._pybullet_client.getJointInfo(self.quadruped, i)\n joint_name = joint_info[1].decode(\"UTF-8\")\n joint_id = self._joint_name_to_id[joint_name]\n if _CHASSIS_NAME_PATTERN.match(joint_name):\n self._chassis_link_ids.append(joint_id)\n elif _BRACKET_NAME_PATTERN.match(joint_name):\n self._bracket_link_ids.append(joint_id)\n elif _MOTOR_NAME_PATTERN.match(joint_name):\n self._motor_link_ids.append(joint_id)\n elif _KNEE_NAME_PATTERN.match(joint_name):\n self._foot_link_ids.append(joint_id)\n\n elif (_LEG_NAME_PATTERN1.match(joint_name)\n or _LEG_NAME_PATTERN2.match(joint_name)\n or _LEG_NAME_PATTERN3.match(joint_name)):\n self._leg_link_ids.append(joint_id)\n else:\n raise ValueError(\"Unknown category of joint %s\" % joint_name)\n\n self._leg_link_ids.extend(self._foot_link_ids)\n self._chassis_link_ids.sort()\n self._motor_link_ids.sort()\n self._foot_link_ids.sort()\n self._leg_link_ids.sort()\n self._bracket_link_ids.sort()\n\n def _RemoveDefaultJointDamping(self):\n num_joints = self._pybullet_client.getNumJoints(self.quadruped)\n for i in range(num_joints):\n joint_info = self._pybullet_client.getJointInfo(self.quadruped, i)\n self._pybullet_client.changeDynamics(joint_info[0],\n -1,\n linearDamping=0,\n angularDamping=0)\n\n def _BuildMotorIdList(self):\n self._motor_id_list = [\n self._joint_name_to_id[motor_name]\n for motor_name in self._GetMotorNames()\n ]\n\n def _CreateRackConstraint(self, init_position, init_orientation):\n \"\"\"Create a constraint that keeps the chassis at a fixed frame.\n\n This frame is defined by init_position and init_orientation.\n\n Args:\n init_position: initial position of the fixed frame.\n init_orientation: initial orientation of the fixed frame in quaternion\n format [x,y,z,w].\n\n Returns:\n Return the constraint id.\n \"\"\"\n fixed_constraint = self._pybullet_client.createConstraint(\n parentBodyUniqueId=self.quadruped,\n parentLinkIndex=-1,\n childBodyUniqueId=-1,\n childLinkIndex=-1,\n jointType=self._pybullet_client.JOINT_FIXED,\n jointAxis=[0, 0, 0],\n parentFramePosition=[0, 0, 0],\n childFramePosition=init_position,\n childFrameOrientation=init_orientation)\n return fixed_constraint\n\n def IsObservationValid(self):\n \"\"\"Whether the observation is valid for the current time step.\n\n In simulation, observations are always valid. In real hardware, it may not\n be valid from time to time when communication error happens between the\n Nvidia TX2 and the microcontroller.\n\n Returns:\n Whether the observation is valid for the current time step.\n \"\"\"\n return True\n\n def Reset(self, reload_urdf=True, default_motor_angles=None, reset_time=3.0):\n \"\"\"Reset the minitaur to its initial states.\n\n Args:\n reload_urdf: Whether to reload the urdf file. If not, Reset() just place\n the minitaur back to its starting position.\n default_motor_angles: The default motor angles. If it is None, minitaur\n will hold a default pose (motor angle math.pi / 2) for 100 steps. In\n torque control mode, the phase of holding the default pose is skipped.\n reset_time: The duration (in seconds) to hold the default motor angles. If\n reset_time <= 0 or in torque control mode, the phase of holding the\n default pose is skipped.\n \"\"\"\n if reload_urdf:\n self._LoadRobotURDF()\n if self._on_rack:\n self.rack_constraint = (self._CreateRackConstraint(\n self._GetDefaultInitPosition(), self._GetDefaultInitOrientation()))\n self._BuildJointNameToIdDict()\n self._BuildUrdfIds()\n self._RemoveDefaultJointDamping()\n self._BuildMotorIdList()\n self._RecordMassInfoFromURDF()\n self._RecordInertiaInfoFromURDF()\n self.ResetPose(add_constraint=True)\n else:\n self._pybullet_client.resetBasePositionAndOrientation(\n self.quadruped, self._GetDefaultInitPosition(),\n self._GetDefaultInitOrientation())\n self._pybullet_client.resetBaseVelocity(self.quadruped, [0, 0, 0],\n [0, 0, 0])\n self.ResetPose(add_constraint=False)\n\n self._overheat_counter = np.zeros(self.num_motors)\n self._motor_enabled_list = [True] * self.num_motors\n self._observation_history.clear()\n self._step_counter = 0\n self._state_action_counter = 0\n self._is_safe = True\n self._last_action = None\n self._SettleDownForReset(default_motor_angles, reset_time)\n if self._enable_action_filter:\n self._ResetActionFilter()\n\n def _LoadRobotURDF(self):\n \"\"\"Loads the URDF file for the robot.\"\"\"\n urdf_file = self.GetURDFFile()\n if self._self_collision_enabled:\n self.quadruped = self._pybullet_client.loadURDF(\n urdf_file,\n self._GetDefaultInitPosition(),\n self._GetDefaultInitOrientation(),\n flags=self._pybullet_client.URDF_USE_SELF_COLLISION)\n else:\n self.quadruped = self._pybullet_client.loadURDF(\n urdf_file, self._GetDefaultInitPosition(),\n self._GetDefaultInitOrientation())\n\n def _SettleDownForReset(self, default_motor_angles, reset_time):\n \"\"\"Sets the default motor angles and waits for the robot to settle down.\n\n The reset is skipped is reset_time is less than zereo.\n\n Args:\n default_motor_angles: A list of motor angles that the robot will achieve\n at the end of the reset phase.\n reset_time: The time duration for the reset phase.\n \"\"\"\n if reset_time <= 0:\n return\n # Important to fill the observation buffer.\n self.ReceiveObservation()\n for _ in range(100):\n self._StepInternal(\n [math.pi / 2] * self.num_motors,\n motor_control_mode=robot_config.MotorControlMode.POSITION)\n # Don't continue to reset if a safety error has occurred.\n if not self._is_safe:\n return\n\n if default_motor_angles is None:\n return\n\n num_steps_to_reset = int(reset_time / self.time_step)\n for _ in range(num_steps_to_reset):\n self._StepInternal(\n default_motor_angles,\n motor_control_mode=robot_config.MotorControlMode.POSITION)\n # Don't continue to reset if a safety error has occurred.\n if not self._is_safe:\n return\n\n def _SetMotorTorqueById(self, motor_id, torque):\n self._pybullet_client.setJointMotorControl2(\n bodyIndex=self.quadruped,\n jointIndex=motor_id,\n controlMode=self._pybullet_client.TORQUE_CONTROL,\n force=torque)\n\n def _SetMotorTorqueByIds(self, motor_ids, torques):\n self._pybullet_client.setJointMotorControlArray(\n bodyIndex=self.quadruped,\n jointIndices=motor_ids,\n controlMode=self._pybullet_client.TORQUE_CONTROL,\n forces=torques)\n\n def _SetDesiredMotorAngleByName(self, motor_name, desired_angle):\n self._SetDesiredMotorAngleById(self._joint_name_to_id[motor_name],\n desired_angle)\n\n def GetURDFFile(self):\n return \"quadruped/minitaur.urdf\"\n\n def ResetPose(self, add_constraint):\n \"\"\"Reset the pose of the minitaur.\n\n Args:\n add_constraint: Whether to add a constraint at the joints of two feet.\n \"\"\"\n for i in range(self.num_legs):\n self._ResetPoseForLeg(i, add_constraint)\n\n def _ResetPoseForLeg(self, leg_id, add_constraint):\n \"\"\"Reset the initial pose for the leg.\n\n Args:\n leg_id: It should be 0, 1, 2, or 3, which represents the leg at\n front_left, back_left, front_right and back_right.\n add_constraint: Whether to add a constraint at the joints of two feet.\n \"\"\"\n knee_friction_force = 0\n half_pi = math.pi / 2.0\n knee_angle = -2.1834\n\n leg_position = LEG_POSITION[leg_id]\n self._pybullet_client.resetJointState(\n self.quadruped,\n self._joint_name_to_id[\"motor_\" + leg_position + \"L_joint\"],\n self._motor_direction[2 * leg_id] * half_pi,\n targetVelocity=0)\n self._pybullet_client.resetJointState(\n self.quadruped,\n self._joint_name_to_id[\"knee_\" + leg_position + \"L_link\"],\n self._motor_direction[2 * leg_id] * knee_angle,\n targetVelocity=0)\n self._pybullet_client.resetJointState(\n self.quadruped,\n self._joint_name_to_id[\"motor_\" + leg_position + \"R_joint\"],\n self._motor_direction[2 * leg_id + 1] * half_pi,\n targetVelocity=0)\n self._pybullet_client.resetJointState(\n self.quadruped,\n self._joint_name_to_id[\"knee_\" + leg_position + \"R_link\"],\n self._motor_direction[2 * leg_id + 1] * knee_angle,\n targetVelocity=0)\n if add_constraint:\n self._pybullet_client.createConstraint(\n self.quadruped,\n self._joint_name_to_id[\"knee_\" + leg_position + \"R_link\"],\n self.quadruped,\n self._joint_name_to_id[\"knee_\" + leg_position + \"L_link\"],\n self._pybullet_client.JOINT_POINT2POINT, [0, 0, 0],\n KNEE_CONSTRAINT_POINT_RIGHT, KNEE_CONSTRAINT_POINT_LEFT)\n\n # Disable the default motor in pybullet.\n self._pybullet_client.setJointMotorControl2(\n bodyIndex=self.quadruped,\n jointIndex=(self._joint_name_to_id[\"motor_\" + leg_position +\n \"L_joint\"]),\n controlMode=self._pybullet_client.VELOCITY_CONTROL,\n targetVelocity=0,\n force=knee_friction_force)\n self._pybullet_client.setJointMotorControl2(\n bodyIndex=self.quadruped,\n jointIndex=(self._joint_name_to_id[\"motor_\" + leg_position +\n \"R_joint\"]),\n controlMode=self._pybullet_client.VELOCITY_CONTROL,\n targetVelocity=0,\n force=knee_friction_force)\n\n self._pybullet_client.setJointMotorControl2(\n bodyIndex=self.quadruped,\n jointIndex=(self._joint_name_to_id[\"knee_\" + leg_position + \"L_link\"]),\n controlMode=self._pybullet_client.VELOCITY_CONTROL,\n targetVelocity=0,\n force=knee_friction_force)\n self._pybullet_client.setJointMotorControl2(\n bodyIndex=self.quadruped,\n jointIndex=(self._joint_name_to_id[\"knee_\" + leg_position + \"R_link\"]),\n controlMode=self._pybullet_client.VELOCITY_CONTROL,\n targetVelocity=0,\n force=knee_friction_force)\n\n def GetBasePosition(self):\n \"\"\"Get the position of minitaur's base.\n\n Returns:\n The position of minitaur's base.\n \"\"\"\n return self._base_position\n\n def GetBaseVelocity(self):\n \"\"\"Get the linear velocity of minitaur's base.\n\n Returns:\n The velocity of minitaur's base.\n \"\"\"\n velocity, _ = self._pybullet_client.getBaseVelocity(self.quadruped)\n return velocity\n\n def GetTrueBaseRollPitchYaw(self):\n \"\"\"Get minitaur's base orientation in euler angle in the world frame.\n\n Returns:\n A tuple (roll, pitch, yaw) of the base in world frame.\n \"\"\"\n orientation = self.GetTrueBaseOrientation()\n roll_pitch_yaw = self._pybullet_client.getEulerFromQuaternion(orientation)\n return np.asarray(roll_pitch_yaw)\n\n def GetBaseRollPitchYaw(self):\n \"\"\"Get minitaur's base orientation in euler angle in the world frame.\n\n This function mimicks the noisy sensor reading and adds latency.\n Returns:\n A tuple (roll, pitch, yaw) of the base in world frame polluted by noise\n and latency.\n \"\"\"\n delayed_orientation = np.array(\n self._control_observation[3 * self.num_motors:3 * self.num_motors + 4])\n delayed_roll_pitch_yaw = self._pybullet_client.getEulerFromQuaternion(\n delayed_orientation)\n roll_pitch_yaw = self._AddSensorNoise(np.array(delayed_roll_pitch_yaw),\n self._observation_noise_stdev[3])\n return roll_pitch_yaw\n\n def GetHipPositionsInBaseFrame(self):\n \"\"\"Get the hip joint positions of the robot within its base frame.\"\"\"\n raise NotImplementedError(\"Not implemented for Minitaur.\")\n\n def ComputeMotorAnglesFromFootLocalPosition(self, leg_id,\n foot_local_position):\n \"\"\"Use IK to compute the motor angles, given the foot link's local position.\n\n Args:\n leg_id: The leg index.\n foot_local_position: The foot link's position in the base frame.\n\n Returns:\n A tuple. The position indices and the angles for all joints along the\n leg. The position indices is consistent with the joint orders as returned\n by GetMotorAngles API.\n \"\"\"\n assert len(self._foot_link_ids) == self.num_legs\n toe_id = self._foot_link_ids[leg_id]\n\n motors_per_leg = self.num_motors // self.num_legs\n joint_position_idxs = list(\n range(leg_id * motors_per_leg,\n leg_id * motors_per_leg + motors_per_leg))\n\n joint_angles = kinematics.joint_angles_from_link_position(\n robot=self,\n link_position=foot_local_position,\n link_id=toe_id,\n joint_ids=joint_position_idxs,\n )\n\n # Joint offset is necessary for Laikago.\n joint_angles = np.multiply(\n np.asarray(joint_angles) -\n np.asarray(self._motor_offset)[joint_position_idxs],\n self._motor_direction[joint_position_idxs])\n\n # Return the joing index (the same as when calling GetMotorAngles) as well\n # as the angles.\n return joint_position_idxs, joint_angles.tolist()\n\n def ComputeJacobian(self, leg_id):\n \"\"\"Compute the Jacobian for a given leg.\"\"\"\n # Does not work for Minitaur which has the four bar mechanism for now.\n assert len(self._foot_link_ids) == self.num_legs\n full_jacobian = kinematics.compute_jacobian(\n robot=self,\n link_id=self._foot_link_ids[leg_id],\n )\n motors_per_leg = self.num_motors // self.num_legs\n com_dof = 6\n return full_jacobian[com_dof + leg_id * motors_per_leg:com_dof +\n (leg_id + 1) * motors_per_leg]\n\n def MapContactForceToJointTorques(self, leg_id, contact_force):\n \"\"\"Maps the foot contact force to the leg joint torques.\"\"\"\n jv = self.ComputeJacobian(leg_id)\n motor_torques_list = np.matmul(contact_force, jv)\n motor_torques_dict = {}\n motors_per_leg = self.num_motors // self.num_legs\n for torque_id, joint_id in enumerate(\n range(leg_id * motors_per_leg, (leg_id + 1) * motors_per_leg)):\n motor_torques_dict[joint_id] = motor_torques_list[torque_id]\n return motor_torques_dict\n\n def GetFootContacts(self):\n \"\"\"Get minitaur's foot contact situation with the ground.\n\n Returns:\n A list of 4 booleans. The ith boolean is True if leg i is in contact with\n ground.\n \"\"\"\n contacts = []\n for leg_idx in range(MINITAUR_NUM_MOTORS // 2):\n link_id_1 = self._foot_link_ids[leg_idx * 2]\n link_id_2 = self._foot_link_ids[leg_idx * 2 + 1]\n contact_1 = bool(\n self._pybullet_client.getContactPoints(bodyA=0,\n bodyB=self.quadruped,\n linkIndexA=-1,\n linkIndexB=link_id_1))\n contact_2 = bool(\n self._pybullet_client.getContactPoints(bodyA=0,\n bodyB=self.quadruped,\n linkIndexA=-1,\n linkIndexB=link_id_2))\n contacts.append(contact_1 or contact_2)\n return contacts\n\n def GetFootPositionsInBaseFrame(self):\n \"\"\"Get the robot's foot position in the base frame.\"\"\"\n assert len(self._foot_link_ids) == self.num_legs\n foot_positions = []\n for foot_id in self.GetFootLinkIDs():\n foot_positions.append(\n kinematics.link_position_in_base_frame(\n robot=self,\n link_id=foot_id,\n ))\n return np.array(foot_positions)\n\n def GetTrueMotorAngles(self):\n \"\"\"Gets the eight motor angles at the current moment, mapped to [-pi, pi].\n\n Returns:\n Motor angles, mapped to [-pi, pi].\n \"\"\"\n motor_angles = [state[0] for state in self._joint_states]\n motor_angles = np.multiply(\n np.asarray(motor_angles) - np.asarray(self._motor_offset),\n self._motor_direction)\n return motor_angles\n\n def GetMotorAngles(self):\n \"\"\"Gets the eight motor angles.\n\n This function mimicks the noisy sensor reading and adds latency. The motor\n angles that are delayed, noise polluted, and mapped to [-pi, pi].\n\n Returns:\n Motor angles polluted by noise and latency, mapped to [-pi, pi].\n \"\"\"\n motor_angles = self._AddSensorNoise(\n np.array(self._control_observation[0:self.num_motors]),\n self._observation_noise_stdev[0])\n return MapToMinusPiToPi(motor_angles)\n\n def GetTrueMotorVelocities(self):\n \"\"\"Get the velocity of all eight motors.\n\n Returns:\n Velocities of all eight motors.\n \"\"\"\n motor_velocities = [state[1] for state in self._joint_states]\n\n motor_velocities = np.multiply(motor_velocities, self._motor_direction)\n return motor_velocities\n\n def GetMotorVelocities(self):\n \"\"\"Get the velocity of all eight motors.\n\n This function mimicks the noisy sensor reading and adds latency.\n Returns:\n Velocities of all eight motors polluted by noise and latency.\n \"\"\"\n return self._AddSensorNoise(\n np.array(self._control_observation[self.num_motors:2 *\n self.num_motors]),\n self._observation_noise_stdev[1])\n\n def GetTrueMotorTorques(self):\n \"\"\"Get the amount of torque the motors are exerting.\n\n Returns:\n Motor torques of all eight motors.\n \"\"\"\n return self._observed_motor_torques\n\n def GetMotorTorques(self):\n \"\"\"Get the amount of torque the motors are exerting.\n\n This function mimicks the noisy sensor reading and adds latency.\n Returns:\n Motor torques of all eight motors polluted by noise and latency.\n \"\"\"\n return self._AddSensorNoise(\n np.array(self._control_observation[2 * self.num_motors:3 *\n self.num_motors]),\n self._observation_noise_stdev[2])\n\n def GetEnergyConsumptionPerControlStep(self):\n \"\"\"Get the amount of energy used in last one time step.\n\n Returns:\n Energy Consumption based on motor velocities and torques (Nm^2/s).\n \"\"\"\n return np.abs(np.dot(\n self.GetMotorTorques(),\n self.GetMotorVelocities())) * self.time_step * self._action_repeat\n\n def GetTrueBaseOrientation(self):\n \"\"\"Get the orientation of minitaur's base, represented as quaternion.\n\n Returns:\n The orientation of minitaur's base.\n \"\"\"\n return self._base_orientation\n\n def GetBaseOrientation(self):\n \"\"\"Get the orientation of minitaur's base, represented as quaternion.\n\n This function mimicks the noisy sensor reading and adds latency.\n Returns:\n The orientation of minitaur's base polluted by noise and latency.\n \"\"\"\n return self._pybullet_client.getQuaternionFromEuler(\n self.GetBaseRollPitchYaw())\n\n def GetTrueBaseRollPitchYawRate(self):\n \"\"\"Get the rate of orientation change of the minitaur's base in euler angle.\n\n Returns:\n rate of (roll, pitch, yaw) change of the minitaur's base.\n \"\"\"\n angular_velocity = self._pybullet_client.getBaseVelocity(self.quadruped)[1]\n orientation = self.GetTrueBaseOrientation()\n return self.TransformAngularVelocityToLocalFrame(angular_velocity,\n orientation)\n\n def TransformAngularVelocityToLocalFrame(self, angular_velocity,\n orientation):\n \"\"\"Transform the angular velocity from world frame to robot's frame.\n\n Args:\n angular_velocity: Angular velocity of the robot in world frame.\n orientation: Orientation of the robot represented as a quaternion.\n\n Returns:\n angular velocity of based on the given orientation.\n \"\"\"\n # Treat angular velocity as a position vector, then transform based on the\n # orientation given by dividing (or multiplying with inverse).\n # Get inverse quaternion assuming the vector is at 0,0,0 origin.\n _, orientation_inversed = self._pybullet_client.invertTransform(\n [0, 0, 0], orientation)\n # Transform the angular_velocity at neutral orientation using a neutral\n # translation and reverse of the given orientation.\n relative_velocity, _ = self._pybullet_client.multiplyTransforms(\n [0, 0, 0], orientation_inversed, angular_velocity,\n self._pybullet_client.getQuaternionFromEuler([0, 0, 0]))\n return np.asarray(relative_velocity)\n\n def GetBaseRollPitchYawRate(self):\n \"\"\"Get the rate of orientation change of the minitaur's base in euler angle.\n\n This function mimicks the noisy sensor reading and adds latency.\n Returns:\n rate of (roll, pitch, yaw) change of the minitaur's base polluted by noise\n and latency.\n \"\"\"\n return self._AddSensorNoise(\n np.array(self._control_observation[3 * self.num_motors +\n 4:3 * self.num_motors + 7]),\n self._observation_noise_stdev[4])\n\n def GetActionDimension(self):\n \"\"\"Get the length of the action list.\n\n Returns:\n The length of the action list.\n \"\"\"\n return self.num_motors\n\n def _ApplyOverheatProtection(self, actual_torque):\n if self._motor_overheat_protection:\n for i in range(self.num_motors):\n if abs(actual_torque[i]) > OVERHEAT_SHUTDOWN_TORQUE:\n self._overheat_counter[i] += 1\n else:\n self._overheat_counter[i] = 0\n if (self._overheat_counter[i] >\n OVERHEAT_SHUTDOWN_TIME / self.time_step):\n self._motor_enabled_list[i] = False\n\n def ApplyAction(self, motor_commands, motor_control_mode):\n \"\"\"Apply the motor commands using the motor model.\n\n Args:\n motor_commands: np.array. Can be motor angles, torques, hybrid commands,\n or motor pwms (for Minitaur only).\n motor_control_mode: A MotorControlMode enum.\n \"\"\"\n self.last_action_time = self._state_action_counter * self.time_step\n control_mode = motor_control_mode\n\n if control_mode is None:\n control_mode = self._motor_control_mode\n\n motor_commands = np.asarray(motor_commands)\n\n q, qdot = self._GetPDObservation()\n qdot_true = self.GetTrueMotorVelocities()\n actual_torque, observed_torque = self._motor_model.convert_to_torque(\n motor_commands, q, qdot, qdot_true, control_mode)\n\n # May turn off the motor\n self._ApplyOverheatProtection(actual_torque)\n\n # The torque is already in the observation space because we use\n # GetMotorAngles and GetMotorVelocities.\n self._observed_motor_torques = observed_torque\n\n # Transform into the motor space when applying the torque.\n self._applied_motor_torque = np.multiply(actual_torque,\n self._motor_direction)\n motor_ids = []\n motor_torques = []\n\n for motor_id, motor_torque, motor_enabled in zip(\n self._motor_id_list, self._applied_motor_torque,\n self._motor_enabled_list):\n if motor_enabled:\n motor_ids.append(motor_id)\n motor_torques.append(motor_torque)\n else:\n motor_ids.append(motor_id)\n motor_torques.append(0)\n self._SetMotorTorqueByIds(motor_ids, motor_torques)\n\n def ConvertFromLegModel(self, actions):\n \"\"\"Convert the actions that use leg model to the real motor actions.\n\n Args:\n actions: The theta, phi of the leg model.\n\n Returns:\n The eight desired motor angles that can be used in ApplyActions().\n \"\"\"\n motor_angle = copy.deepcopy(actions)\n scale_for_singularity = 1\n offset_for_singularity = 1.5\n half_num_motors = self.num_motors // 2\n quater_pi = math.pi / 4\n for i in range(self.num_motors):\n action_idx = i // 2\n forward_backward_component = (\n -scale_for_singularity * quater_pi *\n (actions[action_idx + half_num_motors] + offset_for_singularity))\n extension_component = (-1)**i * quater_pi * actions[action_idx]\n if i >= half_num_motors:\n extension_component = -extension_component\n motor_angle[i] = (math.pi + forward_backward_component +\n extension_component)\n return motor_angle\n\n def GetBaseMassesFromURDF(self):\n \"\"\"Get the mass of the base from the URDF file.\"\"\"\n return self._base_mass_urdf\n\n def GetBaseInertiasFromURDF(self):\n \"\"\"Get the inertia of the base from the URDF file.\"\"\"\n return self._base_inertia_urdf\n\n def GetLegMassesFromURDF(self):\n \"\"\"Get the mass of the legs from the URDF file.\"\"\"\n return self._leg_masses_urdf\n\n def GetLegInertiasFromURDF(self):\n \"\"\"Get the inertia of the legs from the URDF file.\"\"\"\n return self._leg_inertia_urdf\n\n def SetBaseMasses(self, base_mass):\n \"\"\"Set the mass of minitaur's base.\n\n Args:\n base_mass: A list of masses of each body link in CHASIS_LINK_IDS. The\n length of this list should be the same as the length of CHASIS_LINK_IDS.\n\n Raises:\n ValueError: It is raised when the length of base_mass is not the same as\n the length of self._chassis_link_ids.\n \"\"\"\n if len(base_mass) != len(self._chassis_link_ids):\n raise ValueError(\n \"The length of base_mass {} and self._chassis_link_ids {} are not \"\n \"the same.\".format(len(base_mass), len(self._chassis_link_ids)))\n for chassis_id, chassis_mass in zip(self._chassis_link_ids, base_mass):\n self._pybullet_client.changeDynamics(self.quadruped,\n chassis_id,\n mass=chassis_mass)\n\n def SetLegMasses(self, leg_masses):\n \"\"\"Set the mass of the legs.\n\n A leg includes leg_link and motor. 4 legs contain 16 links (4 links each)\n and 8 motors. First 16 numbers correspond to link masses, last 8 correspond\n to motor masses (24 total).\n\n Args:\n leg_masses: The leg and motor masses for all the leg links and motors.\n\n Raises:\n ValueError: It is raised when the length of masses is not equal to number\n of links + motors.\n \"\"\"\n if len(leg_masses) != len(self._leg_link_ids) + len(self._motor_link_ids):\n raise ValueError(\"The number of values passed to SetLegMasses are \"\n \"different than number of leg links and motors.\")\n for leg_id, leg_mass in zip(self._leg_link_ids, leg_masses):\n self._pybullet_client.changeDynamics(self.quadruped,\n leg_id,\n mass=leg_mass)\n motor_masses = leg_masses[len(self._leg_link_ids):]\n for link_id, motor_mass in zip(self._motor_link_ids, motor_masses):\n self._pybullet_client.changeDynamics(self.quadruped,\n link_id,\n mass=motor_mass)\n\n def SetBaseInertias(self, base_inertias):\n \"\"\"Set the inertias of minitaur's base.\n\n Args:\n base_inertias: A list of inertias of each body link in CHASIS_LINK_IDS.\n The length of this list should be the same as the length of\n CHASIS_LINK_IDS.\n\n Raises:\n ValueError: It is raised when the length of base_inertias is not the same\n as the length of self._chassis_link_ids and base_inertias contains\n negative values.\n \"\"\"\n if len(base_inertias) != len(self._chassis_link_ids):\n raise ValueError(\n \"The length of base_inertias {} and self._chassis_link_ids {} are \"\n \"not the same.\".format(len(base_inertias),\n len(self._chassis_link_ids)))\n for chassis_id, chassis_inertia in zip(self._chassis_link_ids,\n base_inertias):\n for inertia_value in chassis_inertia:\n if (np.asarray(inertia_value) < 0).any():\n raise ValueError(\"Values in inertia matrix should be non-negative.\")\n self._pybullet_client.changeDynamics(\n self.quadruped, chassis_id, localInertiaDiagonal=chassis_inertia)\n\n def SetLegInertias(self, leg_inertias):\n \"\"\"Set the inertias of the legs.\n\n A leg includes leg_link and motor. 4 legs contain 16 links (4 links each)\n and 8 motors. First 16 numbers correspond to link inertia, last 8 correspond\n to motor inertia (24 total).\n\n Args:\n leg_inertias: The leg and motor inertias for all the leg links and motors.\n\n Raises:\n ValueError: It is raised when the length of inertias is not equal to\n the number of links + motors or leg_inertias contains negative values.\n \"\"\"\n\n if len(leg_inertias) != len(self._leg_link_ids) + len(\n self._motor_link_ids):\n raise ValueError(\"The number of values passed to SetLegMasses are \"\n \"different than number of leg links and motors.\")\n for leg_id, leg_inertia in zip(self._leg_link_ids, leg_inertias):\n for inertia_value in leg_inertias:\n if (np.asarray(inertia_value) < 0).any():\n raise ValueError(\"Values in inertia matrix should be non-negative.\")\n self._pybullet_client.changeDynamics(self.quadruped,\n leg_id,\n localInertiaDiagonal=leg_inertia)\n\n motor_inertias = leg_inertias[len(self._leg_link_ids):]\n for link_id, motor_inertia in zip(self._motor_link_ids, motor_inertias):\n for inertia_value in motor_inertias:\n if (np.asarray(inertia_value) < 0).any():\n raise ValueError(\"Values in inertia matrix should be non-negative.\")\n self._pybullet_client.changeDynamics(self.quadruped,\n link_id,\n localInertiaDiagonal=motor_inertia)\n\n def SetFootFriction(self, foot_friction):\n \"\"\"Set the lateral friction of the feet.\n\n Args:\n foot_friction: The lateral friction coefficient of the foot. This value is\n shared by all four feet.\n \"\"\"\n for link_id in self._foot_link_ids:\n self._pybullet_client.changeDynamics(self.quadruped,\n link_id,\n lateralFriction=foot_friction)\n\n def SetFootRestitution(self, foot_restitution):\n \"\"\"Set the coefficient of restitution at the feet.\n\n Args:\n foot_restitution: The coefficient of restitution (bounciness) of the feet.\n This value is shared by all four feet.\n \"\"\"\n for link_id in self._foot_link_ids:\n self._pybullet_client.changeDynamics(self.quadruped,\n link_id,\n restitution=foot_restitution)\n\n def SetJointFriction(self, joint_frictions):\n for knee_joint_id, friction in zip(self._foot_link_ids, joint_frictions):\n self._pybullet_client.setJointMotorControl2(\n bodyIndex=self.quadruped,\n jointIndex=knee_joint_id,\n controlMode=self._pybullet_client.VELOCITY_CONTROL,\n targetVelocity=0,\n force=friction)\n\n def GetNumKneeJoints(self):\n return len(self._foot_link_ids)\n\n def SetBatteryVoltage(self, voltage):\n self._motor_model.set_voltage(voltage)\n\n def SetMotorViscousDamping(self, viscous_damping):\n self._motor_model.set_viscous_damping(viscous_damping)\n\n def GetTrueObservation(self):\n observation = []\n observation.extend(self.GetTrueMotorAngles())\n observation.extend(self.GetTrueMotorVelocities())\n observation.extend(self.GetTrueMotorTorques())\n observation.extend(self.GetTrueBaseOrientation())\n observation.extend(self.GetTrueBaseRollPitchYawRate())\n return observation\n\n def ReceiveObservation(self):\n \"\"\"Receive the observation from sensors.\n\n This function is called once per step. The observations are only updated\n when this function is called.\n \"\"\"\n self._joint_states = self._pybullet_client.getJointStates(\n self.quadruped, self._motor_id_list)\n self._base_position, orientation = (\n self._pybullet_client.getBasePositionAndOrientation(self.quadruped))\n # Computes the relative orientation relative to the robot's\n # initial_orientation.\n _, self._base_orientation = self._pybullet_client.multiplyTransforms(\n positionA=[0, 0, 0],\n orientationA=orientation,\n positionB=[0, 0, 0],\n orientationB=self._init_orientation_inv)\n self._observation_history.appendleft(self.GetTrueObservation())\n self._control_observation = self._GetControlObservation()\n self.last_state_time = self._state_action_counter * self.time_step\n\n def _GetDelayedObservation(self, latency):\n \"\"\"Get observation that is delayed by the amount specified in latency.\n\n Args:\n latency: The latency (in seconds) of the delayed observation.\n\n Returns:\n observation: The observation which was actually latency seconds ago.\n \"\"\"\n if latency <= 0 or len(self._observation_history) == 1:\n observation = self._observation_history[0]\n else:\n n_steps_ago = int(latency / self.time_step)\n if n_steps_ago + 1 >= len(self._observation_history):\n return self._observation_history[-1]\n remaining_latency = latency - n_steps_ago * self.time_step\n blend_alpha = remaining_latency / self.time_step\n observation = (\n (1.0 - blend_alpha) *\n np.array(self._observation_history[n_steps_ago]) +\n blend_alpha * np.array(self._observation_history[n_steps_ago + 1]))\n return observation\n\n def _GetPDObservation(self):\n pd_delayed_observation = self._GetDelayedObservation(self._pd_latency)\n q = pd_delayed_observation[0:self.num_motors]\n qdot = pd_delayed_observation[self.num_motors:2 * self.num_motors]\n return (np.array(q), np.array(qdot))\n\n def _GetControlObservation(self):\n control_delayed_observation = self._GetDelayedObservation(\n self._control_latency)\n return control_delayed_observation\n\n def _AddSensorNoise(self, sensor_values, noise_stdev):\n if noise_stdev <= 0:\n return sensor_values\n observation = sensor_values + np.random.normal(scale=noise_stdev,\n size=sensor_values.shape)\n return observation\n\n def SetControlLatency(self, latency):\n \"\"\"Set the latency of the control loop.\n\n It measures the duration between sending an action from Nvidia TX2 and\n receiving the observation from microcontroller.\n\n Args:\n latency: The latency (in seconds) of the control loop.\n \"\"\"\n self._control_latency = latency\n\n def GetControlLatency(self):\n \"\"\"Get the control latency.\n\n Returns:\n The latency (in seconds) between when the motor command is sent and when\n the sensor measurements are reported back to the controller.\n \"\"\"\n return self._control_latency\n\n def SetMotorGains(self, kp, kd):\n \"\"\"Set the gains of all motors.\n\n These gains are PD gains for motor positional control. kp is the\n proportional gain and kd is the derivative gain.\n\n Args:\n kp: proportional gain(s) of the motors.\n kd: derivative gain(s) of the motors.\n \"\"\"\n if isinstance(kp, (collections.Sequence, np.ndarray)):\n self._motor_kps = np.asarray(kp)\n else:\n self._motor_kps = np.full(self.num_motors, kp)\n\n if isinstance(kd, (collections.Sequence, np.ndarray)):\n self._motor_kds = np.asarray(kd)\n else:\n self._motor_kds = np.full(self.num_motors, kd)\n\n self._motor_model.set_motor_gains(kp, kd)\n\n def GetMotorGains(self):\n \"\"\"Get the gains of the motor.\n\n Returns:\n The proportional gain.\n The derivative gain.\n \"\"\"\n return self._motor_kps, self._motor_kds\n\n def GetMotorPositionGains(self):\n \"\"\"Get the position gains of the motor.\n\n Returns:\n The proportional gain.\n \"\"\"\n return self._motor_kps\n\n def GetMotorVelocityGains(self):\n \"\"\"Get the velocity gains of the motor.\n\n Returns:\n The derivative gain.\n \"\"\"\n return self._motor_kds\n\n def SetMotorStrengthRatio(self, ratio):\n \"\"\"Set the strength of all motors relative to the default value.\n\n Args:\n ratio: The relative strength. A scalar range from 0.0 to 1.0.\n \"\"\"\n self._motor_model.set_strength_ratios([ratio] * self.num_motors)\n\n def SetMotorStrengthRatios(self, ratios):\n \"\"\"Set the strength of each motor relative to the default value.\n\n Args:\n ratios: The relative strength. A numpy array ranging from 0.0 to 1.0.\n \"\"\"\n self._motor_model.set_strength_ratios(ratios)\n\n def SetTimeSteps(self, action_repeat, simulation_step):\n \"\"\"Set the time steps of the control and simulation.\n\n Args:\n action_repeat: The number of simulation steps that the same action is\n repeated.\n simulation_step: The simulation time step.\n \"\"\"\n self.time_step = simulation_step\n self._action_repeat = action_repeat\n\n def _GetMotorNames(self):\n return MOTOR_NAMES\n\n def _GetDefaultInitPosition(self):\n \"\"\"Returns the init position of the robot.\n\n It can be either 1) origin (INIT_POSITION), 2) origin with a rack\n (INIT_RACK_POSITION), or 3) the previous position.\n \"\"\"\n # If we want continuous resetting and is not the first episode.\n if self._reset_at_current_position and self._observation_history:\n x, y, _ = self.GetBasePosition()\n _, _, z = INIT_POSITION\n return [x, y, z]\n\n if self._on_rack:\n return INIT_RACK_POSITION\n else:\n return INIT_POSITION\n\n def _GetDefaultInitOrientation(self):\n \"\"\"Returns the init position of the robot.\n\n It can be either 1) INIT_ORIENTATION or 2) the previous rotation in yaw.\n \"\"\"\n # If we want continuous resetting and is not the first episode.\n if self._reset_at_current_position and self._observation_history:\n _, _, yaw = self.GetBaseRollPitchYaw()\n return self._pybullet_client.getQuaternionFromEuler([0.0, 0.0, yaw])\n return INIT_ORIENTATION\n\n @property\n def chassis_link_ids(self):\n return self._chassis_link_ids\n\n def SetAllSensors(self, sensors):\n \"\"\"set all sensors to this robot and move the ownership to this robot.\n\n Args:\n sensors: a list of sensors to this robot.\n \"\"\"\n for s in sensors:\n s.set_robot(self)\n self._sensors = sensors\n\n def GetAllSensors(self):\n \"\"\"get all sensors associated with this robot.\n\n Returns:\n sensors: a list of all sensors.\n \"\"\"\n return self._sensors\n\n def GetSensor(self, name):\n \"\"\"get the first sensor with the given name.\n\n This function return None if a sensor with the given name does not exist.\n\n Args:\n name: the name of the sensor we are looking\n\n Returns:\n sensor: a sensor with the given name. None if not exists.\n \"\"\"\n for s in self._sensors:\n if s.get_name() == name:\n return s\n return None\n\n @property\n def is_safe(self):\n return self._is_safe\n\n @property\n def last_action(self):\n return self._last_action\n\n def ProcessAction(self, action, substep_count):\n \"\"\"If enabled, interpolates between the current and previous actions.\n\n Args:\n action: current action.\n substep_count: the step count should be between [0, self.__action_repeat).\n\n Returns:\n If interpolation is enabled, returns interpolated action depending on\n the current action repeat substep.\n \"\"\"\n if self._enable_action_interpolation and self._last_action is not None:\n lerp = float(substep_count + 1) / self._action_repeat\n proc_action = self._last_action + lerp * (action - self._last_action)\n else:\n proc_action = action\n\n return proc_action\n\n def _BuildActionFilter(self):\n sampling_rate = 1 / (self.time_step * self._action_repeat)\n num_joints = self.GetActionDimension()\n a_filter = action_filter.ActionFilterButter(sampling_rate=sampling_rate,\n num_joints=num_joints)\n return a_filter\n\n def _ResetActionFilter(self):\n self._action_filter.reset()\n\n def _FilterAction(self, action):\n # initialize the filter history, since resetting the filter will fill\n # the history with zeros and this can cause sudden movements at the start\n # of each episode\n if self._step_counter == 0:\n default_action = self.GetMotorAngles()\n self._action_filter.init_history(default_action)\n\n filtered_action = self._action_filter.filter(action)\n return filtered_action\n\n @property\n def pybullet_client(self):\n return self._pybullet_client\n\n @property\n def joint_states(self):\n return self._joint_states\n\n @classmethod\n def GetConstants(cls):\n del cls\n return minitaur_constants\n" ]
[ [ "numpy.multiply", "numpy.asarray", "numpy.matmul", "numpy.full", "numpy.random.normal", "numpy.array", "numpy.zeros" ] ]
lleunyoungll/GAN_BallcounterBar
[ "c128214061b9cf294701d490dbbc8b831107072e" ]
[ "lib/model.py" ]
[ "\"\"\"GANomaly\n\"\"\"\n# pylint: disable=C0301,E1101,W0622,C0103,R0902,R0915\n\n##\nfrom collections import OrderedDict\nimport os\nimport time\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom torch.autograd import Variable\nimport torch.optim as optim\nimport torch.nn as nn\nimport torch.utils.data\nimport torchvision.utils as vutils\n\nfrom lib.networks import NetG, NetD, weights_init\nfrom lib.visualizer import Visualizer\nfrom lib.loss import l2_loss\nfrom lib.evaluate import evaluate\n\n\nclass BaseModel():\n \"\"\" Base Model for ganomaly\n \"\"\"\n def __init__(self, opt, dataloader):\n ##\n # Seed for deterministic behavior\n self.seed(opt.manualseed)\n\n # Initalize variables.\n self.opt = opt\n self.visualizer = Visualizer(opt)\n self.dataloader = dataloader\n self.trn_dir = os.path.join(self.opt.outf, self.opt.name, 'train')\n self.tst_dir = os.path.join(self.opt.outf, self.opt.name, 'test')\n self.device = torch.device(\"cuda:0\" if self.opt.device != 'cpu' else \"cpu\")\n\n ##\n def set_input(self, input:torch.Tensor):\n \"\"\" Set input and ground truth\n\n Args:\n input (FloatTensor): Input data for batch i.\n \"\"\"\n with torch.no_grad():\n self.input.resize_(input[0].size()).copy_(input[0])\n self.gt.resize_(input[1].size()).copy_(input[1])\n self.label.resize_(input[1].size())\n\n # Copy the first batch as the fixed input.\n if self.total_steps == self.opt.batchsize:\n self.fixed_input.resize_(input[0].size()).copy_(input[0])\n\n ##\n def seed(self, seed_value):\n \"\"\" Seed \n \n Arguments:\n seed_value {int} -- [description]\n \"\"\"\n # Check if seed is default value\n if seed_value == -1:\n return\n\n # Otherwise seed all functionality\n import random\n random.seed(seed_value)\n torch.manual_seed(seed_value)\n torch.cuda.manual_seed_all(seed_value)\n np.random.seed(seed_value)\n torch.backends.cudnn.deterministic = True\n\n ##\n def get_errors(self):\n \"\"\" Get netD and netG errors.\n\n Returns:\n [OrderedDict]: Dictionary containing errors.\n \"\"\"\n\n errors = OrderedDict([\n ('err_d', self.err_d.item()),\n ('err_g', self.err_g.item()),\n ('err_g_adv', self.err_g_adv.item()),\n ('err_g_con', self.err_g_con.item()),\n ('err_g_enc', self.err_g_enc.item())])\n\n return errors\n\n ##\n def get_current_images(self):\n \"\"\" Returns current images.\n\n Returns:\n [reals, fakes, fixed]\n \"\"\"\n\n reals = self.input.data\n fakes = self.fake.data\n fixed = self.netg(self.fixed_input)[0].data\n\n return reals, fakes, fixed\n\n ##\n def save_weights(self, epoch):\n \"\"\"Save netG and netD weights for the current epoch.\n\n Args:\n epoch ([int]): Current epoch number.\n \"\"\"\n\n weight_dir = os.path.join(self.opt.outf, self.opt.name, 'train', 'weights')\n if not os.path.exists(weight_dir): os.makedirs(weight_dir)\n\n torch.save({'epoch': epoch + 1, 'state_dict': self.netg.state_dict()},\n '%s/netG_%s.pth' % (weight_dir,epoch))\n torch.save({'epoch': epoch + 1, 'state_dict': self.netd.state_dict()},\n '%s/netD_%s.pth' % (weight_dir,epoch))\n\n ##\n def train_one_epoch(self):\n \"\"\" Train the model for one epoch.\n \"\"\"\n\n self.netg.train()\n epoch_iter = 0\n for data in tqdm(self.dataloader['train'], leave=False, total=len(self.dataloader['train'])):\n self.total_steps += self.opt.batchsize\n epoch_iter += self.opt.batchsize\n\n self.set_input(data)\n # self.optimize()\n self.optimize_params()\n\n if self.total_steps % self.opt.print_freq == 0:\n errors = self.get_errors()\n if self.opt.display:\n counter_ratio = float(epoch_iter) / len(self.dataloader['train'].dataset)\n self.visualizer.plot_current_errors(self.epoch, counter_ratio, errors)\n\n if self.total_steps % self.opt.save_image_freq == 0:\n reals, fakes, fixed = self.get_current_images()\n self.visualizer.save_current_images(self.epoch, reals, fakes, fixed)\n if self.opt.display:\n self.visualizer.display_current_images(reals, fakes, fixed)\n\n print(\">> Training model %s. Epoch %d/%d\" % (self.name, self.epoch+1, self.opt.niter))\n # self.visualizer.print_current_errors(self.epoch, errors)\n\n ##\n def train(self):\n \"\"\" Train the model\n \"\"\"\n\n ##\n # TRAIN\n self.total_steps = 0\n best_auc = 0\n if self.opt.phase==\"test\":\n self.test()\n elif self.opt.phase==\"train\":\n # Train for niter epochs.\n print(\">> Training model %s.\" % self.name)\n for self.epoch in range(self.opt.iter, self.opt.niter):\n # Train for one epoch\n self.train_one_epoch()\n #res = self.test()\n #if res[self.opt.metric] > best_auc:\n if (self.epoch % self.opt.save_weight_freq == 0) and self.opt.phase==\"train\":\n #best_auc = res[self.opt.metric]\n self.save_weights(self.epoch)\n #self.visualizer.print_current_performance(res, best_auc)\n print(\">> Training model %s.[Done]\" % self.name)\n\n ##\n def test(self):\n \"\"\" Test GANomaly model.\n\n Args:\n dataloader ([type]): Dataloader for the test set\n\n Raises:\n IOError: Model weights not found.\n \"\"\"\n with torch.no_grad():\n # Load the weights of netg and netd.\n if self.opt.load_weights:\n if self.opt.testOnefilepath==\"\":\n path = \"./output/{}/{}/train/weights/netG.pth\".format(self.name.lower(), self.opt.dataset)\n else:\n path=\"./savedWeights/netG.pth\"\n\n pretrained_dict = torch.load(path)['state_dict']\n\n try:\n self.netg.load_state_dict(pretrained_dict)\n except IOError:\n raise IOError(\"netG weights not found\")\n print(' Loaded weights.')\n\n self.opt.phase = 'test'\n\n # Create big error tensor for the test set.\n self.an_scores = torch.zeros(size=(len(self.dataloader['test'].dataset),), dtype=torch.float32, device=self.device)\n self.gt_labels = torch.zeros(size=(len(self.dataloader['test'].dataset),), dtype=torch.long, device=self.device)\n self.latent_i = torch.zeros(size=(len(self.dataloader['test'].dataset), self.opt.nz), dtype=torch.float32, device=self.device)\n self.latent_o = torch.zeros(size=(len(self.dataloader['test'].dataset), self.opt.nz), dtype=torch.float32, device=self.device)\n\n print(\" Testing model %s.\" % self.name)\n self.times = []\n self.total_steps = 0\n epoch_iter = 0\n for i, data in enumerate(self.dataloader['test'], 0):\n self.total_steps += self.opt.batchsize\n epoch_iter += self.opt.batchsize\n time_i = time.time()\n self.set_input(data)\n self.fake, latent_i, latent_o = self.netg(self.input)\n\n error = torch.mean(torch.pow((latent_i-latent_o), 2), dim=1)\n time_o = time.time()\n\n self.an_scores[i*self.opt.batchsize : i*self.opt.batchsize+error.size(0)] = error.reshape(error.size(0))\n self.gt_labels[i*self.opt.batchsize : i*self.opt.batchsize+error.size(0)] = self.gt.reshape(error.size(0))\n self.latent_i [i*self.opt.batchsize : i*self.opt.batchsize+error.size(0), :] = latent_i.reshape(error.size(0), self.opt.nz)\n self.latent_o [i*self.opt.batchsize : i*self.opt.batchsize+error.size(0), :] = latent_o.reshape(error.size(0), self.opt.nz)\n\n self.times.append(time_o - time_i)\n\n # Save test images.\n if self.opt.save_test_images:\n if self.opt.testOnefilepath==\"\":\n dst = os.path.join(self.opt.outf, self.opt.name, 'test', 'images')\n else:\n dst=\"./testResultOneFiles\"\n \n if not os.path.isdir(dst):\n os.makedirs(dst)\n real, fake, _ = self.get_current_images()\n vutils.save_image(real, '%s/real_%03d.png' % (dst, i+1), normalize=True)\n vutils.save_image(fake, '%s/fake_%03d.png' % (dst, i+1), normalize=True)\n\n # Measure inference time.\n self.times = np.array(self.times)\n self.times = np.mean(self.times[:100] * 1000)\n\n # Scale error vector between [0, 1]\n self.an_scores = (self.an_scores - torch.min(self.an_scores)) / (torch.max(self.an_scores) - torch.min(self.an_scores))\n # auc, eer = roc(self.gt_labels, self.an_scores)\n '''\n auc = evaluate(self.gt_labels, self.an_scores, metric=self.opt.metric)\n performance = OrderedDict([('Avg Run Time (ms/batch)', self.times), (self.opt.metric, auc)])\n\n if self.opt.display_id > 0 and self.opt.phase == 'test':\n counter_ratio = float(epoch_iter) / len(self.dataloader['test'].dataset)\n self.visualizer.plot_performance(self.epoch, counter_ratio, performance)\n return performance\n '''\n return \"bye\"\n\n##\nclass Ganomaly(BaseModel):\n \"\"\"GANomaly Class\n \"\"\"\n\n @property\n def name(self): return 'Ganomaly'\n\n def __init__(self, opt, dataloader):\n super(Ganomaly, self).__init__(opt, dataloader)\n\n # -- Misc attributes\n self.epoch = 0\n self.times = []\n self.total_steps = 0\n\n ##\n # Create and initialize networks.\n self.netg = NetG(self.opt).to(self.device)\n self.netd = NetD(self.opt).to(self.device)\n self.netg.apply(weights_init)\n self.netd.apply(weights_init)\n\n ##\n if self.opt.resume != '':\n print(\"\\nLoading pre-trained networks.\")\n self.opt.iter = torch.load(os.path.join(self.opt.resume, 'netG.pth'))['epoch']\n self.netg.load_state_dict(torch.load(os.path.join(self.opt.resume, 'netG.pth'))['state_dict'])\n self.netd.load_state_dict(torch.load(os.path.join(self.opt.resume, 'netD.pth'))['state_dict'])\n print(\"\\tDone.\\n\")\n\n self.l_adv = l2_loss\n self.l_con = nn.L1Loss()\n self.l_enc = l2_loss\n self.l_bce = nn.BCELoss()\n\n ##\n # Initialize input tensors.\n self.input = torch.empty(size=(self.opt.batchsize, 3, self.opt.isize, self.opt.isize), dtype=torch.float32, device=self.device)\n self.label = torch.empty(size=(self.opt.batchsize,), dtype=torch.float32, device=self.device)\n self.gt = torch.empty(size=(opt.batchsize,), dtype=torch.long, device=self.device)\n self.fixed_input = torch.empty(size=(self.opt.batchsize, 3, self.opt.isize, self.opt.isize), dtype=torch.float32, device=self.device)\n self.real_label = torch.ones (size=(self.opt.batchsize,), dtype=torch.float32, device=self.device)\n self.fake_label = torch.zeros(size=(self.opt.batchsize,), dtype=torch.float32, device=self.device)\n ##\n # Setup optimizer\n if self.opt.isTrain:\n self.netg.train()\n self.netd.train()\n self.optimizer_d = optim.Adam(self.netd.parameters(), lr=self.opt.lr, betas=(self.opt.beta1, 0.999))\n self.optimizer_g = optim.Adam(self.netg.parameters(), lr=self.opt.lr, betas=(self.opt.beta1, 0.999))\n\n ##\n def forward_g(self):\n \"\"\" Forward propagate through netG\n \"\"\"\n self.fake, self.latent_i, self.latent_o = self.netg(self.input)\n\n ##\n def forward_d(self):\n \"\"\" Forward propagate through netD\n \"\"\"\n self.pred_real, self.feat_real = self.netd(self.input)\n self.pred_fake, self.feat_fake = self.netd(self.fake.detach())\n\n ##\n def backward_g(self):\n \"\"\" Backpropagate through netG\n \"\"\"\n self.err_g_adv = self.l_adv(self.netd(self.input)[1], self.netd(self.fake)[1])\n self.err_g_con = self.l_con(self.fake, self.input)\n self.err_g_enc = self.l_enc(self.latent_o, self.latent_i)\n self.err_g = self.err_g_adv * self.opt.w_adv + \\\n self.err_g_con * self.opt.w_con + \\\n self.err_g_enc * self.opt.w_enc\n self.err_g.backward(retain_graph=True)\n\n ##\n def backward_d(self):\n \"\"\" Backpropagate through netD\n \"\"\"\n # Real - Fake Loss\n self.err_d_real = self.l_bce(self.pred_real, self.real_label)\n self.err_d_fake = self.l_bce(self.pred_fake, self.fake_label)\n\n # NetD Loss & Backward-Pass\n self.err_d = (self.err_d_real + self.err_d_fake) * 0.5\n self.err_d.backward()\n\n ##\n def reinit_d(self):\n \"\"\" Re-initialize the weights of netD\n \"\"\"\n self.netd.apply(weights_init)\n print(' Reloading net d')\n\n def optimize_params(self):\n \"\"\" Forwardpass, Loss Computation and Backwardpass.\n \"\"\"\n # Forward-pass\n self.forward_g()\n self.forward_d()\n\n # Backward-pass\n # netg\n self.optimizer_g.zero_grad()\n self.backward_g()\n self.optimizer_g.step()\n\n # netd\n self.optimizer_d.zero_grad()\n self.backward_d()\n self.optimizer_d.step()\n if self.err_d.item() < 1e-5: self.reinit_d()\n" ]
[ [ "numpy.random.seed", "torch.nn.BCELoss", "numpy.mean", "numpy.array", "torch.nn.L1Loss" ] ]
The-Academic-Observatory/observatory-reports
[ "6b59f3e1950ba2ed69c37eb64b845f3224d52cbb" ]
[ "observatory-reports/observatory/reports/charts/output_types_time_chart.py" ]
[ "# Copyright 2020 Curtin University\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# Author: Cameron Neylon\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nfrom observatory.reports import defaults\nfrom .generic_time_chart import GenericTimeChart\n\n\nclass OutputTypesTimeChart(GenericTimeChart):\n \"\"\"Generate a Plot of Output Types Over Time\n\n Shares the `types_palette` with OutputTypesPieChart\n \"\"\"\n\n def __init__(self,\n df: pd.DataFrame,\n identifier: str,\n year_range: tuple = (2000, 2020),\n typecolumn: str = 'type',\n countcolumn: str = 'count'\n ):\n \"\"\"Initialisation function\n \"\"\"\n\n columns = ['Output Types', 'value']\n self.typecolumn = typecolumn\n self.countcolumn = countcolumn\n super().__init__(df, columns, identifier, year_range)\n self.melt_var_name = 'Output Types'\n\n def process_data(self):\n \"\"\"Data selection and processing function\n \"\"\"\n\n self.df['Output Types'] = self.df[self.typecolumn]\n self.df['value'] = self.df[self.countcolumn]\n columns = ['id', 'Year of Publication'] + self.columns\n self.columns = defaults.output_types\n figdata = self.df[self.df.id == self.identifier][columns]\n figdata.sort_values('Year of Publication', inplace=True)\n self.figdata = figdata\n return self.figdata\n\n def plot(self,\n palette=None,\n ax=None,\n **kwargs):\n \"\"\"Plotting function\n \"\"\"\n\n if not palette:\n palette = defaults.outputs_palette\n super().plot(palette=palette,\n ax=ax, **kwargs)\n plt.ylabel('Number of Outputs')\n return self.fig\n" ]
[ [ "matplotlib.pyplot.ylabel" ] ]
lupalab/neural-statistician
[ "52d3c2447d02304c2aea66112a59fad8324c1687", "52d3c2447d02304c2aea66112a59fad8324c1687" ]
[ "faces/facesmodel.py", "omniglot/omninets.py" ]
[ "import os\nimport sys\nimport torch\n\nfrom facesnets import (SharedConvolutionalEncoder, StatisticNetwork, InferenceNetwork,\n LatentDecoder, ObservationDecoder)\nfrom torch.autograd import Variable\nfrom torch import nn\nfrom torch.nn import functional as F, init\ntry:\n from utils import (kl_diagnormal_diagnormal, kl_diagnormal_stdnormal,\n gaussian_log_likelihood)\nexcept ModuleNotFoundError:\n # put parent directory in path for utils\n sys.path.append(os.path.join(os.path.dirname(__file__), '..'))\n from utils import (kl_diagnormal_diagnormal, kl_diagnormal_stdnormal,\n gaussian_log_likelihood)\n\n\n# Model\nclass Statistician(nn.Module):\n def __init__(self, batch_size=16, sample_size=200, n_features=1,\n c_dim=3, n_hidden_statistic=128, hidden_dim_statistic=3,\n n_stochastic=1, z_dim=16, n_hidden=3, hidden_dim=128,\n nonlinearity=F.relu, print_vars=False):\n \"\"\"\n\n :param batch_size:\n :param sample_size: \n :param n_features: \n :param c_dim: \n :param n_hidden_statistic: \n :param hidden_dim_statistic: \n :param n_stochastic: \n :param z_dim: \n :param n_hidden: \n :param hidden_dim: \n :param nonlinearity: \n :param print_vars: \n \"\"\"\n super(Statistician, self).__init__()\n # data shape\n self.batch_size = batch_size\n self.sample_size = sample_size\n self.n_features = n_features\n\n # context\n self.c_dim = c_dim\n self.n_hidden_statistic = n_hidden_statistic\n self.hidden_dim_statistic = hidden_dim_statistic\n\n # latent\n self.n_stochastic = n_stochastic\n self.z_dim = z_dim\n self.n_hidden = n_hidden\n self.hidden_dim = hidden_dim\n\n self.nonlinearity = nonlinearity\n\n # modules\n # convolutional encoder\n self.shared_convolutional_encoder = SharedConvolutionalEncoder(self.nonlinearity)\n\n # statistic network\n statistic_args = (self.batch_size, self.sample_size, self.n_features,\n self.n_hidden_statistic, self.hidden_dim_statistic,\n self.c_dim, self.nonlinearity)\n self.statistic_network = StatisticNetwork(*statistic_args)\n\n z_args = (self.batch_size, self.sample_size, self.n_features,\n self.n_hidden, self.hidden_dim, self.c_dim, self.z_dim,\n self.nonlinearity)\n # inference networks\n self.inference_networks = nn.ModuleList([InferenceNetwork(*z_args)\n for _ in range(self.n_stochastic)])\n\n # latent decoders\n self.latent_decoders = nn.ModuleList([LatentDecoder(*z_args)\n for _ in range(self.n_stochastic)])\n\n # observation decoder\n observation_args = (self.batch_size, self.sample_size, self.n_features,\n self.n_hidden, self.hidden_dim, self.c_dim,\n self.n_stochastic, self.z_dim, self.nonlinearity)\n self.observation_decoder = ObservationDecoder(*observation_args)\n\n # initialize weights\n self.apply(self.weights_init)\n\n # print variables for sanity check and debugging\n if print_vars:\n for i, pair in enumerate(self.named_parameters()):\n name, param = pair\n print(\"{} --> {}, {}\".format(i + 1, name, param.size()))\n print()\n\n def forward(self, x):\n # convolutional encoder\n h = self.shared_convolutional_encoder(x)\n\n # statistic network\n c_mean, c_logvar = self.statistic_network(h)\n if self.training:\n c = self.reparameterize_gaussian(c_mean, c_logvar)\n else: # sampling conditioned on inputs\n c = c_mean\n\n # inference networks\n qz_samples = []\n qz_params = []\n z = None\n for inference_network in self.inference_networks:\n z_mean, z_logvar = inference_network(h, z, c)\n qz_params.append([z_mean, z_logvar])\n z = self.reparameterize_gaussian(z_mean, z_logvar)\n qz_samples.append(z)\n\n # latent decoders\n pz_params = []\n z = None\n for i, latent_decoder in enumerate(self.latent_decoders):\n z_mean, z_logvar = latent_decoder(z, c)\n pz_params.append([z_mean, z_logvar])\n z = qz_samples[i]\n\n # observation decoder\n zs = torch.cat(qz_samples, dim=1)\n x_mean, x_logvar = self.observation_decoder(zs, c)\n\n outputs = (\n (c_mean, c_logvar),\n (qz_params, pz_params),\n (x, x_mean, x_logvar)\n )\n\n return outputs\n\n def loss(self, outputs, weight):\n c_outputs, z_outputs, x_outputs = outputs\n\n # 1. Reconstruction loss\n x, x_mean, x_logvar = x_outputs\n recon_loss = gaussian_log_likelihood(x.view(-1, 3, 64, 64), x_mean, x_logvar, clip=True)\n recon_loss /= (self.batch_size * self.sample_size)\n\n # 2. KL Divergence terms\n kl = 0\n\n # a) Context divergence\n c_mean, c_logvar = c_outputs\n kl_c = kl_diagnormal_stdnormal(c_mean, c_logvar)\n kl += kl_c\n\n # b) Latent divergences\n qz_params, pz_params = z_outputs\n shapes = (\n (self.batch_size, self.sample_size, self.z_dim),\n (self.batch_size, 1, self.z_dim)\n )\n for i in range(self.n_stochastic):\n args = (qz_params[i][0].view(shapes[0]),\n qz_params[i][1].view(shapes[0]),\n pz_params[i][0].view(shapes[1] if i == 0 else shapes[0]),\n pz_params[i][1].view(shapes[1] if i == 0 else shapes[0]))\n kl_z = kl_diagnormal_diagnormal(*args)\n kl += kl_z\n\n kl /= (self.batch_size * self.sample_size)\n\n # Variational lower bound and weighted loss\n vlb = recon_loss - kl\n loss = - ((weight * recon_loss) - (kl / weight))\n\n return loss, vlb\n\n def step(self, inputs, alpha, optimizer, clip_gradients=True):\n assert self.training is True\n\n outputs = self.forward(inputs)\n loss, vlb = self.loss(outputs, weight=(alpha + 1))\n\n # perform gradient update\n optimizer.zero_grad()\n loss.backward()\n if clip_gradients:\n for param in self.parameters():\n if param.grad is not None:\n param.grad.data = param.grad.data.clamp(min=-0.5, max=0.5)\n optimizer.step()\n\n # output variational lower bound for batch\n return vlb.data[0]\n\n def sample(self):\n c = torch.randn(self.batch_size, self.c_dim)\n\n # latent decoders\n pz_samples = []\n z = None\n for i, latent_decoder in enumerate(self.latent_decoders):\n z_mean, z_logvar = latent_decoder(z, c)\n z = self.reparameterize_gaussian(z_mean, z_logvar)\n pz_samples.append(z)\n\n # observation decoder\n zs = torch.cat(pz_samples, dim=1)\n x_mean, x_logvar = self.observation_decoder(zs, c)\n\n return x_mean\n\n def sample_conditioned(self, inputs):\n h = self.shared_convolutional_encoder(inputs)\n c, _ = self.statistic_network(h)\n\n # latent decoders\n pz_samples = []\n z = None\n for i, latent_decoder in enumerate(self.latent_decoders):\n z_mean, z_logvar = latent_decoder(z, c)\n if i == 0:\n z_mean = z_mean.repeat(self.sample_size, 1)\n z_logvar = z_logvar.repeat(self.sample_size, 1)\n z = self.reparameterize_gaussian(z_mean, z_logvar)\n pz_samples.append(z)\n\n # observation decoder\n zs = torch.cat(pz_samples, dim=1)\n x_mean, x_logvar = self.observation_decoder(zs, c)\n\n return x_mean\n\n def save(self, optimizer, path):\n torch.save({\n 'model_state': self.state_dict(),\n 'optimizer_state': optimizer.state_dict()\n }, path)\n\n @staticmethod\n def reparameterize_gaussian(mean, logvar):\n std = torch.exp(0.5 * logvar)\n eps = Variable(torch.randn(std.size()).cuda())\n return mean + std * eps\n\n @staticmethod\n def weights_init(m):\n if isinstance(m, (nn.Linear, nn.Conv2d)):\n init.xavier_normal(m.weight.data, gain=init.calculate_gain('relu'))\n init.constant(m.bias.data, 0)\n elif isinstance(m, nn.BatchNorm1d):\n pass\n", "import torch\n\nfrom torch import nn\nfrom torch.autograd import Variable\nfrom torch.nn import functional as F\n\n\n# Module for residual/skip connections\nclass FCResBlock(nn.Module):\n def __init__(self, dim, n, nonlinearity, batch_norm=True):\n \"\"\"\n\n :param dim:\n :param n:\n :param nonlinearity:\n \"\"\"\n super(FCResBlock, self).__init__()\n self.n = n\n self.nonlinearity = nonlinearity\n self.batch_norm = batch_norm\n if self.batch_norm:\n self.block = nn.ModuleList(\n [nn.ModuleList([nn.Linear(dim, dim), nn.BatchNorm1d(num_features=dim)])\n for _ in range(self.n)]\n )\n else:\n self.block = nn.ModuleList([nn.Linear(dim, dim) for _ in range(self.n)])\n\n def forward(self, x):\n e = x + 0\n\n if self.batch_norm:\n for i, pair in enumerate(self.block):\n fc, bn = pair\n e = fc(e)\n e = bn(e)\n if i < (self.n - 1):\n e = self.nonlinearity(e)\n\n else:\n for i, layer in enumerate(self.block):\n e = layer(e)\n if i < (self.n - 1):\n e = self.nonlinearity(e)\n\n return self.nonlinearity(e + x)\n\n\n# Building block for convolutional encoder with same padding\nclass Conv2d3x3(nn.Module):\n def __init__(self, in_channels, out_channels, downsample=False):\n super(Conv2d3x3, self).__init__()\n stride = 2 if downsample else 1\n self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=3,\n padding=1, stride=stride)\n\n def forward(self, x):\n return self.conv(x)\n\n\n# SHARED CONVOLUTIONAL ENCODER\nclass SharedConvolutionalEncoder(nn.Module):\n def __init__(self, nonlinearity):\n super(SharedConvolutionalEncoder, self).__init__()\n self.nonlinearity = nonlinearity\n\n self.conv_layers = nn.ModuleList([\n Conv2d3x3(in_channels=1, out_channels=64),\n Conv2d3x3(in_channels=64, out_channels=64),\n Conv2d3x3(in_channels=64, out_channels=64, downsample=True),\n # shape is now (-1, 64, 14 , 14)\n Conv2d3x3(in_channels=64, out_channels=128),\n Conv2d3x3(in_channels=128, out_channels=128),\n Conv2d3x3(in_channels=128, out_channels=128, downsample=True),\n # shape is now (-1, 128, 7, 7)\n Conv2d3x3(in_channels=128, out_channels=256),\n Conv2d3x3(in_channels=256, out_channels=256),\n Conv2d3x3(in_channels=256, out_channels=256, downsample=True)\n # shape is now (-1, 256, 4, 4)\n ])\n\n self.bn_layers = nn.ModuleList([\n nn.BatchNorm2d(num_features=64),\n nn.BatchNorm2d(num_features=64),\n nn.BatchNorm2d(num_features=64),\n nn.BatchNorm2d(num_features=128),\n nn.BatchNorm2d(num_features=128),\n nn.BatchNorm2d(num_features=128),\n nn.BatchNorm2d(num_features=256),\n nn.BatchNorm2d(num_features=256),\n nn.BatchNorm2d(num_features=256),\n ])\n\n def forward(self, x):\n h = x.view(-1, 1, 28, 28)\n for conv, bn in zip(self.conv_layers, self.bn_layers):\n h = conv(h)\n h = bn(h)\n h = self.nonlinearity(h)\n return h\n\n\n# PRE-POOLING FOR STATISTIC NETWORK\nclass PrePool(nn.Module):\n \"\"\"\n\n \"\"\"\n\n def __init__(self, batch_size, n_features, n_hidden, hidden_dim, nonlinearity):\n super(PrePool, self).__init__()\n self.batch_size = batch_size\n self.n_features = n_features\n\n self.n_hidden = n_hidden\n self.hidden_dim = hidden_dim\n\n self.nonlinearity = nonlinearity\n\n # modules\n self.fc = nn.Linear(self.n_features, self.hidden_dim)\n self.bn = nn.BatchNorm1d(self.hidden_dim)\n\n def forward(self, h):\n # reshape and affine\n e = h.view(-1, self.n_features)\n e = self.fc(e)\n e = self.bn(e)\n e = self.nonlinearity(e)\n\n return e\n\n\n# POST POOLING FOR STATISTIC NETWORK\nclass PostPool(nn.Module):\n \"\"\"\n\n \"\"\"\n\n def __init__(self, n_hidden, hidden_dim, c_dim, nonlinearity):\n super(PostPool, self).__init__()\n self.n_hidden = n_hidden\n self.hidden_dim = hidden_dim\n self.c_dim = c_dim\n\n self.nonlinearity = nonlinearity\n\n # modules\n self.fc_layers = nn.ModuleList([nn.Linear(self.hidden_dim, self.hidden_dim),\n nn.Linear(self.hidden_dim, self.hidden_dim)])\n self.bn_layers = nn.ModuleList([nn.BatchNorm1d(self.hidden_dim),\n nn.BatchNorm1d(self.hidden_dim)])\n\n self.fc_params = nn.Linear(self.hidden_dim, 2 * self.c_dim)\n self.bn_params = nn.BatchNorm1d(1, eps=1e-3, momentum=1e-2)\n\n def forward(self, e):\n for fc, bn in zip(self.fc_layers, self.bn_layers):\n e = fc(e)\n e = bn(e)\n e = self.nonlinearity(e)\n\n # affine transformation to parameters\n e = self.fc_params(e)\n\n # 'global' batch norm\n e = e.view(-1, 1, 2 * self.c_dim)\n e = self.bn_params(e)\n e = e.view(-1, 2 * self.c_dim)\n\n mean, logvar = e[:, :self.c_dim], e[:, self.c_dim:]\n\n return mean, logvar\n\n\n# STATISTIC NETWORK q(c|D)\nclass StatisticNetwork(nn.Module):\n \"\"\"\n\n \"\"\"\n\n def __init__(self, batch_size, sample_size, n_features,\n n_hidden, hidden_dim, c_dim, nonlinearity):\n super(StatisticNetwork, self).__init__()\n self.batch_size = batch_size\n self.sample_size = sample_size\n self.n_features = n_features\n\n self.n_hidden = n_hidden\n self.hidden_dim = hidden_dim\n self.c_dim = c_dim\n\n self.nonlinearity = nonlinearity\n\n # modules\n self.prepool = PrePool(self.batch_size, self.n_features,\n self.n_hidden, self.hidden_dim, self.nonlinearity)\n self.postpool = PostPool(self.n_hidden, self.hidden_dim,\n self.c_dim, self.nonlinearity)\n\n def forward(self, h):\n e = self.prepool(h)\n # e = self.sample_dropout(e)\n e = self.pool(e)\n e = self.postpool(e)\n return e\n\n def pool(self, e):\n e = e.view(self.batch_size, self.sample_size, self.hidden_dim)\n e = e.mean(1).view(self.batch_size, self.hidden_dim)\n return e\n\n def sample_dropout(self, e):\n # create mask\n a = Variable(torch.ones((self.batch_size, 1, 1)).cuda())\n p = 0.5 if self.training else 1\n b = Variable(torch.bernoulli(p * torch.ones((self.batch_size,\n self.sample_size - 1, 1)).cuda()))\n mask = torch.cat([a, b], 1)\n\n # zero out samples\n e = e.view(self.batch_size, self.sample_size, self.hidden_dim)\n e = e * mask.expand_as(e)\n\n # take mean across sample dimension\n extra_feature = torch.sum(mask, 1)\n e = torch.sum(e, 1)\n e /= extra_feature.expand_as(e)\n\n # add number of retained samples as extra feature\n e = torch.cat([e, extra_feature], 2).squeeze(1)\n\n return e\n\n\nclass InferenceNetwork(nn.Module):\n \"\"\"\n Inference network q(z|h, z, c) gives approximate posterior over latent variables.\n \"\"\"\n def __init__(self, batch_size, sample_size, n_features,\n n_hidden, hidden_dim, c_dim, z_dim, nonlinearity):\n super(InferenceNetwork, self).__init__()\n self.batch_size = batch_size\n self.sample_size = sample_size\n self.n_features = n_features\n\n self.n_hidden = n_hidden\n self.hidden_dim = hidden_dim\n self.c_dim = c_dim\n\n self.z_dim = z_dim\n\n self.nonlinearity = nonlinearity\n\n # modules\n self.fc_h = nn.Linear(self.n_features, self.hidden_dim)\n self.fc_c = nn.Linear(self.c_dim, self.hidden_dim)\n self.fc_z = nn.Linear(self.z_dim, self.hidden_dim)\n\n self.fc_res_block = FCResBlock(dim=self.hidden_dim, n=self.n_hidden,\n nonlinearity=self.nonlinearity, batch_norm=True)\n\n self.fc_params = nn.Linear(self.hidden_dim, 2 * self.z_dim)\n self.bn_params = nn.BatchNorm1d(1, eps=1e-3, momentum=1e-2)\n\n def forward(self, h, z, c):\n # combine h, z, and c\n # embed h\n eh = h.view(-1, self.n_features)\n eh = self.fc_h(eh)\n eh = eh.view(self.batch_size, self.sample_size, self.hidden_dim)\n\n # embed z if we have more than one stochastic layer\n if z is not None:\n ez = z.view(-1, self.z_dim)\n ez = self.fc_z(ez)\n ez = ez.view(self.batch_size, self.sample_size, self.hidden_dim)\n else:\n ez = Variable(torch.zeros(eh.size()).cuda())\n\n # embed c and expand for broadcast addition\n ec = self.fc_c(c)\n ec = ec.view(self.batch_size, 1, self.hidden_dim).expand_as(eh)\n\n # sum and reshape\n e = eh + ez + ec\n e = e.view(self.batch_size * self.sample_size, self.hidden_dim)\n e = self.nonlinearity(e)\n\n # for layer in self.fc_block:\n e = self.fc_res_block(e)\n\n # affine transformation to parameters\n e = self.fc_params(e)\n\n # 'global' batch norm\n e = e.view(-1, 1, 2 * self.z_dim)\n e = self.bn_params(e)\n e = e.view(-1, 2 * self.z_dim)\n\n mean, logvar = e[:, :self.z_dim].contiguous(), e[:, self.z_dim:].contiguous()\n\n return mean, logvar\n\n\n# LATENT DECODER p(z|z, c)\nclass LatentDecoder(nn.Module):\n \"\"\"\n\n \"\"\"\n\n def __init__(self, batch_size, sample_size, n_features,\n n_hidden, hidden_dim, c_dim, z_dim, nonlinearity):\n super(LatentDecoder, self).__init__()\n self.batch_size = batch_size\n self.sample_size = sample_size\n self.n_features = n_features\n\n self.n_hidden = n_hidden\n self.hidden_dim = hidden_dim\n self.c_dim = c_dim\n\n self.z_dim = z_dim\n\n self.nonlinearity = nonlinearity\n\n # modules\n self.fc_c = nn.Linear(self.c_dim, self.hidden_dim)\n self.fc_z = nn.Linear(self.z_dim, self.hidden_dim)\n\n self.fc_res_block = FCResBlock(dim=self.hidden_dim, n=self.n_hidden,\n nonlinearity=self.nonlinearity, batch_norm=True)\n\n self.fc_params = nn.Linear(self.hidden_dim, 2 * self.z_dim)\n self.bn_params = nn.BatchNorm1d(1, eps=1e-3, momentum=1e-2)\n\n def forward(self, z, c):\n # combine z and c\n # embed z if we have more than one stochastic layer\n if z is not None:\n ez = z.view(-1, self.z_dim)\n ez = self.fc_z(ez)\n ez = ez.view(self.batch_size, self.sample_size, self.hidden_dim)\n else:\n ez = Variable(torch.zeros(self.batch_size, 1, self.hidden_dim).cuda())\n\n # embed c and expand for broadcast addition\n ec = self.fc_c(c)\n ec = ec.view(self.batch_size, 1, self.hidden_dim).expand_as(ez)\n\n # sum and reshape\n e = ez + ec\n e = e.view(-1, self.hidden_dim)\n e = self.nonlinearity(e)\n\n # for layer in self.fc_block:\n e = self.fc_res_block(e)\n\n # affine transformation to parameters\n e = self.fc_params(e)\n\n # 'global' batch norm\n e = e.view(-1, 1, 2 * self.z_dim)\n e = self.bn_params(e)\n e = e.view(-1, 2 * self.z_dim)\n\n mean, logvar = e[:, :self.z_dim].contiguous(), e[:, self.z_dim:].contiguous()\n\n return mean, logvar\n\n\n# Observation Decoder p(x|z, c)\nclass ObservationDecoder(nn.Module):\n \"\"\"\n\n \"\"\"\n def __init__(self, batch_size, sample_size, n_features,\n n_hidden, hidden_dim, c_dim, n_stochastic, z_dim,\n nonlinearity):\n super(ObservationDecoder, self).__init__()\n self.batch_size = batch_size\n self.sample_size = sample_size\n self.n_features = n_features\n\n self.n_hidden = n_hidden\n self.hidden_dim = hidden_dim\n self.c_dim = c_dim\n\n self.n_stochastic = n_stochastic\n self.z_dim = z_dim\n\n self.nonlinearity = nonlinearity\n\n # modules\n self.fc_zs = nn.Linear(self.n_stochastic * self.z_dim, self.hidden_dim)\n self.fc_c = nn.Linear(self.c_dim, self.hidden_dim)\n\n self.fc_initial = nn.Linear(self.hidden_dim, 256 * 4 * 4)\n\n self.conv_layers = nn.ModuleList([\n Conv2d3x3(256, 256),\n Conv2d3x3(256, 256),\n nn.ConvTranspose2d(256, 256, kernel_size=2, stride=2),\n Conv2d3x3(256, 128),\n Conv2d3x3(128, 128),\n nn.ConvTranspose2d(128, 128, kernel_size=2, stride=2),\n Conv2d3x3(128, 64),\n nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=0),\n nn.ConvTranspose2d(64, 64, kernel_size=2, stride=2)\n ])\n \n self.bn_layers = nn.ModuleList([\n nn.BatchNorm2d(256),\n nn.BatchNorm2d(256),\n nn.BatchNorm2d(256),\n nn.BatchNorm2d(128),\n nn.BatchNorm2d(128),\n nn.BatchNorm2d(128),\n nn.BatchNorm2d(64),\n nn.BatchNorm2d(64),\n nn.BatchNorm2d(64),\n ])\n\n self.conv_final = nn.Conv2d(64, 1, kernel_size=1)\n\n def forward(self, zs, c):\n # concatenate zs and c\n ezs = self.fc_zs(zs)\n ezs = ezs.view(self.batch_size, self.sample_size, self.hidden_dim)\n\n ec = self.fc_c(c)\n ec = ec.view(self.batch_size, 1, self.hidden_dim).expand_as(ezs)\n\n e = ezs + ec\n e = self.nonlinearity(e)\n e = e.view(-1, self.hidden_dim)\n\n e = self.fc_initial(e)\n e = e.view(-1, self.hidden_dim, 4, 4)\n\n for conv, bn in zip(self.conv_layers, self.bn_layers):\n e = conv(e)\n e = bn(e)\n e = self.nonlinearity(e)\n\n e = self.conv_final(e)\n e = F.sigmoid(e)\n\n return e" ]
[ [ "torch.nn.init.calculate_gain", "torch.cat", "torch.randn", "torch.exp", "torch.nn.init.constant" ], [ "torch.nn.BatchNorm1d", "torch.ones", "torch.nn.ConvTranspose2d", "torch.cat", "torch.zeros", "torch.nn.Conv2d", "torch.sum", "torch.nn.Linear", "torch.nn.functional.sigmoid", "torch.nn.BatchNorm2d" ] ]
Miedema/MCNetwork
[ "daab1fe5880c47695c6e21124f99aa6b2589aba1" ]
[ "scripts/seperateFintess_2D.py" ]
[ "#!/usr/bin/python3\nfrom tools import *\nfrom sys import argv\nfrom os.path import join\n\nimport h5py\nimport matplotlib.pylab as plt\nimport numpy as np\n\n\n###################################################### see old version at the end (easier to understand, but less generalized and not using pca) ########################################################################\n\nif len(argv) > 1:\n pathToSimFolder = argv[1]\nelse:\n pathToSimFolder = \"../data/\"\n\n\n# controlFitness = np.load(join(pathToSimFolder,\"fitness.npy\" ))\ncurrents = np.load(join(pathToSimFolder, \"currents.npy\"))\ncurrentsUncert = np.load(join(pathToSimFolder, \"currentsUncert.npy\"))\n\nmin_ = np.min(currents, axis=(1, 2))\nmax_ = np.max(currents, axis=(1, 2))\nnormedCurrents = ((currents.T - min_) / (max_ - min_)).T\n\n\nsamples = currents.shape[0]\nprint(\"samples: \", samples)\n\n# minFitness = 0.8\nbins = 200\n# fitnessBins = 100\n\n\nD = np.array(\n [\n currents[:, 0, 0] - currents[:, 0, 1],\n currents[:, 0, 0] - currents[:, 1, 0],\n currents[:, 0, 0] - currents[:, 1, 1],\n ]\n)\nN = D.shape[0]\n\n\nC = np.cov(D)\n_, M = np.linalg.eig(C)\n\n# M = np.array([[1,-1,0],[0,0,-1],[0.5,0.5,-0.5]]).T #<<<<<-------- define transformation matrix here and ignore PCA\nDelta = M.T @ D\n\n# ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n\n\nDelta_bins, Delta_counts = [], []\n\nfor i in range(N):\n Delta_counts_, Delta_bins_ = np.histogram(Delta[i], bins=bins, density=True)\n Delta_bins.append(Delta_bins_)\n Delta_counts.append(Delta_counts_)\n\n\nDelta_mesh = np.array(\n np.meshgrid(\n *[(Delta_bins[i][1:] + Delta_bins[i][:-1]) / 2 for i in range(N)], indexing=\"ij\"\n )\n)\nprobabilities = np.array(\n np.meshgrid(\n *[(Delta_bins[i][1:] - Delta_bins[i][:-1]) * Delta_counts[i] for i in range(N)],\n indexing=\"ij\",\n )\n)\ntotProbab = np.prod(probabilities, axis=0)\n\n\nD_mesh = np.einsum(\"ji...,i...->j...\", np.linalg.inv(M.T), Delta_mesh)\n\ndiffs = np.zeros((bins, bins, bins, 2, 2, 2, 2))\n\ndiffs[:, :, :, 0, 0, 0, 1] = D_mesh[0]\ndiffs[:, :, :, 0, 0, 1, 0] = D_mesh[1]\ndiffs[:, :, :, 0, 0, 1, 1] = D_mesh[2]\ndiffs[:, :, :, 0, 1, 1, 0] = D_mesh[1] - D_mesh[0]\ndiffs[:, :, :, 0, 1, 1, 1] = D_mesh[2] - D_mesh[0]\ndiffs[:, :, :, 1, 0, 1, 1] = D_mesh[2] - D_mesh[1]\n\ndiffs[:, :, :, 0, 1, 0, 0] = -diffs[:, :, :, 0, 0, 0, 1]\ndiffs[:, :, :, 1, 0, 0, 0] = -diffs[:, :, :, 0, 0, 1, 0]\ndiffs[:, :, :, 1, 1, 0, 0] = -diffs[:, :, :, 0, 0, 1, 1]\ndiffs[:, :, :, 1, 0, 0, 1] = -diffs[:, :, :, 0, 1, 1, 0]\ndiffs[:, :, :, 1, 1, 0, 1] = -diffs[:, :, :, 0, 1, 1, 1]\ndiffs[:, :, :, 1, 1, 1, 0] = -diffs[:, :, :, 1, 0, 1, 1]\n\nmax_min = np.max(np.abs(diffs), axis=(3, 4, 5, 6))\n\nI_normed = np.zeros((bins, bins, bins, 2, 2))\n\nI_normed[:, :, :, 0, 0] = np.max(diffs[:, :, :, 0, 0, :, :], axis=(3, 4)) / max_min\nI_normed[:, :, :, 0, 1] = np.max(diffs[:, :, :, 0, 1, :, :], axis=(3, 4)) / max_min\nI_normed[:, :, :, 1, 0] = np.max(diffs[:, :, :, 1, 0, :, :], axis=(3, 4)) / max_min\nI_normed[:, :, :, 1, 1] = np.max(diffs[:, :, :, 1, 1, :, :], axis=(3, 4)) / max_min\n\n\ndef getFitness(gate, normed_currents):\n def gateFunc(in1, in2):\n if gate == \"AND\":\n return in1 & in2\n if gate == \"NAND\":\n return not (in1 & in2)\n if gate == \"OR\":\n return in1 | in2\n if gate == \"NOR\":\n return not (in1 | in2)\n if gate == \"XOR\":\n return in1 ^ in2\n if gate == \"XNOR\":\n return not (in1 ^ in2)\n\n if len(normed_currents.shape) == 5:\n return 1 - 0.25 * np.sum(\n [\n abs(\n gateFunc(int(i / 2), i % 2)\n - normed_currents[:, :, :, int(i / 2), i % 2]\n )\n for i in range(4)\n ],\n axis=0,\n )\n elif len(normed_currents.shape) == 3:\n return 1 - 0.25 * np.sum(\n [\n abs(gateFunc(int(i / 2), i % 2) - normed_currents[:, int(i / 2), i % 2])\n for i in range(4)\n ],\n axis=0,\n )\n\n\n################################################ 2D distr ################################################\n\n\naxlims = [[-0.01, 0.07], [-0.015, 0.015], [-0.01, 0.01]]\n\npermutations = [(0, 1), (0, 2), (1, 2)]\n\ncounts2D = []\nfor i in range(len(permutations)):\n counts2D.append(\n np.histogram2d(\n Delta[permutations[i][0]],\n Delta[permutations[i][1]],\n bins=bins,\n density=True,\n )[0]\n )\n\ncounts2D_linSeperated = []\nfor i in range(len(permutations)):\n counts2D_linSeperated.append(\n np.multiply(\n *np.meshgrid(\n Delta_counts[permutations[i][0]],\n Delta_counts[permutations[i][1]],\n indexing=\"ij\",\n )\n )\n )\n\nfor i in range(len(permutations)):\n counts2D[i] *= (\n Delta_bins[permutations[i][0]][1] - Delta_bins[permutations[i][0]][0]\n ) * (Delta_bins[permutations[i][1]][1] - Delta_bins[permutations[i][1]][0])\n counts2D_linSeperated[i] *= (\n Delta_bins[permutations[i][0]][1] - Delta_bins[permutations[i][0]][0]\n ) * (Delta_bins[permutations[i][1]][1] - Delta_bins[permutations[i][1]][0])\n\n\nfor i in range(len(permutations)):\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(4.980614173228346, 3.2), sharey=True)\n\n vmin = min(np.min(counts2D_linSeperated[i]), np.min(counts2D[i]))\n vmax = max(np.max(counts2D_linSeperated[i]), np.max(counts2D[i]))\n\n im1 = ax1.imshow(\n counts2D[i],\n cmap=\"gnuplot\",\n vmin=vmin,\n vmax=vmax,\n extent=[\n Delta_bins[permutations[i][1]][0],\n Delta_bins[permutations[i][1]][-1],\n Delta_bins[permutations[i][0]][-1],\n Delta_bins[permutations[i][0]][0],\n ],\n aspect=\"auto\",\n )\n im2 = ax2.imshow(\n counts2D_linSeperated[i],\n cmap=\"gnuplot\",\n vmin=vmin,\n vmax=vmax,\n extent=[\n Delta_bins[permutations[i][1]][0],\n Delta_bins[permutations[i][1]][-1],\n Delta_bins[permutations[i][0]][-1],\n Delta_bins[permutations[i][0]][0],\n ],\n aspect=\"auto\",\n )\n\n ax1.set_xlabel(rf\"$\\scriptsize \\Delta_{{ {permutations[i][1]+1} }}$\")\n ax1.set_ylabel(rf\"$\\scriptsize \\Delta_{{ {permutations[i][0]+1} }}$\")\n ax2.set_xlabel(rf\"$\\scriptsize \\Delta_{{ {permutations[i][1]+1} }}$\")\n\n ax1.set_xlim(axlims[permutations[i][1]])\n ax2.set_xlim(axlims[permutations[i][1]])\n ax1.set_ylim(axlims[permutations[i][0]])\n\n # fig.subplots_adjust(right=0.82)\n # cbar_ax = fig.add_axes([0.86, 0.15, 0.04, 0.7])\n # fig.colorbar(im1, cax=cbar_ax)\n plt.savefig(\n join(\n pathToSimFolder,\n f\"density2D_Delta{permutations[i][0]+1}_Delta{permutations[i][1]+1}_bins_{bins}.png\",\n ),\n bbox_inches=\"tight\",\n dpi=300,\n )\n # plt.show()\n plt.close(fig)\n\n\n########################### fitness plots ###########################\n\ngates = [\"AND\", \"NAND\", \"OR\", \"NOR\", \"XOR\", \"XNOR\"]\n# gates = [\"XOR\"]\nfor gate in gates:\n fitness = getFitness(gate, I_normed)\n controlFitness = getFitness(gate, normedCurrents)\n\n for i in range(len(permutations)):\n fig, (ax1, ax2) = plt.subplots(\n 1, 2, figsize=(4.980614173228346, 3.2), sharey=True\n )\n\n thirdIndex = [j for j in range(3) if j not in permutations[i]][0]\n fitness_seperated = np.sum(probabilities[thirdIndex] * fitness, axis=thirdIndex)\n fitness2D = (\n np.histogram2d(\n Delta[permutations[i][0]],\n Delta[permutations[i][1]],\n bins=bins,\n weights=controlFitness,\n )[0]\n / np.histogram2d(\n Delta[permutations[i][0]], Delta[permutations[i][1]], bins=bins\n )[0]\n )\n\n vmin = min(np.min(fitness_seperated), np.min(fitness2D))\n vmax = max(np.max(fitness_seperated), np.max(fitness2D))\n\n im1 = ax1.imshow(\n fitness2D,\n cmap=\"gnuplot\",\n vmin=vmin,\n vmax=vmax,\n extent=[\n Delta_bins[permutations[i][1]][0],\n Delta_bins[permutations[i][1]][-1],\n Delta_bins[permutations[i][0]][-1],\n Delta_bins[permutations[i][0]][0],\n ],\n aspect=\"auto\",\n )\n im2 = ax2.imshow(\n fitness_seperated,\n cmap=\"gnuplot\",\n vmin=vmin,\n vmax=vmax,\n extent=[\n Delta_bins[permutations[i][1]][0],\n Delta_bins[permutations[i][1]][-1],\n Delta_bins[permutations[i][0]][-1],\n Delta_bins[permutations[i][0]][0],\n ],\n aspect=\"auto\",\n )\n\n ax1.set_xlabel(rf\"$\\scriptsize \\Delta_{{ {permutations[i][1]+1} }}$\")\n ax1.set_ylabel(rf\"$\\scriptsize \\Delta_{{ {permutations[i][0]+1} }}$\")\n ax2.set_xlabel(rf\"$\\scriptsize \\Delta_{{ {permutations[i][1]+1} }}$\")\n\n ax1.set_xlim(axlims[permutations[i][1]])\n ax2.set_xlim(axlims[permutations[i][1]])\n ax1.set_ylim(axlims[permutations[i][0]])\n\n fig.subplots_adjust(right=0.82)\n cbar_ax = fig.add_axes([0.86, 0.15, 0.04, 0.7])\n fig.colorbar(im1, cax=cbar_ax)\n plt.savefig(\n join(\n pathToSimFolder,\n f\"{gate}_fitness2D_Delta{permutations[i][0]+1}_Delta{permutations[i][1]+1}_bins_{bins}.png\",\n ),\n bbox_inches=\"tight\",\n dpi=300,\n )\n # plt.show()\n plt.close(fig)\n\n\n###################################################### old version starts here ########################################################################\n\"\"\"\n#!/usr/bin/python3\nfrom tools import *\nfrom sys import argv\nfrom os.path import join\n\nimport h5py\nimport matplotlib.pylab as plt\nimport numpy as np\n\n\n\nif len(argv)>1:\n pathToSimFolder=argv[1]\nelse:\n pathToSimFolder=\"../data/\"\n\n\n\n\n\ncontrolFitness = np.load(join(pathToSimFolder,\"fitness.npy\" ))\ncurrents = np.load(join(pathToSimFolder,\"currents.npy\" ))\ncurrentsUncert = np.load(join(pathToSimFolder,\"currentsUncert.npy\"))\nN = currents.shape[0]\n\nbins = 50\n\n\nprint(\"################ XOR ################\")\n\n\n\nD_10_01 = currents[:,1,0]-currents[:,0,1]\nD_11_00 = currents[:,1,1]-currents[:,0,0]\nD_DIFF = (currents[:,1,1]+currents[:,0,0]-currents[:,0,1]-currents[:,1,0])/2\n\n\nD0_counts, D0_bins = np.histogram(D_10_01, bins = bins, density = True)\nD1_counts, D1_bins = np.histogram(D_11_00, bins = bins, density = True)\nDd_counts, Dd_bins = np.histogram(D_DIFF , bins = bins, density = True)\n\n\n\nD0_D1_counts, _ , _ = np.histogram2d(D_10_01, D_11_00, bins = bins, density = True)\nD0_Dd_counts, _ , _ = np.histogram2d(D_10_01, D_DIFF, bins = bins, density = True)\nD1_Dd_counts, _ , _ = np.histogram2d(D_11_00, D_DIFF, bins = bins, density = True)\n\nlinSeperated_D0_D1_counts = np.multiply( * np.meshgrid(D0_counts, D1_counts, indexing = \"ij\"))\nlinSeperated_D0_Dd_counts = np.multiply( * np.meshgrid(D0_counts, Dd_counts, indexing = \"ij\"))\nlinSeperated_D1_Dd_counts = np.multiply( * np.meshgrid(D1_counts, Dd_counts, indexing = \"ij\"))\n\n\n\nD0_D1_counts *= (D0_bins[1]-D0_bins[0]) * (D1_bins[1]-D1_bins[0])\nD0_Dd_counts *= (D0_bins[1]-D0_bins[0]) * (Dd_bins[1]-Dd_bins[0])\nD1_Dd_counts *= (D1_bins[1]-D1_bins[0]) * (Dd_bins[1]-Dd_bins[0])\nlinSeperated_D0_D1_counts *= (D0_bins[1]-D0_bins[0]) * (D1_bins[1]-D1_bins[0])\nlinSeperated_D0_Dd_counts *= (D0_bins[1]-D0_bins[0]) * (Dd_bins[1]-Dd_bins[0])\nlinSeperated_D1_Dd_counts *= (D1_bins[1]-D1_bins[0]) * (Dd_bins[1]-Dd_bins[0])\n\n\n\n\n\n\nfig, (ax1, ax2)=plt.subplots(1,2,figsize=(4.980614173228346,3.2), sharey=True)\n\nvmin = min(np.min(linSeperated_D0_D1_counts), np.min(D0_D1_counts))\nvmax = max(np.max(linSeperated_D0_D1_counts), np.max(D0_D1_counts))\n\nim1 = ax1.imshow(D0_D1_counts , cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ D1_bins[0], D1_bins[-1], D0_bins[-1], D0_bins[0]], aspect = \"auto\")\nim2 = ax2.imshow(linSeperated_D0_D1_counts, cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ D1_bins[0], D1_bins[-1], D0_bins[-1], D0_bins[0]], aspect = \"auto\")\n\nax1.set_xlabel(r\"$\\scriptsize \\Delta_{2}^\\textrm{X}$\")\nax1.set_ylabel(r\"$\\scriptsize \\Delta_{1}^\\textrm{X}$\")\nax2.set_xlabel(r\"$\\scriptsize \\Delta_{2}^\\textrm{X}$\")\n\n# fig.subplots_adjust(right=0.82)\n# cbar_ax = fig.add_axes([0.86, 0.15, 0.04, 0.7])\n# fig.colorbar(im1, cax=cbar_ax)\nplt.savefig(join(pathToSimFolder,f\"XOR_density2D_D0_D1_bins_{bins}.png\"),bbox_inches=\"tight\",dpi=300) \n# plt.show()\nplt.close(fig)\n\n\n\n\n\n\n\n\nfig, (ax1, ax2)=plt.subplots(1,2,figsize=(4.980614173228346,3.2), sharey=True)\n\nvmin = min(np.min(linSeperated_D0_Dd_counts), np.min(D0_Dd_counts))\nvmax = max(np.max(linSeperated_D0_Dd_counts), np.max(D0_Dd_counts))\n\nim1 = ax1.imshow(D0_Dd_counts , cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ Dd_bins[0], Dd_bins[-1], D0_bins[-1], D0_bins[0]], aspect = \"auto\")\nim2 = ax2.imshow(linSeperated_D0_Dd_counts, cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ Dd_bins[0], Dd_bins[-1], D0_bins[-1], D0_bins[0]], aspect = \"auto\")\n\nax1.set_xlabel(r\"$\\scriptsize \\Delta_{3}^\\textrm{X}$\")\nax1.set_ylabel(r\"$\\scriptsize \\Delta_{1}^\\textrm{X}$\")\nax2.set_xlabel(r\"$\\scriptsize \\Delta_{3}^\\textrm{X}$\")\n\n# fig.subplots_adjust(right=0.82)\n# cbar_ax = fig.add_axes([0.86, 0.15, 0.04, 0.7])\n# fig.colorbar(im1, cax=cbar_ax)\nplt.savefig(join(pathToSimFolder,f\"XOR_density2D_D0_Dd_bins_{bins}.png\"),bbox_inches=\"tight\",dpi=300) \n# plt.show()\nplt.close(fig)\n\n\n\n\n\n\n\nfig, (ax1, ax2)=plt.subplots(1,2,figsize=(4.980614173228346,3.2), sharey=True)\n\nvmin = min(np.min(linSeperated_D1_Dd_counts), np.min(D1_Dd_counts))\nvmax = max(np.max(linSeperated_D1_Dd_counts), np.max(D1_Dd_counts))\n\nim1 = ax1.imshow(D1_Dd_counts , cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ Dd_bins[0], Dd_bins[-1], D1_bins[-1], D1_bins[0]], aspect = \"auto\")\nim2 = ax2.imshow(linSeperated_D1_Dd_counts, cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ Dd_bins[0], Dd_bins[-1], D1_bins[-1], D1_bins[0]], aspect = \"auto\")\n\nax1.set_xlabel(r\"$\\scriptsize \\Delta_{3}^\\textrm{X}$\")\nax1.set_ylabel(r\"$\\scriptsize \\Delta_{2}^\\textrm{X}$\")\nax2.set_xlabel(r\"$\\scriptsize \\Delta_{3}^\\textrm{X}$\")\n\n# fig.subplots_adjust(right=0.82)\n# cbar_ax = fig.add_axes([0.86, 0.15, 0.04, 0.7])\n# fig.colorbar(im1, cax=cbar_ax)\nplt.savefig(join(pathToSimFolder,f\"XOR_density2D_D1_Dd_bins_{bins}.png\"),bbox_inches=\"tight\",dpi=300) \n# plt.show()\nplt.close(fig)\n\n\n\n\n\n########################### fitness plots ###########################\nD0, D1, Dd = np.meshgrid((D0_bins[1:]+D0_bins[:-1])/2,\n (D1_bins[1:]+D1_bins[:-1])/2,\n (Dd_bins[1:]+Dd_bins[:-1])/2, indexing = \"ij\")\n\n\ndiffs = np.zeros((bins,bins,bins,2,2,2,2))\n\n\n\ndiffs[:,:,:,0,0,0,1] = Dd+(+D0-D1)/2\ndiffs[:,:,:,0,0,1,0] = Dd+(-D0-D1)/2\ndiffs[:,:,:,1,1,0,1] = Dd+(+D0+D1)/2\ndiffs[:,:,:,1,1,1,0] = Dd+(-D0+D1)/2\ndiffs[:,:,:,1,0,0,1] = D0\ndiffs[:,:,:,1,1,0,0] = D1\ndiffs[:,:,:,0,1,0,0] = -diffs[:,:,:,0,0,0,1]\ndiffs[:,:,:,1,0,0,0] = -diffs[:,:,:,0,0,1,0]\ndiffs[:,:,:,0,1,1,1] = -diffs[:,:,:,1,1,0,1]\ndiffs[:,:,:,1,0,1,1] = -diffs[:,:,:,1,1,1,0]\ndiffs[:,:,:,0,1,1,0] = -diffs[:,:,:,1,0,0,1]\ndiffs[:,:,:,0,0,1,1] = -diffs[:,:,:,1,1,0,0]\n\n\nDelta = np.max(np.abs(diffs),axis=(3,4,5,6))\n\nI_normed = np.zeros((bins,bins,bins,2,2))\n\nI_normed[:,:,:,0,0] = np.max(diffs[:,:,:,0,0,:,:],axis=(3,4))/Delta\nI_normed[:,:,:,0,1] = np.max(diffs[:,:,:,0,1,:,:],axis=(3,4))/Delta\nI_normed[:,:,:,1,0] = np.max(diffs[:,:,:,1,0,:,:],axis=(3,4))/Delta\nI_normed[:,:,:,1,1] = np.max(diffs[:,:,:,1,1,:,:],axis=(3,4))/Delta\n\n\nfitness = 1-(I_normed[:,:,:,0,0] + 1-I_normed[:,:,:,0,1] + 1-I_normed[:,:,:,1,0] + I_normed[:,:,:,1,1])/4 #XOR\n\n\n\n\n#calc probabilities\n\nprob0, prob1, probd = np.meshgrid((D0_bins[1:]-D0_bins[:-1]) * D0_counts,\n (D1_bins[1:]-D1_bins[:-1]) * D1_counts,\n (Dd_bins[1:]-Dd_bins[:-1]) * Dd_counts, indexing = \"ij\")\n\n\nD0_D1_fitness_seperated = np.sum(probd * fitness , axis = 2)\nD0_Dd_fitness_seperated = np.sum(prob1 * fitness , axis = 1)\nD1_Dd_fitness_seperated = np.sum(prob0 * fitness , axis = 0)\n\n\nD0_D1_fitness = np.histogram2d(D_10_01, D_11_00, bins = bins, weights = controlFitness)[0]/np.histogram2d(D_10_01, D_11_00, bins = bins)[0]\nD0_Dd_fitness = np.histogram2d(D_10_01, D_DIFF , bins = bins, weights = controlFitness)[0]/np.histogram2d(D_10_01, D_DIFF , bins = bins)[0]\nD1_Dd_fitness = np.histogram2d(D_11_00, D_DIFF , bins = bins, weights = controlFitness)[0]/np.histogram2d(D_11_00, D_DIFF , bins = bins)[0]\n\n\nfig, (ax1, ax2)=plt.subplots(1,2,figsize=(4.980614173228346,3.2), sharey=True)\n\nvmin = min(np.min(D0_D1_fitness_seperated), np.min(D0_D1_fitness))\nvmax = max(np.max(D0_D1_fitness_seperated), np.max(D0_D1_fitness))\n\nim1 = ax1.imshow(D0_D1_fitness , cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ D1_bins[0], D1_bins[-1], D0_bins[-1], D0_bins[0]], aspect = \"auto\")\nim2 = ax2.imshow(D0_D1_fitness_seperated, cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ D1_bins[0], D1_bins[-1], D0_bins[-1], D0_bins[0]], aspect = \"auto\")\n\nax1.set_xlabel(r\"$\\scriptsize \\Delta_{2}^\\textrm{X}$\")\nax1.set_ylabel(r\"$\\scriptsize \\Delta_{1}^\\textrm{X}$\")\nax2.set_xlabel(r\"$\\scriptsize \\Delta_{2}^\\textrm{X}$\")\n\nfig.subplots_adjust(right=0.82)\ncbar_ax = fig.add_axes([0.86, 0.15, 0.04, 0.7])\nfig.colorbar(im1, cax=cbar_ax)\nplt.savefig(join(pathToSimFolder,f\"XOR_fitness2D_D0_D1_bins_{bins}.png\"),bbox_inches=\"tight\",dpi=300) \n# plt.show()\nplt.close(fig)\n\n\n\nfig, (ax1, ax2)=plt.subplots(1,2,figsize=(4.980614173228346,3.2), sharey=True)\n\nvmin = min(np.min(D0_Dd_fitness_seperated), np.min(D0_Dd_fitness))\nvmax = max(np.max(D0_Dd_fitness_seperated), np.max(D0_Dd_fitness))\n\nim1 = ax1.imshow(D0_Dd_fitness , cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ Dd_bins[0], Dd_bins[-1], D0_bins[-1], D0_bins[0]], aspect = \"auto\")\nim2 = ax2.imshow(D0_Dd_fitness_seperated, cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ Dd_bins[0], Dd_bins[-1], D0_bins[-1], D0_bins[0]], aspect = \"auto\")\n\nax1.set_xlabel(r\"$\\scriptsize \\Delta_{3}^\\textrm{X}$\")\nax1.set_ylabel(r\"$\\scriptsize \\Delta_{1}^\\textrm{X}$\")\nax2.set_xlabel(r\"$\\scriptsize \\Delta_{3}^\\textrm{X}$\")\n\nfig.subplots_adjust(right=0.82)\ncbar_ax = fig.add_axes([0.86, 0.15, 0.04, 0.7])\nfig.colorbar(im1, cax=cbar_ax)\nplt.savefig(join(pathToSimFolder,f\"XOR_fitness2D_D0_Dd_bins_{bins}.png\"),bbox_inches=\"tight\",dpi=300) \n# plt.show()\nplt.close(fig)\n\n\n\n\nfig, (ax1, ax2)=plt.subplots(1,2,figsize=(4.980614173228346,3.2), sharey=True)\n\nvmin = min(np.min(D1_Dd_fitness_seperated), np.min(D1_Dd_fitness))\nvmax = max(np.max(D1_Dd_fitness_seperated), np.max(D1_Dd_fitness))\n\nim1 = ax1.imshow(D1_Dd_fitness , cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ Dd_bins[0], Dd_bins[-1], D1_bins[-1], D1_bins[0]], aspect = \"auto\")\nim2 = ax2.imshow(D1_Dd_fitness_seperated, cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ Dd_bins[0], Dd_bins[-1], D1_bins[-1], D1_bins[0]], aspect = \"auto\")\n\nax1.set_xlabel(r\"$\\scriptsize \\Delta_{3}^\\textrm{X}$\")\nax1.set_ylabel(r\"$\\scriptsize \\Delta_{2}^\\textrm{X}$\")\nax2.set_xlabel(r\"$\\scriptsize \\Delta_{3}^\\textrm{X}$\")\n\nfig.subplots_adjust(right=0.82)\ncbar_ax = fig.add_axes([0.86, 0.15, 0.04, 0.7])\nfig.colorbar(im1, cax=cbar_ax)\nplt.savefig(join(pathToSimFolder,f\"XOR_fitness2D_D1_Dd_bins_{bins}.png\"),bbox_inches=\"tight\",dpi=300) \n# plt.show()\nplt.close(fig)\n\n\n\nprint(\"################ AND ################\")\n\n\n\nD_00_01 = currents[:,0,0]-currents[:,0,1]\nD_01_10 = currents[:,0,1]-currents[:,1,0]\nD_DIFF = currents[:,1,1] -(currents[:,0,0]+currents[:,0,1]+currents[:,1,0])/3\n\n\nD0_counts, D0_bins = np.histogram(D_00_01, bins = bins, density = True)\nD1_counts, D1_bins = np.histogram(D_01_10, bins = bins, density = True)\nDd_counts, Dd_bins = np.histogram(D_DIFF , bins = bins, density = True)\n\n\n\nD0_D1_counts, _ , _ = np.histogram2d(D_00_01, D_01_10, bins = bins, density = True)\nD0_Dd_counts, _ , _ = np.histogram2d(D_00_01, D_DIFF, bins = bins, density = True)\nD1_Dd_counts, _ , _ = np.histogram2d(D_01_10, D_DIFF, bins = bins, density = True)\n\nlinSeperated_D0_D1_counts = np.multiply( * np.meshgrid(D0_counts, D1_counts, indexing = \"ij\"))\nlinSeperated_D0_Dd_counts = np.multiply( * np.meshgrid(D0_counts, Dd_counts, indexing = \"ij\"))\nlinSeperated_D1_Dd_counts = np.multiply( * np.meshgrid(D1_counts, Dd_counts, indexing = \"ij\"))\n\n\n\nD0_D1_counts *= (D0_bins[1]-D0_bins[0]) * (D1_bins[1]-D1_bins[0])\nlinSeperated_D0_D1_counts *= (D0_bins[1]-D0_bins[0]) * (D1_bins[1]-D1_bins[0])\nD0_Dd_counts *= (D0_bins[1]-D0_bins[0]) * (Dd_bins[1]-Dd_bins[0])\nlinSeperated_D0_Dd_counts *= (D0_bins[1]-D0_bins[0]) * (Dd_bins[1]-Dd_bins[0])\nD1_Dd_counts *= (D1_bins[1]-D1_bins[0]) * (Dd_bins[1]-Dd_bins[0])\nlinSeperated_D1_Dd_counts *= (D1_bins[1]-D1_bins[0]) * (Dd_bins[1]-Dd_bins[0])\n\n\n\n\n\n\nfig, (ax1, ax2)=plt.subplots(1,2,figsize=(4.980614173228346,3.2), sharey=True)\n\nvmin = min(np.min(linSeperated_D0_D1_counts), np.min(D0_D1_counts))\nvmax = max(np.max(linSeperated_D0_D1_counts), np.max(D0_D1_counts))\n\nim1 = ax1.imshow(D0_D1_counts , cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ D1_bins[0], D1_bins[-1], D0_bins[-1], D0_bins[0]], aspect = \"auto\")\nim2 = ax2.imshow(linSeperated_D0_D1_counts, cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ D1_bins[0], D1_bins[-1], D0_bins[-1], D0_bins[0]], aspect = \"auto\")\n\nax1.set_xlabel(r\"$\\scriptsize \\Delta_{2}^\\textrm{A}$\")\nax1.set_ylabel(r\"$\\scriptsize \\Delta_{1}^\\textrm{A}$\")\nax2.set_xlabel(r\"$\\scriptsize \\Delta_{2}^\\textrm{A}$\")\n\n# fig.subplots_adjust(right=0.82)\n# cbar_ax = fig.add_axes([0.86, 0.15, 0.04, 0.7])\n# fig.colorbar(im1, cax=cbar_ax)\nplt.savefig(join(pathToSimFolder,f\"AND_density2D_D0_D1_bins_{bins}.png\"),bbox_inches=\"tight\",dpi=300) \n# plt.show()\nplt.close(fig)\n\n\n\n\n\n\n\n\nfig, (ax1, ax2)=plt.subplots(1,2,figsize=(4.980614173228346,3.2), sharey=True)\n\nvmin = min(np.min(linSeperated_D0_Dd_counts), np.min(D0_Dd_counts))\nvmax = max(np.max(linSeperated_D0_Dd_counts), np.max(D0_Dd_counts))\n\nim1 = ax1.imshow(D0_Dd_counts , cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ Dd_bins[0], Dd_bins[-1], D0_bins[-1], D0_bins[0]], aspect = \"auto\")\nim2 = ax2.imshow(linSeperated_D0_Dd_counts, cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ Dd_bins[0], Dd_bins[-1], D0_bins[-1], D0_bins[0]], aspect = \"auto\")\n\nax1.set_xlabel(r\"$\\scriptsize \\Delta_{3}^\\textrm{A}$\")\nax1.set_ylabel(r\"$\\scriptsize \\Delta_{1}^\\textrm{A}$\")\nax2.set_xlabel(r\"$\\scriptsize \\Delta_{3}^\\textrm{A}$\")\n\n# fig.subplots_adjust(right=0.82)\n# cbar_ax = fig.add_axes([0.86, 0.15, 0.04, 0.7])\n# fig.colorbar(im1, cax=cbar_ax)\nplt.savefig(join(pathToSimFolder,f\"AND_density2D_D0_Dd_bins_{bins}.png\"),bbox_inches=\"tight\",dpi=300) \n# plt.show()\nplt.close(fig)\n\n\n\n\n\n\n\nfig, (ax1, ax2)=plt.subplots(1,2,figsize=(4.980614173228346,3.2), sharey=True)\n\nvmin = min(np.min(linSeperated_D1_Dd_counts), np.min(D1_Dd_counts))\nvmax = max(np.max(linSeperated_D1_Dd_counts), np.max(D1_Dd_counts))\n\nim1 = ax1.imshow(D1_Dd_counts , cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ Dd_bins[0], Dd_bins[-1], D1_bins[-1], D1_bins[0]], aspect = \"auto\")\nim2 = ax2.imshow(linSeperated_D1_Dd_counts, cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ Dd_bins[0], Dd_bins[-1], D1_bins[-1], D1_bins[0]], aspect = \"auto\")\n\nax1.set_xlabel(r\"$\\scriptsize \\Delta_{3}^\\textrm{A}$\")\nax1.set_ylabel(r\"$\\scriptsize \\Delta_{2}^\\textrm{A}$\")\nax2.set_xlabel(r\"$\\scriptsize \\Delta_{3}^\\textrm{A}$\")\n\n# fig.subplots_adjust(right=0.82)\n# cbar_ax = fig.add_axes([0.86, 0.15, 0.04, 0.7])\n# fig.colorbar(im1, cax=cbar_ax)\nplt.savefig(join(pathToSimFolder,f\"AND_density2D_D1_Dd_bins_{bins}.png\"),bbox_inches=\"tight\",dpi=300) \n# plt.show()\nplt.close(fig)\n\n\n\n\n\n########################### fitness plots ###########################\nD0, D1, Dd = np.meshgrid((D0_bins[1:]+D0_bins[:-1])/2,\n (D1_bins[1:]+D1_bins[:-1])/2,\n (Dd_bins[1:]+Dd_bins[:-1])/2, indexing = \"ij\")\n\n\ndiffs = np.zeros((bins,bins,bins,2,2,2,2))\n\n\n\ndiffs[:,:,:,0,0,0,1] = D0\ndiffs[:,:,:,0,0,1,0] = D0 + D1\ndiffs[:,:,:,0,0,1,1] = 1/3*D1 + 2/3*D0 - Dd\ndiffs[:,:,:,0,1,1,0] = D1\ndiffs[:,:,:,0,1,1,1] = 1/3*D1 - 1/3*D0 - Dd\ndiffs[:,:,:,1,0,1,1] =-2/3*D1 - 1/3*D0 - Dd\ndiffs[:,:,:,0,1,0,0] = -diffs[:,:,:,0,0,0,1]\ndiffs[:,:,:,1,0,0,0] = -diffs[:,:,:,0,0,1,0]\ndiffs[:,:,:,1,1,0,0] = -diffs[:,:,:,0,0,1,1]\ndiffs[:,:,:,1,0,0,1] = -diffs[:,:,:,0,1,1,0]\ndiffs[:,:,:,1,1,0,1] = -diffs[:,:,:,0,1,1,1]\ndiffs[:,:,:,1,1,1,0] = -diffs[:,:,:,1,0,1,1]\n\n\nDelta = np.max(np.abs(diffs),axis=(3,4,5,6))\n\nI_normed = np.zeros((bins,bins,bins,2,2))\n\nI_normed[:,:,:,0,0] = np.max(diffs[:,:,:,0,0,:,:],axis=(3,4))/Delta\nI_normed[:,:,:,0,1] = np.max(diffs[:,:,:,0,1,:,:],axis=(3,4))/Delta\nI_normed[:,:,:,1,0] = np.max(diffs[:,:,:,1,0,:,:],axis=(3,4))/Delta\nI_normed[:,:,:,1,1] = np.max(diffs[:,:,:,1,1,:,:],axis=(3,4))/Delta\n\n\nfitness = 1-(I_normed[:,:,:,0,0] + 1-I_normed[:,:,:,0,1] + 1-I_normed[:,:,:,1,0] + I_normed[:,:,:,1,1])/4 #XOR\n\n\n\n\n#calc probabilities\n\nprob0, prob1, probd = np.meshgrid((D0_bins[1:]-D0_bins[:-1]) * D0_counts,\n (D1_bins[1:]-D1_bins[:-1]) * D1_counts,\n (Dd_bins[1:]-Dd_bins[:-1]) * Dd_counts, indexing = \"ij\")\n\n\nD0_D1_fitness_seperated = np.sum(probd * fitness , axis = 2)\nD0_Dd_fitness_seperated = np.sum(prob1 * fitness , axis = 1)\nD1_Dd_fitness_seperated = np.sum(prob0 * fitness , axis = 0)\n\n\nD0_D1_fitness = np.histogram2d(D_00_01, D_01_10, bins = bins, weights = controlFitness)[0]/np.histogram2d(D_00_01, D_01_10, bins = bins)[0]\nD0_Dd_fitness = np.histogram2d(D_00_01, D_DIFF , bins = bins, weights = controlFitness)[0]/np.histogram2d(D_00_01, D_DIFF , bins = bins)[0]\nD1_Dd_fitness = np.histogram2d(D_01_10, D_DIFF , bins = bins, weights = controlFitness)[0]/np.histogram2d(D_01_10, D_DIFF , bins = bins)[0]\n\n\nfig, (ax1, ax2)=plt.subplots(1,2,figsize=(4.980614173228346,3.2), sharey=True)\n\nvmin = min(np.min(D0_D1_fitness_seperated), np.min(D0_D1_fitness))\nvmax = max(np.max(D0_D1_fitness_seperated), np.max(D0_D1_fitness))\n\nim1 = ax1.imshow(D0_D1_fitness , cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ D1_bins[0], D1_bins[-1], D0_bins[-1], D0_bins[0]], aspect = \"auto\")\nim2 = ax2.imshow(D0_D1_fitness_seperated, cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ D1_bins[0], D1_bins[-1], D0_bins[-1], D0_bins[0]], aspect = \"auto\")\n\nax1.set_xlabel(r\"$\\scriptsize \\Delta_{2}^\\textrm{A}$\")\nax1.set_ylabel(r\"$\\scriptsize \\Delta_{1}^\\textrm{A}$\")\nax2.set_xlabel(r\"$\\scriptsize \\Delta_{2}^\\textrm{A}$\")\n\nfig.subplots_adjust(right=0.82)\ncbar_ax = fig.add_axes([0.86, 0.15, 0.04, 0.7])\nfig.colorbar(im1, cax=cbar_ax)\nplt.savefig(join(pathToSimFolder,f\"AND_fitness2D_D0_D1_bins_{bins}.png\"),bbox_inches=\"tight\",dpi=300) \n# plt.show()\nplt.close(fig)\n\n\n\nfig, (ax1, ax2)=plt.subplots(1,2,figsize=(4.980614173228346,3.2), sharey=True)\n\nvmin = min(np.min(D0_Dd_fitness_seperated), np.min(D0_Dd_fitness))\nvmax = max(np.max(D0_Dd_fitness_seperated), np.max(D0_Dd_fitness))\n\nim1 = ax1.imshow(D0_Dd_fitness , cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ Dd_bins[0], Dd_bins[-1], D0_bins[-1], D0_bins[0]], aspect = \"auto\")\nim2 = ax2.imshow(D0_Dd_fitness_seperated, cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ Dd_bins[0], Dd_bins[-1], D0_bins[-1], D0_bins[0]], aspect = \"auto\")\n\nax1.set_xlabel(r\"$\\scriptsize \\Delta_{3}^\\textrm{A}$\")\nax1.set_ylabel(r\"$\\scriptsize \\Delta_{1}^\\textrm{A}$\")\nax2.set_xlabel(r\"$\\scriptsize \\Delta_{3}^\\textrm{A}$\")\n\nfig.subplots_adjust(right=0.82)\ncbar_ax = fig.add_axes([0.86, 0.15, 0.04, 0.7])\nfig.colorbar(im1, cax=cbar_ax)\nplt.savefig(join(pathToSimFolder,f\"AND_fitness2D_D0_Dd_bins_{bins}.png\"),bbox_inches=\"tight\",dpi=300) \n# plt.show()\nplt.close(fig)\n\n\n\n\nfig, (ax1, ax2)=plt.subplots(1,2,figsize=(4.980614173228346,3.2), sharey=True)\n\nvmin = min(np.min(D1_Dd_fitness_seperated), np.min(D1_Dd_fitness))\nvmax = max(np.max(D1_Dd_fitness_seperated), np.max(D1_Dd_fitness))\n\nim1 = ax1.imshow(D1_Dd_fitness , cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ Dd_bins[0], Dd_bins[-1], D1_bins[-1], D1_bins[0]], aspect = \"auto\")\nim2 = ax2.imshow(D1_Dd_fitness_seperated, cmap = \"gnuplot\", vmin = vmin, vmax = vmax, extent = [ Dd_bins[0], Dd_bins[-1], D1_bins[-1], D1_bins[0]], aspect = \"auto\")\n\nax1.set_xlabel(r\"$\\scriptsize \\Delta_{3}^\\textrm{A}$\")\nax1.set_ylabel(r\"$\\scriptsize \\Delta_{2}^\\textrm{A}$\")\nax2.set_xlabel(r\"$\\scriptsize \\Delta_{3}^\\textrm{A}$\")\n\nfig.subplots_adjust(right=0.82)\ncbar_ax = fig.add_axes([0.86, 0.15, 0.04, 0.7])\nfig.colorbar(im1, cax=cbar_ax)\nplt.savefig(join(pathToSimFolder,f\"AND_fitness2D_D1_Dd_bins_{bins}.png\"),bbox_inches=\"tight\",dpi=300) \n# plt.show()\nplt.close(fig)\n\n\n\"\"\"\n" ]
[ [ "numpy.sum", "numpy.histogram", "numpy.abs", "numpy.min", "numpy.linalg.inv", "numpy.linalg.eig", "numpy.meshgrid", "numpy.max", "numpy.cov", "matplotlib.pylab.subplots", "numpy.prod", "numpy.array", "numpy.zeros", "matplotlib.pylab.close", "numpy.histogram2d" ] ]
jmetzen/skgp
[ "5c5671a85d07cd1d4a66146a02327451ff992df0" ]
[ "examples/plot_gp_learning_curve.py" ]
[ "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nr\"\"\"\n==========================================================\nComparing different variants of squared exponential kernel\n==========================================================\n\nThree variants of the squared exponential covariance function are compared:\n * Isotropic squared exponential: a global length scale is learned from data.\n * Automatic relevance determination (ARD): every dimension gets its own\n characteristic length scale, irrelevant dimensions can be ignored if thetaL\n is sufficiently small.\n * Factor analysis distance (FAD): A low-rank approximation of a full\n covariance matrix for the squared exponential kernel is learned.\n Correlations between different dimensions can be identified and exploited\n to some extent.\n\nThe target function maps a 4-dimensional vector onto a real value. One of\nthe dimensions is ignored (and should thus be pruned away by ARD). The other\ndimensions are correlated, which can be exploited by FAD.\n\nThe hyperparameters are optimized within\n.. math::\n\n \\theta_i \\in [1e-4, 1e2]\n\nSee Rasmussen and Williams 2006, p107 for details regarding the different\nvariants of the squared exponential kernel.\n\n\"\"\"\nprint(__doc__)\n\n# Author: Jan Hendrik Metzen <[email protected]>\n# Licence: BSD 3 clause\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.learning_curve import learning_curve\nfrom skgp.estimators import GaussianProcess\n\nnp.random.seed(1)\n\n\ndef f(X):\n \"\"\" Target function for GPR.\n\n Note that one dimension (X[:, 3]) is irrelevant and should thus be ignored\n by ARD. Furthermore, the values x in R^3 and\n x + \\alpha (1, 2 , 0) + \\beta (1, 0, 2) have the same value for all x and\n all alpha and beta. This can be exploited by FAD.\n \"\"\"\n return np.tanh(2 * X[:, 0] - X[:, 1] - X[:, 2])\n\nXtrain = np.random.random((200, 4)) * 2 - 1\nytrain = f(Xtrain)\n\nplt.figure()\ncolors = ['r', 'g', 'b', 'c', 'm']\nlabels = {1: \"Isotropic\", 4: \"Automatic Relevance Determination\",\n 8: \"Factor Analysis\"}\nfor i, n in enumerate(labels.keys()):\n train_sizes, train_scores, test_scores = \\\n learning_curve(GaussianProcess(corr='squared_exponential',\n theta0=[1.0] * n, thetaL=[1e-4] * n,\n thetaU=[1e2] * n),\n Xtrain, ytrain, scoring=\"mean_squared_error\",\n cv=10, n_jobs=4)\n test_scores = -test_scores # Scores correspond to negative MSE\n test_scores_mean = np.mean(test_scores, axis=1)\n test_scores_min = np.min(test_scores, axis=1)\n test_scores_max = np.max(test_scores, axis=1)\n\n plt.plot(train_sizes, test_scores_mean, label=labels[n],\n color=colors[i])\n plt.fill_between(train_sizes, test_scores_min, test_scores_max,\n alpha=0.2, color=colors[i])\n\nplt.legend(loc=\"best\")\nplt.title(\"Learning Curve\")\nplt.xlabel(\"Training examples\")\nplt.ylabel(\"Mean Squared Error\")\nplt.yscale(\"symlog\", linthreshy=1e-10)\nplt.show()\n" ]
[ [ "matplotlib.pyplot.legend", "numpy.random.random", "matplotlib.pyplot.title", "numpy.random.seed", "numpy.min", "matplotlib.pyplot.yscale", "matplotlib.pyplot.plot", "numpy.max", "matplotlib.pyplot.ylabel", "numpy.mean", "matplotlib.pyplot.fill_between", "matplotlib.pyplot.xlabel", "numpy.tanh", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
Spiritdude/compas_slicer
[ "58dedfbebd123258506174453d5f73d18d745819" ]
[ "src/compas_slicer/pre_processing/preprocessing_utils/compound_target.py" ]
[ "import numpy as np\nimport math\nfrom compas.datastructures import Mesh\nimport compas_slicer.utilities as utils\nimport logging\nimport networkx as nx\nfrom compas_slicer.slicers.slice_utilities import create_graph_from_mesh_vkeys\nfrom compas_slicer.pre_processing.preprocessing_utils.geodesics import get_igl_EXACT_geodesic_distances, \\\n get_custom_HEAT_geodesic_distances\n\nimport statistics\n\nlogger = logging.getLogger('logger')\n\n__all__ = ['CompoundTarget',\n 'blend_union_list',\n 'stairs_union_list',\n 'chamfer_union_list']\n\n\nclass CompoundTarget:\n \"\"\"\n Represents a desired user-provided target. It acts as a key-frame that controls the print paths\n orientations. After the curved slicing , the print paths will be aligned to the compound target close to\n its area. The vertices that belong to the target are marked with their vertex attributes; they have\n data['v_attr'] = value.\n\n Attributes\n ----------\n mesh: :class:`compas.datastructures.Mesh`\n v_attr : str\n The key of the attribute dict to be checked.\n value: int\n The value of the attribute dict with key=v_attr. If in a vertex data[v_attr]==value then the vertex is part of\n this target.\n DATA_PATH: str\n has_blend_union: bool\n blend_radius : float\n geodesics_method: str\n 'exact_igl' exact igl geodesic distances\n 'heat' custom heat geodesic distances\n anisotropic_scaling: bool\n This is not yet implemented\n \"\"\"\n\n def __init__(self, mesh, v_attr, value, DATA_PATH, union_method='min', union_params=[],\n geodesics_method='exact_igl', anisotropic_scaling=False):\n\n logger.info('Creating target with attribute : ' + v_attr + '=%d' % value)\n logger.info('union_method : ' + union_method + ', union_params = ' + str(union_params))\n self.mesh = mesh\n self.v_attr = v_attr\n self.value = value\n self.DATA_PATH = DATA_PATH\n self.OUTPUT_PATH = utils.get_output_directory(DATA_PATH)\n\n self.union_method = union_method\n self.union_params = union_params\n\n self.geodesics_method = geodesics_method\n self.anisotropic_scaling = anisotropic_scaling # Anisotropic scaling not yet implemented\n\n self.offset = 0\n self.VN = len(list(self.mesh.vertices()))\n\n # filled in by function 'self.find_targets_connected_components()'\n self.all_target_vkeys = [] # flattened list with all vi_starts\n self.clustered_vkeys = [] # nested list with all vi_starts\n self.number_of_boundaries = None # int\n\n self.weight_max_per_cluster = []\n\n # geodesic distances\n # filled in by function 'self.update_distances_lists()'\n self._distances_lists = [] # nested list. Shape: number_of_boundaries x number_of_vertices\n self._distances_lists_flipped = [] # nested list. Shape: number_of_vertices x number_of_boundaries\n self._np_distances_lists_flipped = np.array([]) # numpy array of self._distances_lists_flipped\n self._max_dist = None # maximum get_distance value from the target on any vertex of the mesh\n\n # compute\n self.find_targets_connected_components()\n self.compute_geodesic_distances()\n\n # --- Neighborhoods clustering\n def find_targets_connected_components(self):\n \"\"\"\n Clusters all the vertices that belong to the target into neighborhoods using a graph.\n Each target can have an arbitrary number of neighborhoods/clusters.\n Fills in the attributes: self.all_target_vkeys, self.clustered_vkeys, self.number_of_boundaries\n \"\"\"\n self.all_target_vkeys = [vkey for vkey, data in self.mesh.vertices(data=True) if\n data[self.v_attr] == self.value]\n assert len(self.all_target_vkeys) > 0, \"There are no vertices in the mesh with the attribute : \" \\\n + self.v_attr + \", value : %d\" % self.value + \" .Probably you made a \" \\\n \"mistake while creating the targets. \"\n G = create_graph_from_mesh_vkeys(self.mesh, self.all_target_vkeys)\n assert len(list(G.nodes())) == len(self.all_target_vkeys)\n self.number_of_boundaries = len(list(nx.connected_components(G)))\n\n for i, cp in enumerate(nx.connected_components(G)):\n self.clustered_vkeys.append(list(cp))\n logger.info(\"Compound target with 'boundary'=%d. Number of connected_components : %d\" % (\n self.value, len(list(nx.connected_components(G)))))\n\n # --- Geodesic distances\n def compute_geodesic_distances(self):\n \"\"\"\n Computes the geodesic distances from each of the target's neighborhoods to all the mesh vertices.\n Fills in the distances attributes.\n \"\"\"\n if self.geodesics_method == 'exact_igl':\n distances_lists = [get_igl_EXACT_geodesic_distances(self.mesh, vstarts) for vstarts in\n self.clustered_vkeys]\n elif self.geodesics_method == 'heat':\n distances_lists = [get_custom_HEAT_geodesic_distances(self.mesh, vstarts, self.OUTPUT_PATH) for vstarts in\n self.clustered_vkeys]\n else:\n raise ValueError('Unknown geodesics method : ' + self.geodesics_method)\n\n distances_lists = [list(dl) for dl in distances_lists] # number_of_boundaries x #V\n self.update_distances_lists(distances_lists)\n\n def update_distances_lists(self, distances_lists):\n \"\"\"\n Fills in the distances attributes.\n \"\"\"\n self._distances_lists = distances_lists\n self._distances_lists_flipped = [] # empty\n for i in range(self.VN):\n current_values = [self._distances_lists[list_index][i] for list_index in range(self.number_of_boundaries)]\n self._distances_lists_flipped.append(current_values)\n self._np_distances_lists_flipped = np.array(self._distances_lists_flipped)\n self._max_dist = np.max(self._np_distances_lists_flipped)\n\n # --- Uneven weights\n @property\n def has_uneven_weights(self):\n \"\"\" Returns True if the target has uneven_weights calculated, False otherwise. \"\"\"\n return len(self.weight_max_per_cluster) > 0\n\n def compute_uneven_boundaries_weight_max(self, other_target):\n \"\"\"\n If the target has multiple neighborhoods/clusters of vertices, then it computes their maximum distance from\n the other_target. Based on that it calculates their weight_max for the interpolation process\n \"\"\"\n if self.number_of_boundaries > 1:\n ds_avg_HIGH = self.get_boundaries_rel_dist_from_other_target(other_target)\n max_param = max(ds_avg_HIGH)\n for i, d in enumerate(ds_avg_HIGH): # offset all distances except the maximum one\n if abs(d - max_param) > 0.01: # if it isn't the max value\n ds_avg_HIGH[i] = d + self.offset\n\n self.weight_max_per_cluster = [d / max_param for d in ds_avg_HIGH]\n logger.info('weight_max_per_cluster : ' + str(self.weight_max_per_cluster))\n else:\n logger.info(\"Did not compute_norm_of_gradient uneven boundaries, target consists of single component\")\n\n # --- Relation to other target\n def get_boundaries_rel_dist_from_other_target(self, other_target, avg_type='median'):\n \"\"\"\n Returns a list, one relative distance value per connected boundary neighborhood.\n That is the average of the distances of the vertices of that boundary neighborhood from the other_target.\n \"\"\"\n distances = []\n for vi_starts in self.clustered_vkeys:\n ds = [other_target.get_distance(vi) for vi in vi_starts]\n if avg_type == 'mean':\n distances.append(statistics.mean(ds))\n else: # 'median'\n distances.append(statistics.median(ds))\n return distances\n\n def get_avg_distances_from_other_target(self, other_target):\n \"\"\"\n Returns the minimum and maximum distance of the vertices of this target from the other_target\n \"\"\"\n extreme_distances = []\n for v_index in other_target.all_target_vkeys:\n extreme_distances.append(self.get_all_distances()[v_index])\n return np.average(np.array(extreme_distances))\n\n #############################\n # --- get all distances\n\n # All distances\n def get_all_distances(self):\n \"\"\" Returns the resulting distances per every vertex. \"\"\"\n return [self.get_distance(i) for i in range(self.VN)]\n\n def get_all_clusters_distances_dict(self):\n \"\"\" Returns dict. keys: index of connected target neighborhood, value: list, distances (one per vertex). \"\"\"\n return {i: self._distances_lists[i] for i in range(self.number_of_boundaries)}\n\n def get_max_dist(self):\n \"\"\" Returns the maximum distance that the target has on a mesh vertex. \"\"\"\n return self._max_dist\n\n #############################\n # --- per vkey distances\n\n def get_all_distances_for_vkey(self, i):\n \"\"\" Returns distances from each cluster separately for vertex i. Smooth union doesn't play here any role. \"\"\"\n return [self._distances_lists[list_index][i] for list_index in range(self.number_of_boundaries)]\n\n def get_distance(self, i):\n \"\"\" Return get_distance for vertex with vkey i. \"\"\"\n if self.union_method == 'min':\n # --- simple union\n return np.min(self._np_distances_lists_flipped[i])\n elif self.union_method == 'smooth':\n # --- blend (smooth) union\n return blend_union_list(values=self._np_distances_lists_flipped[i], r=self.union_params[0])\n elif self.union_method == 'chamfer':\n # --- blend (smooth) union\n return chamfer_union_list(values=self._np_distances_lists_flipped[i], r=self.union_params[0])\n elif self.union_method == 'stairs':\n # --- stairs union\n return stairs_union_list(values=self._np_distances_lists_flipped[i], r=self.union_params[0],\n n=self.union_params[1])\n else:\n raise ValueError(\"Unknown Union method : \", self.union_method)\n\n #############################\n # --- scalar field smoothing\n\n def laplacian_smoothing(self, iterations, strength):\n \"\"\" Smooth the distances on the mesh, using iterative laplacian smoothing. \"\"\"\n L = utils.get_mesh_cotmatrix_igl(self.mesh, fix_boundaries=True)\n new_distances_lists = []\n\n logger.info('Laplacian smoothing of all distances')\n for i, a in enumerate(self._distances_lists):\n a = np.array(a) # a: numpy array containing the attribute to be smoothed\n for _ in range(iterations): # iterative smoothing\n a_prime = a + strength * L * a\n a = a_prime\n new_distances_lists.append(list(a))\n self.update_distances_lists(new_distances_lists)\n\n #############################\n # ------ output\n def save_distances(self, name):\n \"\"\"\n Save distances to json.\n Saves one list with distance values (one per vertex).\n\n Parameters\n ----------\n name: str, name of json to be saved\n \"\"\"\n utils.save_to_json(self.get_all_distances(), self.OUTPUT_PATH, name)\n\n # ------ assign new Mesh\n def assign_new_mesh(self, mesh):\n \"\"\" When the base mesh changes, a new mesh needs to be assigned. \"\"\"\n mesh.to_json(self.OUTPUT_PATH + \"/temp.obj\")\n mesh = Mesh.from_json(self.OUTPUT_PATH + \"/temp.obj\")\n self.mesh = mesh\n self.VN = len(list(self.mesh.vertices()))\n\n\n####################\n# unions on lists\n\ndef blend_union_list(values, r):\n \"\"\" Returns a smooth union of all the elements in the list, with blend radius blend_radius. \"\"\"\n d_result = 9999999 # very big number\n for d in values:\n d_result = blend_union(d_result, d, r)\n return d_result\n\n\ndef stairs_union_list(values, r, n):\n \"\"\" Returns a stairs union of all the elements in the list, with blend radius r and number of peaks n-1.\"\"\"\n d_result = 9999999 # very big number\n for i, d in enumerate(values):\n d_result = stairs_union(d_result, d, r, n)\n return d_result\n\n\ndef chamfer_union_list(values, r):\n d_result = 9999999 # very big number\n for i, d in enumerate(values):\n d_result = chamfer_union(d_result, d, r)\n return d_result\n\n\n####################\n# unions on pairs\n\ndef blend_union(da, db, r):\n \"\"\" Returns a smooth union of the two elements da, db with blend radius blend_radius. \"\"\"\n e = max(r - abs(da - db), 0)\n return min(da, db) - e * e * 0.25 / r\n\n\ndef chamfer_union(a, b, r):\n \"\"\" Returns a chamfer union of the two elements da, db with radius r. \"\"\"\n return min(min(a, b), (a - r + b) * math.sqrt(0.5))\n\n\ndef stairs_union(a, b, r, n):\n \"\"\" Returns a stairs union of the two elements da, db with radius r. \"\"\"\n s = r / n\n u = b - r\n return min(min(a, b), 0.5 * (u + a + abs((u - a + s) % (2 * s) - s)))\n\n\nif __name__ == \"__main__\":\n pass\n" ]
[ [ "numpy.max", "numpy.array", "numpy.min" ] ]
Orthocenter/Real-time-GesRec
[ "81803a59a5d58e271e7b80cd193d51ab0088ec7d" ]
[ "datasets/jester.py" ]
[ "import torch\nimport torch.utils.data as data\nfrom PIL import Image\nfrom spatial_transforms import *\nimport os\nimport math\nimport functools\nimport json\nimport copy\nfrom numpy.random import randint\nimport numpy as np\nimport random\n\nfrom utils import load_value_file\n\n\ndef pil_loader(path, modality):\n # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)\n with open(path, 'rb') as f:\n #print(path)\n with Image.open(f) as img:\n if modality == 'RGB':\n return img.convert('RGB')\n elif modality == 'Flow':\n return img.convert('L')\n\n\ndef accimage_loader(path, modality):\n try:\n import accimage\n return accimage.Image(path)\n except IOError:\n # Potentially a decoding problem, fall back to PIL.Image\n return pil_loader(path)\n\n\ndef get_default_image_loader():\n from torchvision import get_image_backend\n if get_image_backend() == 'accimage':\n return accimage_loader\n else:\n return pil_loader\n\n\ndef video_loader(video_dir_path, frame_indices, modality, sample_duration, image_loader):\n \n video = []\n\n if modality == 'RGB':\n for i in frame_indices:\n image_path = os.path.join(video_dir_path, '{:05d}.jpg'.format(i))\n if os.path.exists(image_path):\n video.append(image_loader(image_path, modality))\n else:\n print(image_path, \"------- Does not exist\")\n return video\n return video\n\n\ndef get_default_video_loader():\n image_loader = get_default_image_loader()\n return functools.partial(video_loader, image_loader=image_loader)\n\n\ndef load_annotation_data(data_file_path):\n with open(data_file_path, 'r') as data_file:\n return json.load(data_file)\n\n\ndef get_class_labels(data):\n class_labels_map = {}\n index = 0\n for class_label in data['labels']:\n class_labels_map[class_label] = index\n index += 1\n return class_labels_map\n\n\ndef get_video_names_and_annotations(data, subset):\n video_names = []\n annotations = []\n\n for key, value in data['database'].items():\n this_subset = value['subset']\n if this_subset == subset:\n label = value['annotations']['label']\n #video_names.append('{}/{}'.format(label, key))\n video_names.append(key)\n annotations.append(value['annotations'])\n\n return video_names, annotations\n\n\ndef make_dataset(root_path, annotation_path, subset, n_samples_for_each_video,\n sample_duration):\n data = load_annotation_data(annotation_path)\n video_names, annotations = get_video_names_and_annotations(data, subset)\n class_to_idx = get_class_labels(data)\n idx_to_class = {}\n for name, label in class_to_idx.items():\n idx_to_class[label] = name\n\n dataset = []\n print(\"[INFO]: Jester Dataset - \" + subset + \" is loading...\")\n for i in range(len(video_names)):\n if i % 1000 == 0:\n print('dataset loading [{}/{}]'.format(i, len(video_names)))\n\n video_path = os.path.join(root_path, video_names[i])\n \n if not os.path.exists(video_path):\n continue\n\n n_frames_file_path = os.path.join(video_path, 'n_frames')\n n_frames = int(load_value_file(n_frames_file_path))\n if n_frames <= 0:\n continue\n\n begin_t = 1\n end_t = n_frames\n sample = {\n 'video': video_path,\n 'segment': [begin_t, end_t],\n 'n_frames': n_frames,\n #'video_id': video_names[i].split('/')[1]\n 'video_id': video_names[i]\n }\n if len(annotations) != 0:\n sample['label'] = class_to_idx[annotations[i]['label']]\n else:\n sample['label'] = -1\n\n if n_samples_for_each_video == 1:\n sample['frame_indices'] = list(range(1, n_frames + 1))\n dataset.append(sample)\n else:\n if n_samples_for_each_video > 1:\n step = max(1,\n math.ceil((n_frames - 1 - sample_duration) /\n (n_samples_for_each_video - 1)))\n else:\n step = sample_duration\n for j in range(1, n_frames, step):\n sample_j = copy.deepcopy(sample)\n sample_j['frame_indices'] = list(\n range(j, min(n_frames + 1, j + sample_duration)))\n dataset.append(sample_j)\n\n return dataset, idx_to_class\n\n\n\n\nclass Jester(data.Dataset):\n \"\"\"\n Args:\n root (string): Root directory path.\n spatial_transform (callable, optional): A function/transform that takes in an PIL image\n and returns a transformed version. E.g, ``transforms.RandomCrop``\n temporal_transform (callable, optional): A function/transform that takes in a list of frame indices\n and returns a transformed version\n target_transform (callable, optional): A function/transform that takes in the\n target and transforms it.\n loader (callable, optional): A function to load an video given its path and frame indices.\n Attributes:\n classes (list): List of the class names.\n class_to_idx (dict): Dict with items (class_name, class_index).\n imgs (list): List of (image path, class_index) tuples\n \"\"\"\n\n def __init__(self,\n root_path,\n annotation_path,\n subset,\n n_samples_for_each_video=1,\n spatial_transform=None,\n temporal_transform=None,\n target_transform=None,\n sample_duration=16,\n modality='RGB',\n get_loader=get_default_video_loader):\n self.data, self.class_names = make_dataset(\n root_path, annotation_path, subset, n_samples_for_each_video,\n sample_duration)\n\n self.spatial_transform = spatial_transform\n self.temporal_transform = temporal_transform\n self.target_transform = target_transform\n self.modality = modality\n self.sample_duration = sample_duration\n self.loader = get_loader()\n\n def __getitem__(self, index):\n \"\"\"\n Args:\n index (int): Index\n Returns:\n tuple: (image, target) where target is class_index of the target class.\n \"\"\"\n path = self.data[index]['video']\n\n frame_indices = self.data[index]['frame_indices']\n if self.temporal_transform is not None:\n frame_indices = self.temporal_transform(frame_indices)\n clip = self.loader(path, frame_indices, self.modality, self.sample_duration)\n\n oversample_clip =[]\n if self.spatial_transform is not None:\n self.spatial_transform.randomize_parameters()\n clip = [self.spatial_transform(img) for img in clip]\n \n im_dim = clip[0].size()[-2:]\n clip = torch.cat(clip, 0).view((self.sample_duration, -1) + im_dim).permute(1, 0, 2, 3)\n \n\n target = self.data[index]\n if self.target_transform is not None:\n target = self.target_transform(target)\n\n \n return clip, target\n\n def __len__(self):\n return len(self.data)\n\n\n" ]
[ [ "torch.cat" ] ]
esw0116/Super-SloMo
[ "876f0f61b8365306cdadcde976c2ddc6a8e20bf8" ]
[ "save_deblurred_result.py" ]
[ "\n#[Super SloMo]\n##High Quality Estimation of Multiple Intermediate Frames for Video Interpolation\n\nimport argparse\n\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.optim as optim\nimport torch.nn as nn\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom model.extraction import center, ends, MPRNet\nfrom data import gopro_center\nfrom data import red_half as red\nimport dataloader\nfrom utils import meanshift\n\nfrom copy import deepcopy\nimport datetime\nimport os, sys\nimport numpy as np\nimport tqdm\n\n\n# For parsing commandline arguments\nparser = argparse.ArgumentParser()\nparser.add_argument('--dataset', type=str, required=True, choices=['gopro', 'reds'], help='datasets')\nparser.add_argument('--phase', type=str, required=True, choices=['train', 'test'], help='datasets')\nparser.add_argument(\"--dataset_root\", type=str, default='dataset', help='path to dataset folder containing train-test-validation folders')\nparser.add_argument(\"--extract\", type=str, help='Add blurry image')\nparser.add_argument(\"--seq_len\", type=int, default=11, help='number of frames that composes a sequence.')\nparser.add_argument(\"--train_batch_size\", type=int, default=8, help='batch size for training. Default: 6.')\nparser.add_argument(\"--validation_batch_size\", type=int, default=1, help='batch size for validation. Default: 10.')\n\nargs = parser.parse_args()\n\n###Initialize flow computation and arbitrary-time flow interpolation CNNs.\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n### Load Pretrained Extraction Models\n\n# center_estimation = center.Center()\ncenter_estimation = MPRNet.MPRNet()\npretrained_weight = torch.load(args.extract)['state_dict']\nprint('Estimation Network: {}'.format(args.extract))\n\ncenter_state_dict = {}\nends_state_dict = {}\nfor key, value in pretrained_weight.items():\n if key.startswith('center_est.'):\n center_state_dict[key[11:]] = value\n elif key.startswith('gen.'):\n ends_state_dict[key[4:]] = value\ncenter_estimation.load_state_dict(center_state_dict)\ncenter_estimation = center_estimation.to(device)\n\nmean = [0.429, 0.431, 0.397]\nstd = [1, 1, 1]\n\ntransform = transforms.ToTensor()\n# GoPro\nif args.dataset == 'gopro':\n dataset_name = 'GoPro'\n is_train = True if args.phase == 'train' else False\n validationset = gopro_center.GoPro(root=args.dataset_root, transform=transform, randomCropSize=(1280, 720), seq_len=args.seq_len, train=is_train)\nelif args.dataset == 'reds':\n dataset_name = 'REDS120fps'\n validationset = red.RedBase(root=args.dataset_root, transform=transform, randomCropSize=(1280, 720), seq_len=args.seq_len, train=False)\nvalidationloader = torch.utils.data.DataLoader(validationset, batch_size=args.validation_batch_size, shuffle=False)\n\nprint(validationset)\n\n###Loss and Optimizer\n\nseq_len = args.seq_len\nctr_idx = seq_len // 2\n\ndef test():\n tqdm_loader = tqdm.tqdm(validationloader, ncols=80)\n\n imgsave_folder = os.path.join('dataset/MPRNet_Result', dataset_name+'{:02d}'.format(seq_len), args.phase)\n if not os.path.exists(imgsave_folder):\n os.makedirs(imgsave_folder)\n\n with torch.no_grad():\n for idx, (validationData, _, validationFile) in enumerate(tqdm_loader):\n if args.dataset == 'reds':\n if seq_len == 5:\n blurred_img = validationData[-1].to(device)\n validationData = validationData[:-1]\n else:\n validationData = validationData[:-1]\n blurred_img = torch.zeros_like(validationData[0])\n for image in validationData:\n blurred_img += image\n blurred_img /= len(validationData)\n blurred_img = blurred_img.to(device)\n else:\n blurred_img = torch.zeros_like(validationData[0])\n for image in validationData:\n blurred_img += image\n blurred_img /= len(validationData)\n blurred_img = blurred_img.to(device)\n\n batch_size = blurred_img.shape[0]\n\n blurred_img = meanshift(blurred_img, mean, std, device, False)\n center = center_estimation(blurred_img)\n \n out_img = center.cpu().clone()\n foldername = os.path.basename(os.path.dirname(validationFile[ctr_idx][0]))\n if not os.path.exists(os.path.join(imgsave_folder, foldername)):\n os.makedirs(os.path.join(imgsave_folder, foldername))\n filename = os.path.splitext(os.path.basename(validationFile[ctr_idx][0]))[0] + '.png'\n\n\n torchvision.utils.save_image(out_img[0], os.path.join(imgsave_folder, foldername, filename))\n\n\nprint(\"Test Start\")\ntest()\nprint(\"Test End\")\nsys.exit(0)\n" ]
[ [ "torch.load", "torch.zeros_like", "torch.utils.data.DataLoader", "torch.no_grad", "torch.cuda.is_available" ] ]
yxtj/henn
[ "5093f3e637ba0bb3e48c4f890b3b469c3617f2c5" ]
[ "heutil.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 4 18:43:10 2022\n\n@author: yanxi\n\"\"\"\nfrom hesign import sign\nimport numpy as np\n\n#%% sum\n\ndef sum_list(x):\n n = len(x)\n if n > 2:\n return sum_list(x[:n//2]) + sum_list(x[n//2:])\n else:\n return sum(x)\n \n\ndef avg_list(x):\n n = len(x)\n f = 1.0/n\n return sum_list(x) * f\n\n\ndef var_list(x, mean=None):\n y = x*x\n m2 = sum_list(y)\n if mean is None:\n mean = avg_list(x)\n return m2 - mean*mean\n\n\n# %% dot product\n\ndef dot_product(a, b):\n if a.ndim == 1:\n if b.ndim == 1:\n return dot_product_11(a,b)\n else:\n return dot_product_12(a, b)\n else:\n if b.ndim == 1:\n return dot_product_21(a,b)\n else:\n return dot_product_22(a, b)\n\ndef dot_product_11(w, x):\n assert x.ndim == w.ndim == 1\n assert len(x) == len(w)\n y = x*w\n return sum_list(y)\n\ndef dot_product_21(m, x):\n assert m.ndim == 2\n assert x.ndim == 1\n assert m.shape[1] == len(x)\n out = np.array([ dot_product_11(m[i], x) for i in range(m.shape[0]) ])\n return out\n\ndef dot_product_12(x, m):\n assert x.ndim == 1\n assert m.ndim == 2\n assert len(x) == m.shape[0]\n out = np.array([ dot_product_11(x, m[:,i]) for i in range(m.shape[1]) ])\n return out\n\ndef dot_product_22(a, b):\n assert a.ndim == 2\n assert b.ndim == 2\n assert a.shape[1] == b.shape[0]\n out = np.empty((a.shape[0], b.shape[1]), dtype=a.dtype)\n for i in range(a.shape[0]):\n for j in range(b.shape[1]):\n out[i,j] = dot_product_11(a[i], b[:,j])\n return out\n\n# %% max with polynomial approximation\n\ndef max(a, b, alpha=7, quick=False):\n x = a+b\n y = a-b\n s = sign(y)\n return ( x + s*y) / 2\n\ndef max_list(x, alpha=7, quick=False):\n n = len(x)\n if n == 1:\n return x[0]\n elif n == 2:\n return max(x[0], x[1], alpha, quick)\n else:\n p = n//2\n return max(max_list(x[:p], alpha, quick),\n max_list(x[p:], alpha, quick),\n alpha, quick)\n\n# %% univariate functions\n\ndef relu(x, alpha=7, quick=False):\n '''\n ReLU approximation using HE-sign function (polynomial approximation)\n '''\n return ( x + sign(x)*x) / 2\n\n\ndef sqrt(x):\n '''\n Square root approximation with polynonimal approximation\n 1 + (x-1)/2 - (x-1)**2/8 + (x-1)**3/16 - (x-1)**4*(5/128) + ...\n '''\n t = x-1\n return 1 + t/2 - t*t/8\n " ]
[ [ "numpy.empty" ] ]
Roasted-Ice/StegaStamp
[ "955426381b7d8be055532d225df8070423d5eac7" ]
[ "detector.py" ]
[ "import os,time,cv2, sys, math\nimport bchlib\nimport tensorflow as tf\nimport argparse\nimport numpy as np\nfrom tensorflow.python.saved_model import tag_constants\nfrom tensorflow.python.saved_model import signature_constants\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--detector_model', type=str, required=True)\nparser.add_argument('--decoder_model', type=str, required=True)\nparser.add_argument('--video', type=str, required=True)\nparser.add_argument('--secret_size', type=int, default=100)\nparser.add_argument('--save_video', type=str, default=None)\nparser.add_argument('--visualize_detector', action='store_true', help='Visualize detector mask output')\nargs = parser.parse_args()\n\nBCH_POLYNOMIAL = 137\nBCH_BITS = 5\n\ndef get_intersect(p1, p2, p3, p4):\n s = np.vstack([p1,p2,p3,p4])\n h = np.hstack((s, np.ones((4, 1))))\n l1 = np.cross(h[0], h[1])\n l2 = np.cross(h[2], h[3])\n x, y, z = np.cross(l1, l2)\n if z == 0:\n print('invalid')\n return (0,0)\n return (x/z, y/z)\n\ndef poly_area(poly):\n return 0.5*np.abs(np.dot(poly[:,0],np.roll(poly[:,1],1))-np.dot(poly[:,1],np.roll(poly[:,0],1)))\n\ndef order_points(pts):\n rect = np.zeros((4, 2), dtype=np.float32)\n s = pts.sum(axis=1)\n rect[0] = pts[np.argmin(s)]\n rect[2] = pts[np.argmax(s)]\n\n diff = np.diff(pts, axis = 1)\n rect[1] = pts[np.argmin(diff)]\n rect[3] = pts[np.argmax(diff)]\n return rect\n\ndef main():\n # Initializing network\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n detector_graph = tf.Graph()\n decoder_graph = tf.Graph()\n\n with detector_graph.as_default():\n detector_sess = tf.Session()\n detector_model = tf.saved_model.loader.load(detector_sess, [tag_constants.SERVING], args.detector_model)\n\n detector_input_name = detector_model.signature_def[signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY].inputs['image'].name\n detector_input = detector_graph.get_tensor_by_name(detector_input_name)\n\n detector_output_name = detector_model.signature_def[signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY].outputs['detections'].name\n detector_output = detector_graph.get_tensor_by_name(detector_output_name)\n\n with decoder_graph.as_default():\n decoder_sess = tf.Session()\n decoder_model = tf.saved_model.loader.load(decoder_sess, [tag_constants.SERVING], args.decoder_model)\n\n decoder_input_name = decoder_model.signature_def[signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY].inputs['image'].name\n decoder_input = decoder_graph.get_tensor_by_name(decoder_input_name)\n\n decoder_output_name = decoder_model.signature_def[signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY].outputs['decoded'].name\n decoder_output = decoder_graph.get_tensor_by_name(decoder_output_name)\n\n cap = cv2.VideoCapture(args.video)\n bch = bchlib.BCH(BCH_POLYNOMIAL, BCH_BITS)\n\n ret, frame = cap.read()\n f_height, f_width = frame.shape[0:2]\n\n if args.save_video is not None:\n fourcc1 = cv2.VideoWriter_fourcc(*'XVID')\n out = cv2.VideoWriter(args.save_video, fourcc1, 30.0, (f_width, f_height))\n\n while(True):\n ret, frame = cap.read()\n if frame is None:\n break\n frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n\n detector_image_input = cv2.resize(frame_rgb, (1024,1024))\n detector_image_input = np.expand_dims(np.float32(detector_image_input),axis=0)/255.0\n\n output_image = detector_sess.run(detector_output,feed_dict={detector_input:detector_image_input})\n output_image = np.array(output_image[0,:,:,:])\n output_image = x = np.argmax(output_image, axis = -1)\n\n color_codes = np.array([[255,255,255],[0,0,0]])\n out_vis_image = color_codes[output_image.astype(int)]\n\n mask_im = cv2.resize(np.float32(out_vis_image), (f_width,f_height))\n if args.visualize_detector:\n mask_vis = mask_im.astype(np.uint8)\n\n contours, _ = cv2.findContours(cv2.cvtColor(mask_im, cv2.COLOR_BGR2GRAY).astype(np.uint8),1,2)\n extrema = np.zeros((8,2))\n corners = np.zeros((4,2))\n for cnt in contours:\n area = cv2.contourArea(cnt)\n if area < 1000:\n continue\n\n hull = cv2.convexHull(cnt)\n if len(hull) < 4:\n continue\n\n if args.visualize_detector:\n cv2.polylines(mask_vis, np.int32([corners]), thickness=6, color=(100,100,250), isClosed=True)\n\n extrema[0,:] = hull[np.argmax(hull[:,0,0]),0,:]\n extrema[1,:] = hull[np.argmax(hull[:,0,0]+hull[:,0,1]),0,:]\n extrema[2,:] = hull[np.argmax(hull[:,0,1]),0,:]\n extrema[3,:] = hull[np.argmax(-hull[:,0,0]+hull[:,0,1]),0,:]\n extrema[4,:] = hull[np.argmax(-hull[:,0,0]),0,:]\n extrema[5,:] = hull[np.argmax(-hull[:,0,0]-hull[:,0,1]),0,:]\n extrema[6,:] = hull[np.argmax(-hull[:,0,1]),0,:]\n extrema[7,:] = hull[np.argmax(hull[:,0,0]-hull[:,0,1]),0,:]\n\n extrema_lines = extrema - np.roll(extrema, shift=1, axis=0)\n extrema_len = extrema_lines[:,0]**2 + extrema_lines[:,1]**2\n line_idx = np.sort(extrema_len.argsort()[-4:])\n for c in range(4):\n p1 = extrema[line_idx[(c-1)%4],:]\n p2 = extrema[(line_idx[(c-1)%4]-1)%8,:]\n p3 = extrema[line_idx[c],:]\n p4 = extrema[(line_idx[c]-1)%8,:]\n corners[c,:] = get_intersect(p1, p2, p3, p4)\n\n new_area = poly_area(corners)\n if new_area / area > 1.5:\n continue\n\n corners = order_points(corners)\n corners_full_res = corners\n\n pts_dst = np.array([[0,0],[399,0],[399,399],[0,399]])\n h, status = cv2.findHomography(corners_full_res, pts_dst)\n try:\n warped_im = cv2.warpPerspective(frame_rgb, h, (400,400))\n w_im = warped_im.astype(np.float32)\n w_im /= 255.\n except:\n continue\n\n for im_rotation in range(4):\n w_rotated = np.rot90(w_im, im_rotation)\n recovered_secret = decoder_sess.run([decoder_output],feed_dict={decoder_input:[w_rotated]})[0][0]\n recovered_secret = list(recovered_secret)\n recovered_secret = [int(i) for i in recovered_secret]\n\n packet_binary = \"\".join([str(bit) for bit in recovered_secret[:96]])\n footer = recovered_secret[96:]\n if np.sum(footer) > 0:\n continue\n packet = bytes(int(packet_binary[i : i + 8], 2) for i in range(0, len(packet_binary), 8))\n packet = bytearray(packet)\n\n data, ecc = packet[:-bch.ecc_bytes], packet[-bch.ecc_bytes:]\n\n bitflips = bch.decode_inplace(data, ecc)\n\n if bitflips != -1:\n print('Num bits corrected: ', bitflips)\n try:\n code = data.decode(\"utf-8\")\n except:\n continue\n color = (100,250,100)\n cv2.polylines(frame, np.int32([corners]), thickness=6, color=color, isClosed=True)\n font = cv2.FONT_HERSHEY_SIMPLEX\n im = cv2.putText(frame, code, tuple((corners[0,:]+np.array([0,-15])).astype(np.int)), font, 1,(0,0,0), 2, cv2.LINE_AA)\n\n if args.save_video is not None:\n out.write(frame)\n else:\n cv2.imshow('frame',frame)\n if args.visualize_detector:\n cv2.imshow('detector_mask', mask_vis)\n cv2.waitKey(1)\n\n cap.release()\n if args.save_video:\n out.release()\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.rot90", "tensorflow.Graph", "numpy.sum", "numpy.int32", "numpy.ones", "tensorflow.ConfigProto", "numpy.argmax", "numpy.diff", "numpy.argmin", "tensorflow.Session", "numpy.cross", "numpy.float32", "numpy.roll", "numpy.array", "numpy.zeros", "tensorflow.saved_model.loader.load", "numpy.vstack" ] ]
Res260/rlcard
[ "c0fc9fe70c4ec1c726e5e66b62866086491f5dbf" ]
[ "examples/uno_dqn.py" ]
[ "''' An example of learning a Deep-Q Agent on Dou Dizhu\n'''\n\nimport tensorflow as tf\n\nimport rlcard\nfrom rlcard.agents.dqn_agent import DQNAgent\nfrom rlcard.agents.random_agent import RandomAgent\nfrom rlcard.utils.utils import set_global_seed\nfrom rlcard.utils.logger import Logger\n\n# Make environment\nenv = rlcard.make('uno')\neval_env = rlcard.make('uno')\n\n# Set the iterations numbers and how frequently we evaluate/save plot\nevaluate_every = 100\nsave_plot_every = 1000\nevaluate_num = 10000\nepisode_num = 1000000\n\n# Set the the number of steps for collecting normalization statistics\n# and intial memory size\nmemory_init_size = 1000\nnorm_step = 1000\n\n# The paths for saving the logs and learning curves\nroot_path = './experiments/uno_dqn_result/'\nlog_path = root_path + 'log.txt'\ncsv_path = root_path + 'performance.csv'\nfigure_path = root_path + 'figures/'\n\n# Set a global seed\nset_global_seed(0)\n\nwith tf.Session() as sess:\n # Set agents\n global_step = tf.Variable(0, name='global_step', trainable=False)\n agent = DQNAgent(sess,\n scope='dqn',\n action_num=env.action_num,\n replay_memory_size=20000,\n replay_memory_init_size=memory_init_size,\n norm_step=norm_step,\n state_shape=env.state_shape,\n mlp_layers=[512, 512])\n\n random_agent = RandomAgent(action_num=eval_env.action_num)\n\n sess.run(tf.global_variables_initializer())\n\n env.set_agents([agent, random_agent, random_agent])\n eval_env.set_agents([agent, random_agent, random_agent])\n\n # Count the number of steps\n step_counter = 0\n\n # Init a Logger to plot the learning curve\n logger = Logger(xlabel='timestep', ylabel='reward', legend='DQN on UNO', log_path=log_path, csv_path=csv_path)\n\n for episode in range(episode_num):\n\n # Generate data from the environment\n trajectories, _ = env.run(is_training=True)\n\n # Feed transitions into agent memory, and train the agent\n for ts in trajectories[0]:\n agent.feed(ts)\n step_counter += 1\n\n # Train the agent\n train_count = step_counter - (memory_init_size + norm_step)\n if train_count > 0:\n loss = agent.train()\n print('\\rINFO - Step {}, loss: {}'.format(step_counter, loss), end='')\n\n # Evaluate the performance. Play with random agents.\n if episode % evaluate_every == 0:\n reward = 0\n for eval_episode in range(evaluate_num):\n _, payoffs = eval_env.run(is_training=False)\n reward += payoffs[0]\n\n logger.log('\\n########## Evaluation ##########')\n logger.log('Timestep: {} Average reward is {}'.format(env.timestep, float(reward)/evaluate_num))\n\n # Add point to logger\n logger.add_point(x=env.timestep, y=float(reward)/evaluate_num)\n\n # Make plot\n if episode % save_plot_every == 0 and episode > 0:\n logger.make_plot(save_path=figure_path+str(episode)+'.png')\n\n # Make the final plot\n logger.make_plot(save_path=figure_path+'final_'+str(episode)+'.png')\n" ]
[ [ "tensorflow.Variable", "tensorflow.global_variables_initializer", "tensorflow.Session" ] ]
Sangeerththan/pythonDSA
[ "d126b3a7a8acc1e202107e20a21ed96fb4ab144e" ]
[ "Algorithms/DynamicProgramming/find-number-endless-points.py" ]
[ "import numpy as np\n\ndef countEndless(input_mat, n):\n row = np.zeros((n, n))\n col = np.zeros((n, n))\n for j in range(n):\n isEndless = 1\n for i in range(n - 1, -1, -1):\n if (input_mat[i][j] == 0):\n isEndless = 0\n col[i][j] = isEndless\n for i in range(n):\n isEndless = 1\n for j in range(n - 1, -1, -1):\n if (input_mat[i][j] == 0):\n isEndless = 0\n row[i][j] = isEndless\n ans = 0\n for i in range(n):\n for j in range(1, n):\n if (row[i][j] and col[i][j]):\n ans += 1\n return ans\n\nif __name__ == \"__main__\":\n input_mat = [[1, 0, 1, 1],\n [0, 1, 1, 1],\n [1, 1, 1, 1],\n [0, 1, 1, 0]]\n n = 4\n print(countEndless(input_mat, n))\n" ]
[ [ "numpy.zeros" ] ]
ellisztamas/amajus_mating
[ "9bfdb4ebaa96178c801e5fdd8aecb6b83132b397" ]
[ "002.library/python/tests/test_mcmc.py" ]
[ "import numpy as np\nimport os\nimport pandas as pd\nfrom scipy.stats import beta\nfrom scipy.stats import gamma as gma\n\nfrom amajusmating import mcmc\n\n# FAPS objects and distance matrices are generated in a separate script.\nexec(open('003.scripts/setup_FAPS_GPS.py').read())\n\n# INITIALISE THE MODEL\nnp.random.seed(1246)\n\n# Dictionary listing starting values.\ninitial_parameters = {\n 'missing' : 0.15, # proportion missing fathers\n 'shape' : 1,\n 'scale' : 10,\n 'mixture' : 0.8\n}\n\n# Proposed values are a Gaussian peturbation away from the previous values.\n# This is controlled by the sigma of the gaussian, which is defined for each variable\nproposal_sigma = {\n 'missing' : 0.025,\n 'shape' : 0.05,\n 'scale' : 2,\n 'mixture' : 0.025,\n}\n\n# PRIORS\npriors = (lambda x : {\n 'missing' : beta.pdf(x['missing'], a=3, b=15),\n 'mixture' : beta.pdf(x['mixture'], a=1.1, b=1.1),\n 'shape' : gma.pdf(x['shape'], a=10, scale = 1/5),\n 'scale' : gma.pdf(x['scale'], a=6, scale = 50)\n})\n\ndef test_mcmc():\n folder = os.path.dirname(os.path.abspath(__file__))\n file = \"/mcmc_test_chain\"\n\n chain = mcmc.run_MCMC(\n data= am_data,\n initial_parameters = initial_parameters,\n proposal_sigma = proposal_sigma,\n priors = priors,\n thin=1,\n nreps=3,\n output_dir = folder,\n chain_name = file,\n max_distance = np.inf\n )\n\n assert os.path.exists(folder + file + \".out\")\n assert os.path.exists(folder + file + \".log\")\n\n dat = pd.read_csv(\"002.library/python/tests/mcmc_test_chain.out\", sep=\"\\t\")\n assert list(dat.keys()) == ['iter', 'hours', 'log_posterior', 'log_prior', 'loglik', 'missing', 'mixture', 'scale', 'shape']\n\n os.remove(folder + file + \".out\")\n os.remove(folder + file + \".log\")\n" ]
[ [ "scipy.stats.beta.pdf", "pandas.read_csv", "numpy.random.seed", "scipy.stats.gamma.pdf" ] ]
kinglintianxia/KittiSeg
[ "71cf15b8482fe7e18a98c711bb6ad96960467194" ]
[ "submodules/evaluation/kitti_devkit/seg_utils.py" ]
[ "#!/usr/bin/env python\n# coding: utf-8\n# THE KITTI VISION BENCHMARK SUITE: ROAD BENCHMARK\n#\n# Copyright (C) 2013\n# Honda Research Institute Europe GmbH\n# Carl-Legien-Str. 30\n# 63073 Offenbach/Main\n# Germany\n#\n# UNPUBLISHED PROPRIETARY MATERIAL.\n# ALL RIGHTS RESERVED.\n#\n# Authors: Tobias Kuehnl <[email protected]>\n# Jannik Fritsch <[email protected]>\n#\n\nimport numpy as np\n# import pylab\nimport matplotlib.cm as cm\nimport os\n# import cv2\n\ndef make_overlay(image, gt_prob):\n\n mycm = cm.get_cmap('bwr')\n\n overimage = mycm(gt_prob, bytes=True)\n output = 0.4*overimage[:,:,0:3] + 0.6*image\n\n return output\n\n\ndef overlayImageWithConfidence(in_image, conf, vis_channel = 1, threshold = 0.5):\n '''\n \n :param in_image:\n :param conf:\n :param vis_channel:\n :param threshold:\n '''\n if in_image.dtype == 'uint8':\n visImage = in_image.copy().astype('f4')/255\n else:\n visImage = in_image.copy()\n \n channelPart = visImage[:, :, vis_channel] * (conf > threshold) - conf\n channelPart[channelPart < 0] = 0\n visImage[:, :, vis_channel] = 0.5*visImage[:, :, vis_channel] + 255*conf\n return visImage\n\ndef evalExp(gtBin, cur_prob, thres, validMap = None, validArea=None):\n '''\n Does the basic pixel based evaluation!\n :param gtBin: gt road image, [384,1248], 'True' or 'False'\n :param cur_prob: cnn image [384,1248], 'True' or 'False'\n :param thres: [0.0, 1.0]\n :param validMap: \n :param valid area.\n '''\n\n assert len(cur_prob.shape) == 2, 'Wrong size of input prob map'\n assert len(gtBin.shape) == 2, 'Wrong size of input prob map'\n thresInf = np.concatenate(([-np.Inf], thres, [np.Inf])) # Join a sequence of arrays along an existing axis.\n \n # Merge validMap with validArea\n if validMap is not None:\n if validArea is not None:\n validMap = (validMap == True) & (validArea == True)\n elif validArea is not None:\n validMap=validArea\n\n # histogram of false negatives\n if validMap is not None:\n fnArray = cur_prob[(gtBin == True) & (validMap == True)]\n else:\n fnArray = cur_prob[(gtBin == True)] # TP+FN\n fnHist = np.histogram(fnArray,bins=thresInf)[0] # np.histogram returns [hist, bin]\n # a = np.array([[1,2,3], [4,5,6]])\n # np.cumsum(a)\n # >> array([ 1, 3, 6, 10, 15, 21])\n fnCum = np.cumsum(fnHist) # 累加和[CS,CUSUM]\n FN = fnCum[0:0+len(thres)];\n \n if validMap is not None:\n fpArray = cur_prob[(gtBin == False) & (validMap == True)]\n else:\n fpArray = cur_prob[(gtBin == False)]\n \n fpHist = np.histogram(fpArray, bins=thresInf)[0]\n # np.flipud: Flip array in the up/down direction.\n fpCum = np.flipud(np.cumsum(np.flipud(fpHist)))\n FP = fpCum[1:1+len(thres)]\n\n # count labels and protos\n #posNum = fnArray.shape[0]\n #negNum = fpArray.shape[0]\n if validMap is not None:\n posNum = np.sum((gtBin == True) & (validMap == True))\n negNum = np.sum((gtBin == False) & (validMap == True))\n else:\n posNum = np.sum(gtBin == True)\n negNum = np.sum(gtBin == False)\n return FN, FP, posNum, negNum # FN, FP, TP+FN, FP+TN\n\ndef pxEval_maximizeFMeasure(totalPosNum, totalNegNum, totalFN, totalFP, thresh = None):\n '''\n\n @param totalPosNum: scalar\n @param totalNegNum: scalar\n @param totalFN: vector\n @param totalFP: vector\n @param thresh: vector\n '''\n\n #Calc missing stuff\n totalTP = totalPosNum - totalFN\n totalTN = totalNegNum - totalFP\n\n\n valid = (totalTP>=0) & (totalTN>=0)\n assert valid.all(), 'Detected invalid elements in eval'\n\n recall = totalTP / float( totalPosNum )\n TNR = totalTN / float( totalNegNum )\n precision = totalTP / (totalTP + totalFP + 1e-10)\n # acc = (TP+TN)/(P+N) = (TP+TN)/(TP+TN+FP+FN)\n accuracy = (totalTP + totalTN) / (float( totalPosNum ) + float( totalNegNum ))\n # king \n # compute IOU = TP/(TP+FN+FP)\n IOU = (totalTP) / (float(totalPosNum) + float(totalNegNum) - totalTN)\n \n selector_invalid = (recall==0) & (precision==0)\n recall = recall[~selector_invalid]\n precision = precision[~selector_invalid]\n \n maxValidIndex = len(precision)\n \n #Pascal VOC average precision\n AvgPrec = 0\n counter = 0\n for i in np.arange(0,1.1,0.1):\n ind = np.where(recall>=i)\n if ind == None:\n continue\n pmax = max(precision[ind])\n AvgPrec += pmax\n counter += 1\n AvgPrec = AvgPrec/counter\n \n \n # F-measure operation point\n beta = 1.0\n betasq = beta**2\n F = (1 + betasq) * (precision * recall)/((betasq * precision) + recall + 1e-10)\n index = F.argmax()\n MaxF= F[index]\n \n recall_bst = recall[index]\n precision_bst = precision[index]\n\n TP = totalTP[index]\n TN = totalTN[index]\n FP = totalFP[index]\n FN = totalFN[index]\n valuesMaxF = np.zeros((1,4),'u4')\n valuesMaxF[0,0] = TP\n valuesMaxF[0,1] = TN\n valuesMaxF[0,2] = FP\n valuesMaxF[0,3] = FN\n\n #ACC = (totalTP+ totalTN)/(totalPosNum+totalNegNum)\n prob_eval_scores = calcEvalMeasures(valuesMaxF)\n prob_eval_scores['AvgPrec'] = AvgPrec\n prob_eval_scores['MaxF'] = MaxF\n # king\n prob_eval_scores['accuracy'] = np.mean(accuracy) # cal mean of np.array.\n # king \n prob_eval_scores['IOU'] = np.mean(IOU)\n \n #prob_eval_scores['totalFN'] = totalFN\n #prob_eval_scores['totalFP'] = totalFP\n prob_eval_scores['totalPosNum'] = totalPosNum\n prob_eval_scores['totalNegNum'] = totalNegNum\n\n prob_eval_scores['precision'] = precision\n prob_eval_scores['recall'] = recall\n prob_eval_scores['TNR'] = TNR\n #prob_eval_scores['precision_bst'] = precision_bst\n #prob_eval_scores['recall_bst'] = recall_bst\n prob_eval_scores['thresh'] = thresh\n if thresh is not None:\n BestThresh= thresh[index]\n prob_eval_scores['BestThresh'] = BestThresh\n\n #return a dict\n return prob_eval_scores\n\n\n\ndef calcEvalMeasures(evalDict, tag = '_wp'):\n '''\n \n :param evalDict:\n :param tag:\n '''\n # array mode!\n TP = evalDict[:,0].astype('f4')\n TN = evalDict[:,1].astype('f4')\n FP = evalDict[:,2].astype('f4')\n FN = evalDict[:,3].astype('f4')\n Q = TP / (TP + FP + FN)\n P = TP + FN\n N = TN + FP\n TPR = TP / P\n FPR = FP / N\n FNR = FN / P\n TNR = TN / N\n A = (TP + TN) / (P + N)\n precision = TP / (TP + FP)\n recall = TP / P\n #numSamples = TP + TN + FP + FN\n correct_rate = A\n\n # F-measure\n #beta = 1.0\n #betasq = beta**2\n #F_max = (1 + betasq) * (precision * recall)/((betasq * precision) + recall + 1e-10)\n \n \n outDict =dict()\n\n outDict['TP'+ tag] = TP\n outDict['FP'+ tag] = FP\n outDict['FN'+ tag] = FN\n outDict['TN'+ tag] = TN\n outDict['Q'+ tag] = Q\n outDict['A'+ tag] = A\n outDict['TPR'+ tag] = TPR\n outDict['FPR'+ tag] = FPR\n outDict['FNR'+ tag] = FNR\n outDict['PRE'+ tag] = precision\n outDict['REC'+ tag] = recall\n outDict['correct_rate'+ tag] = correct_rate\n return outDict\n\ndef setFigLinesBW(fig):\n \"\"\"\n Take each axes in the figure, and for each line in the axes, make the\n line viewable in black and white.\n \"\"\"\n for ax in fig.get_axes():\n setAxLinesBW(ax)\n \ndef setAxLinesBW(ax):\n \"\"\"\n Take each Line2D in the axes, ax, and convert the line style to be\n suitable for black and white viewing.\n \"\"\"\n MARKERSIZE = 3\n\n# COLORMAP = {\n# 'r': {'marker': None, 'dash': (None,None)},\n# 'g': {'marker': None, 'dash': [5,2]},\n# 'm': {'marker': None, 'dash': [11,3]},\n# 'b': {'marker': None, 'dash': [6,3,2,3]},\n# 'c': {'marker': None, 'dash': [1,3]},\n# 'y': {'marker': None, 'dash': [5,3,1,2,1,10]},\n# 'k': {'marker': 'o', 'dash': (None,None)} #[1,2,1,10]}\n# }\n COLORMAP = {\n 'r': {'marker': \"None\", 'dash': (\"None\",\"None\")},\n 'g': {'marker': \"None\", 'dash': [5,2]},\n 'm': {'marker': \"None\", 'dash': [11,3]},\n 'b': {'marker': \"None\", 'dash': [6,3,2,3]},\n 'c': {'marker': \"None\", 'dash': [1,3]},\n 'y': {'marker': \"None\", 'dash': [5,3,1,2,1,10]},\n 'k': {'marker': 'o', 'dash': (\"None\",\"None\")} #[1,2,1,10]}\n }\n\n for line in ax.get_lines():\n origColor = line.get_color()\n #line.set_color('black')\n line.set_dashes(COLORMAP[origColor]['dash'])\n line.set_marker(COLORMAP[origColor]['marker'])\n line.set_markersize(MARKERSIZE)\n \ndef plotPrecisionRecall(precision, recall, outFileName, Fig=None, drawCol=1, textLabel = None, title = None, fontsize1 = 24, fontsize2 = 20, linewidth = 3):\n '''\n \n :param precision:\n :param recall:\n :param outFileName:\n :param Fig:\n :param drawCol:\n :param textLabel:\n :param fontsize1:\n :param fontsize2:\n :param linewidth:\n '''\n \n clearFig = False \n \n if Fig == None:\n Fig = pylab.figure()\n clearFig = True\n \n #tableString = 'Algo avgprec Fmax prec recall accuracy fpr Q(TonITS)\\n'\n linecol = ['g','m','b','c']\n #if we are evaluating SP, then BL is available\n #sectionName = 'Evaluation_'+tag+'PxProb'\n #fullEvalFile = os.path.join(eval_dir,evalName)\n #Precision,Recall,evalString = readEvaluation(fullEvalFile,sectionName,AlgoLabel)\n\n pylab.plot(100*recall, 100*precision, linewidth=linewidth, color=linecol[drawCol], label=textLabel)\n\n\n #writing out PrecRecall curves as graphic\n setFigLinesBW(Fig)\n if textLabel!= None:\n pylab.legend(loc='lower left',prop={'size':fontsize2})\n \n if title!= None:\n pylab.title(title, fontsize=fontsize1)\n \n #pylab.title(title,fontsize=24)\n pylab.ylabel('PRECISION [%]',fontsize=fontsize1)\n pylab.xlabel('RECALL [%]',fontsize=fontsize1)\n \n pylab.xlim(0,100)\n pylab.xticks( [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100],\n ('0','','20','','40','','60','','80','','100'), fontsize=fontsize2 )\n pylab.ylim(0,100)\n pylab.yticks( [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100],\n ('0','','20','','40','','60','','80','','100'), fontsize=fontsize2 )\n pylab.grid(True)\n \n # \n if type(outFileName) != list:\n pylab.savefig( outFileName )\n else:\n for outFn in outFileName:\n pylab.savefig( outFn )\n if clearFig:\n pylab.close()\n Fig.clear()\n \n\n\ndef saveBEVImageWithAxes(data, outputname, cmap = None, xlabel = 'x [m]', ylabel = 'z [m]', rangeX = [-10, 10], rangeXpx = None, numDeltaX = 5, rangeZ = [7, 62], rangeZpx = None, numDeltaZ = 5, fontSize = 16):\n '''\n \n :param data:\n :param outputname:\n :param cmap:\n '''\n aspect_ratio = float(data.shape[1])/data.shape[0]\n fig = pylab.figure()\n Scale = 8\n # add +1 to get axis text\n fig.set_size_inches(Scale*aspect_ratio+1,Scale*1)\n ax = pylab.gca()\n #ax.set_axis_off()\n #fig.add_axes(ax)\n if cmap != None:\n pylab.set_cmap(cmap)\n \n #ax.imshow(data, interpolation='nearest', aspect = 'normal')\n ax.imshow(data, interpolation='nearest')\n \n if rangeXpx == None:\n rangeXpx = (0, data.shape[1])\n \n if rangeZpx == None:\n rangeZpx = (0, data.shape[0])\n \n modBev_plot(ax, rangeX, rangeXpx, numDeltaX, rangeZ, rangeZpx, numDeltaZ, fontSize, xlabel = xlabel, ylabel = ylabel)\n #plt.savefig(outputname, bbox_inches='tight', dpi = dpi)\n pylab.savefig(outputname, dpi = data.shape[0]/Scale)\n pylab.close()\n fig.clear()\n \ndef modBev_plot(ax, rangeX = [-10, 10 ], rangeXpx= [0, 400], numDeltaX = 5, rangeZ= [8,48 ], rangeZpx= [0, 800], numDeltaZ = 9, fontSize = None, xlabel = 'x [m]', ylabel = 'z [m]'):\n '''\n\n @param ax:\n '''\n #TODO: Configureabiltiy would be nice!\n if fontSize==None:\n fontSize = 8\n \n ax.set_xlabel(xlabel, fontsize=fontSize)\n ax.set_ylabel(ylabel, fontsize=fontSize)\n \n zTicksLabels_val = np.linspace(rangeZpx[0], rangeZpx[1], numDeltaZ)\n ax.set_yticks(zTicksLabels_val)\n #ax.set_yticks([0, 100, 200, 300, 400, 500, 600, 700, 800])\n xTicksLabels_val = np.linspace(rangeXpx[0], rangeXpx[1], numDeltaX)\n ax.set_xticks(xTicksLabels_val)\n xTicksLabels_val = np.linspace(rangeX[0], rangeX[1], numDeltaX)\n zTicksLabels = map(lambda x: str(int(x)), xTicksLabels_val)\n ax.set_xticklabels(zTicksLabels,fontsize=fontSize)\n zTicksLabels_val = np.linspace(rangeZ[1],rangeZ[0], numDeltaZ)\n zTicksLabels = map(lambda x: str(int(x)), zTicksLabels_val)\n ax.set_yticklabels(zTicksLabels,fontsize=fontSize)\n \n " ]
[ [ "numpy.histogram", "numpy.linspace", "numpy.arange", "numpy.flipud", "numpy.cumsum", "numpy.concatenate", "numpy.mean", "numpy.where", "matplotlib.cm.get_cmap", "numpy.zeros", "numpy.sum" ] ]
clatlan/bcdi
[ "afd50b474995378556195c007dc20316dcbc32af" ]
[ "tests/utils/test_image_registration.py" ]
[ "# -*- coding: utf-8 -*-\n\n# BCDI: tools for pre(post)-processing Bragg coherent X-ray diffraction imaging data\n# (c) 07/2017-06/2019 : CNRS UMR 7344 IM2NP\n# (c) 07/2019-05/2021 : DESY PHOTON SCIENCE\n# (c) 06/2021-present : DESY CFEL\n# authors:\n# Jerome Carnis, [email protected]\n\nimport numpy as np\nimport unittest\nimport bcdi.utils.image_registration as reg\n\n\ndef run_tests(test_class):\n suite = unittest.TestLoader().loadTestsFromTestCase(test_class)\n runner = unittest.TextTestRunner(verbosity=2)\n return runner.run(suite)\n\n\nclass TestCalcNewPositions(unittest.TestCase):\n \"\"\"\n Tests on the function calc_new_positions.\n\n def calc_new_positions(old_positions: list, shift: Sequence[float]) -> np.ndarray\n \"\"\"\n\n def setUp(self):\n self.shapes = ((3,), (4,), (2, 2), (1, 2, 2))\n self.shifts = ((1,), (-0.2,), (2.3, -0.1), (1.1, 0.3, 0))\n\n def test_ndim_no_shift(self):\n correct = (\n np.array([[-2], [-1], [0]]),\n np.array([[-2], [-1], [0], [1]]),\n np.array(\n [\n [-1, -1],\n [-1, 0],\n [0, -1],\n [0, 0],\n ]\n ),\n np.array([[-1, -1, -1], [-1, -1, 0], [-1, 0, -1], [-1, 0, 0]]),\n )\n for index, shape in enumerate(self.shapes):\n with self.subTest():\n old_pos = [np.arange(-val // 2, val // 2) for val in shape]\n new_pos = reg.calc_new_positions(old_pos, shift=(0,) * len(shape))\n self.assertTrue(np.allclose(new_pos, correct[index]))\n\n def test_ndim_with_shift(self):\n correct = (\n np.array([[-3], [-2], [-1]]),\n np.array([[-1.8], [-0.8], [0.2], [1.2]]),\n np.array(\n [\n [-3.3, -0.9],\n [-3.3, 0.1],\n [-2.3, -0.9],\n [-2.3, 0.1],\n ]\n ),\n np.array(\n [[-2.1, -1.3, -1], [-2.1, -1.3, 0], [-2.1, -0.3, -1], [-2.1, -0.3, 0]]\n ),\n )\n for index, shape in enumerate(self.shapes):\n with self.subTest():\n old_pos = [np.arange(-val // 2, val // 2) for val in shape]\n new_pos = reg.calc_new_positions(old_pos, shift=self.shifts[index])\n self.assertTrue(np.allclose(new_pos, correct[index]))\n\n def test_empty_positions(self):\n with self.assertRaises(ValueError):\n reg.calc_new_positions([], shift=[])\n\n def test_wrong_shift_length(self):\n with self.assertRaises(ValueError):\n reg.calc_new_positions([np.arange(-2, 1)], shift=[1, 2])\n\n def test_wrong_shift_none(self):\n with self.assertRaises(ValueError):\n reg.calc_new_positions([np.arange(-2, 1)], shift=None)\n\n\nclass TestGetShift2D(unittest.TestCase):\n \"\"\"\n Tests on the function image_registration.get_shift for 2D arrays.\n\n def get_shift(\n reference_array: np.ndarray,\n shifted_array: np.ndarray,\n shift_method: str = \"modulus\",\n precision: int = 1000,\n support_threshold: Union[None, float] = None,\n verbose: bool = True,\n ) -> Sequence[float]:\n \"\"\"\n\n def setUp(self):\n # executed before each test\n reference_array = np.zeros((5, 5), dtype=complex)\n reference_array[1:4, 1:4] = 1 + 1j\n shifted_array = np.zeros((5, 5), dtype=complex)\n shifted_array[2:, 2:] = 1 + 1j\n self.reference_array = reference_array\n self.shifted_array = shifted_array\n\n def test_method_modulus(self):\n shifts = reg.get_shift(\n reference_array=self.reference_array,\n shifted_array=self.shifted_array,\n shift_method=\"modulus\",\n )\n self.assertTrue(\n np.allclose(\n np.asarray(shifts),\n np.array([-1.0, -1.0]),\n rtol=1e-09,\n atol=1e-09,\n )\n )\n\n def test_method_raw(self):\n shifts = reg.get_shift(\n reference_array=self.reference_array,\n shifted_array=self.shifted_array,\n shift_method=\"raw\",\n )\n self.assertTrue(\n np.allclose(\n np.asarray(shifts),\n np.array([-1.0, -1.0]),\n rtol=1e-09,\n atol=1e-09,\n )\n )\n\n def test_method_support(self):\n shifts = reg.get_shift(\n reference_array=self.reference_array,\n shifted_array=self.shifted_array,\n shift_method=\"support\",\n support_threshold=0.5,\n )\n self.assertTrue(\n np.allclose(\n np.asarray(shifts),\n np.array([-1.0, -1.0]),\n rtol=1e-09,\n atol=1e-09,\n )\n )\n\n def test_method_support_none(self):\n with self.assertRaises(ValueError):\n reg.get_shift(\n reference_array=self.reference_array,\n shifted_array=self.shifted_array,\n shift_method=\"support\",\n )\n\n def test_precision_float(self):\n with self.assertRaises(TypeError):\n reg.get_shift(\n reference_array=self.reference_array,\n shifted_array=self.shifted_array,\n precision=2.3,\n )\n\n def test_precision_null(self):\n with self.assertRaises(ValueError):\n reg.get_shift(\n reference_array=self.reference_array,\n shifted_array=self.shifted_array,\n precision=0,\n )\n\n def test_precision_None(self):\n with self.assertRaises(ValueError):\n reg.get_shift(\n reference_array=self.reference_array,\n shifted_array=self.shifted_array,\n precision=None,\n )\n\n def test_precision_min_allowed(self):\n shifts = reg.get_shift(\n reference_array=self.reference_array,\n shifted_array=self.shifted_array,\n precision=1,\n )\n self.assertTrue(\n np.allclose(\n np.asarray(shifts),\n np.array([-1.0, -1.0]),\n rtol=1e-09,\n atol=1e-09,\n )\n )\n\n def test_wrong_method_name(self):\n with self.assertRaises(ValueError):\n reg.get_shift(\n reference_array=self.reference_array,\n shifted_array=self.shifted_array,\n shift_method=\"wrong\",\n )\n\n\nclass TestGetShift3D(unittest.TestCase):\n \"\"\"\n Tests on the function image_registration.get_shift for 3D arrays.\n\n def get_shift(\n reference_array: np.ndarray,\n shifted_array: np.ndarray,\n shift_method: str = \"modulus\",\n precision: int = 1000,\n support_threshold: Union[None, float] = None,\n verbose: bool = True,\n ) -> Sequence[float]:\n \"\"\"\n\n def setUp(self):\n # executed before each test\n reference_array = np.zeros((5, 5, 5), dtype=complex)\n reference_array[1:4, 1:4, 1:4] = 1 + 1j\n shifted_array = np.zeros((5, 5, 5), dtype=complex)\n shifted_array[2:, 2:, 0:3] = 1 + 1j\n self.reference_array = reference_array\n self.shifted_array = shifted_array\n\n def test_method_modulus(self):\n shifts = reg.get_shift(\n reference_array=self.reference_array,\n shifted_array=self.shifted_array,\n shift_method=\"modulus\",\n )\n self.assertTrue(\n np.allclose(\n np.asarray(shifts),\n np.array([-1.0, -1.0, 1.0]),\n rtol=1e-09,\n atol=1e-09,\n )\n )\n\n def test_method_raw(self):\n shifts = reg.get_shift(\n reference_array=self.reference_array,\n shifted_array=self.shifted_array,\n shift_method=\"raw\",\n )\n self.assertTrue(\n np.allclose(\n np.asarray(shifts),\n np.array([-1.0, -1.0, 1.0]),\n rtol=1e-09,\n atol=1e-09,\n )\n )\n\n def test_method_support(self):\n shifts = reg.get_shift(\n reference_array=self.reference_array,\n shifted_array=self.shifted_array,\n shift_method=\"support\",\n support_threshold=0.5,\n )\n self.assertTrue(\n np.allclose(\n np.asarray(shifts),\n np.array([-1.0, -1.0, 1.0]),\n rtol=1e-09,\n atol=1e-09,\n )\n )\n\n def test_method_support_none(self):\n with self.assertRaises(ValueError):\n reg.get_shift(\n reference_array=self.reference_array,\n shifted_array=self.shifted_array,\n shift_method=\"support\",\n )\n\n def test_precision_float(self):\n with self.assertRaises(TypeError):\n reg.get_shift(\n reference_array=self.reference_array,\n shifted_array=self.shifted_array,\n precision=2.3,\n )\n\n def test_precision_null(self):\n with self.assertRaises(ValueError):\n reg.get_shift(\n reference_array=self.reference_array,\n shifted_array=self.shifted_array,\n precision=0,\n )\n\n def test_precision_None(self):\n with self.assertRaises(ValueError):\n reg.get_shift(\n reference_array=self.reference_array,\n shifted_array=self.shifted_array,\n precision=None,\n )\n\n def test_precision_min_allowed(self):\n shifts = reg.get_shift(\n reference_array=self.reference_array,\n shifted_array=self.shifted_array,\n precision=1,\n )\n self.assertTrue(\n np.allclose(\n np.asarray(shifts),\n np.array([-1.0, -1.0, 1.0]),\n rtol=1e-09,\n atol=1e-09,\n )\n )\n\n def test_wrong_method_name(self):\n with self.assertRaises(ValueError):\n reg.get_shift(\n reference_array=self.reference_array,\n shifted_array=self.shifted_array,\n shift_method=\"wrong\",\n )\n\n\nclass TestInterpRgiTranslation2D(unittest.TestCase):\n \"\"\"\n Tests on the function image_registration.interp_rgi_translation for 2D arrays.\n\n def interp_rgi_translation(array: np.ndarray, shift: Sequence[float]) -> np.ndarray\n \"\"\"\n\n def setUp(self):\n # executed before each test\n reference_array = np.zeros((5, 5), dtype=complex)\n reference_array[1:4, 1:4] = 1 + 1j\n self.reference_array = reference_array\n shifted_array = np.zeros((5, 5), dtype=complex)\n shifted_array[2:, 2:] = 1 + 1j\n self.shifted_array = shifted_array\n self.shifts = (-1.0, -1.0)\n\n def test_output_dtype(self):\n aligned_array = reg.interp_rgi_translation(\n array=self.shifted_array,\n shift=self.shifts,\n )\n self.assertEqual(aligned_array.dtype, self.shifted_array.dtype)\n\n def test_method_rgi(self):\n aligned_array = reg.interp_rgi_translation(\n array=self.shifted_array,\n shift=self.shifts,\n )\n self.assertTrue(\n np.allclose(\n self.reference_array,\n aligned_array,\n rtol=1e-09,\n atol=1e-09,\n )\n )\n\n\nclass TestInterpRgiTranslation3D(unittest.TestCase):\n \"\"\"\n Tests on the function image_registration.interp_rgi_translation for 3D arrays.\n\n def interp_rgi_translation(array: np.ndarray, shift: Sequence[float]) -> np.ndarray\n \"\"\"\n\n def setUp(self):\n # executed before each test\n reference_array = np.zeros((5, 5, 5), dtype=complex)\n reference_array[1:4, 1:4, 1:4] = 1 + 1j\n self.reference_array = reference_array\n shifted_array = np.zeros((5, 5, 5), dtype=complex)\n shifted_array[2:, 2:, 0:3] = 1 + 1j\n self.shifted_array = shifted_array\n self.shifts = (-1.0, -1.0, 1.0)\n\n def test_output_dtype(self):\n aligned_array = reg.interp_rgi_translation(\n array=self.shifted_array,\n shift=self.shifts,\n )\n self.assertEqual(aligned_array.dtype, self.shifted_array.dtype)\n\n def test_method_rgi(self):\n aligned_array = reg.interp_rgi_translation(\n array=self.shifted_array,\n shift=self.shifts,\n )\n self.assertTrue(\n np.allclose(\n self.reference_array,\n aligned_array,\n rtol=1e-09,\n atol=1e-09,\n )\n )\n\n\nclass TestShiftArray2D(unittest.TestCase):\n \"\"\"\n Tests on the function image_registration.shift_array for 2D arrays.\n\n def shift_array(\n array: np.ndarray, shift: Sequence[float], interpolation_method: str = \"subpixel\"\n ) -> np.ndarray:\n \"\"\"\n\n def setUp(self):\n # executed before each test\n reference_array = np.zeros((5, 5), dtype=complex)\n reference_array[1:4, 1:4] = 1 + 1j\n shifted_array = np.zeros((5, 5), dtype=complex)\n shifted_array[2:, 2:] = 1 + 1j\n self.reference_array = reference_array\n self.shifted_array = shifted_array\n self.shifts = reg.get_shift(\n reference_array=self.reference_array, shifted_array=self.shifted_array\n )\n\n def test_output_dtype(self):\n aligned_array = reg.shift_array(\n array=self.shifted_array,\n shift=self.shifts,\n interpolation_method=\"subpixel\",\n )\n self.assertEqual(aligned_array.dtype, self.shifted_array.dtype)\n\n def test_method_subpixel(self):\n aligned_array = reg.shift_array(\n array=self.shifted_array,\n shift=self.shifts,\n interpolation_method=\"subpixel\",\n )\n self.assertTrue(\n np.allclose(\n self.reference_array,\n aligned_array,\n rtol=1e-09,\n atol=1e-09,\n )\n )\n\n def test_method_rgi(self):\n aligned_array = reg.shift_array(\n array=self.shifted_array,\n shift=self.shifts,\n interpolation_method=\"rgi\",\n )\n self.assertTrue(\n np.allclose(\n self.reference_array,\n aligned_array,\n rtol=1e-09,\n atol=1e-09,\n )\n )\n\n def test_method_roll(self):\n aligned_array = reg.shift_array(\n array=self.shifted_array,\n shift=self.shifts,\n interpolation_method=\"roll\",\n )\n self.assertTrue(\n np.allclose(\n self.reference_array,\n aligned_array,\n rtol=1e-09,\n atol=1e-09,\n )\n )\n\n\nclass TestShiftArray3D(unittest.TestCase):\n \"\"\"\n Tests on the function image_registration.shift_array for 3D arrays.\n\n def shift_array(\n array: np.ndarray, shift: Sequence[float], interpolation_method: str = \"subpixel\"\n ) -> np.ndarray:\n \"\"\"\n\n def setUp(self):\n # executed before each test\n reference_array = np.zeros((5, 5, 5), dtype=complex)\n reference_array[1:4, 1:4, 1:4] = 1 + 1j\n shifted_array = np.zeros((5, 5, 5), dtype=complex)\n shifted_array[2:, 2:, 0:3] = 1 + 1j\n self.reference_array = reference_array\n self.shifted_array = shifted_array\n self.shifts = reg.get_shift(\n reference_array=self.reference_array, shifted_array=self.shifted_array\n )\n\n def test_output_dtype(self):\n aligned_array = reg.shift_array(\n array=self.shifted_array,\n shift=self.shifts,\n interpolation_method=\"subpixel\",\n )\n self.assertEqual(aligned_array.dtype, self.shifted_array.dtype)\n\n def test_method_subpixel(self):\n aligned_array = reg.shift_array(\n array=self.shifted_array,\n shift=self.shifts,\n interpolation_method=\"subpixel\",\n )\n self.assertTrue(\n np.allclose(\n self.reference_array,\n aligned_array,\n rtol=1e-09,\n atol=1e-09,\n )\n )\n\n def test_method_rgi(self):\n aligned_array = reg.shift_array(\n array=self.shifted_array,\n shift=self.shifts,\n interpolation_method=\"rgi\",\n )\n self.assertTrue(\n np.allclose(\n self.reference_array,\n aligned_array,\n rtol=1e-09,\n atol=1e-09,\n )\n )\n\n def test_method_roll(self):\n aligned_array = reg.shift_array(\n array=self.shifted_array,\n shift=self.shifts,\n interpolation_method=\"roll\",\n )\n self.assertTrue(\n np.allclose(\n self.reference_array,\n aligned_array,\n rtol=1e-09,\n atol=1e-09,\n )\n )\n\n\nif __name__ == \"__main__\":\n run_tests(TestCalcNewPositions)\n run_tests(TestGetShift2D)\n run_tests(TestGetShift2D)\n run_tests(TestShiftArray2D)\n run_tests(TestShiftArray3D)\n" ]
[ [ "numpy.allclose", "numpy.asarray", "numpy.arange", "numpy.array", "numpy.zeros" ] ]
bjornwallner/alphafoldv2.1.0
[ "d145e95d2f442578a2f5a60d816ee1742720b488" ]
[ "alphafold/common/protein.py" ]
[ "# Copyright 2021 DeepMind Technologies Limited\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\"\"\"Protein data type.\"\"\"\nimport dataclasses\nimport io\nfrom typing import Any, Mapping, Optional\nfrom alphafold.common import residue_constants\nfrom Bio.PDB import PDBParser\nimport numpy as np\n\nFeatureDict = Mapping[str, np.ndarray]\nModelOutput = Mapping[str, Any] # Is a nested dict.\n\n# Complete sequence of chain IDs supported by the PDB format.\nPDB_CHAIN_IDS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'\nPDB_MAX_CHAINS = len(PDB_CHAIN_IDS) # := 62.\n\n\[email protected](frozen=True)\nclass Protein:\n \"\"\"Protein structure representation.\"\"\"\n\n # Cartesian coordinates of atoms in angstroms. The atom types correspond to\n # residue_constants.atom_types, i.e. the first three are N, CA, CB.\n atom_positions: np.ndarray # [num_res, num_atom_type, 3]\n\n # Amino-acid type for each residue represented as an integer between 0 and\n # 20, where 20 is 'X'.\n aatype: np.ndarray # [num_res]\n\n # Binary float mask to indicate presence of a particular atom. 1.0 if an atom\n # is present and 0.0 if not. This should be used for loss masking.\n atom_mask: np.ndarray # [num_res, num_atom_type]\n\n # Residue index as used in PDB. It is not necessarily continuous or 0-indexed.\n residue_index: np.ndarray # [num_res]\n\n # 0-indexed number corresponding to the chain in the protein that this residue\n # belongs to.\n chain_index: np.ndarray # [num_res]\n\n # B-factors, or temperature factors, of each residue (in sq. angstroms units),\n # representing the displacement of the residue from its ground truth mean\n # value.\n b_factors: np.ndarray # [num_res, num_atom_type]\n\n def __post_init__(self):\n if len(np.unique(self.chain_index)) > PDB_MAX_CHAINS:\n raise ValueError(\n f'Cannot build an instance with more than {PDB_MAX_CHAINS} chains '\n 'because these cannot be written to PDB format.')\n\n\ndef from_pdb_string(pdb_str: str, chain_id: Optional[str] = None) -> Protein:\n \"\"\"Takes a PDB string and constructs a Protein object.\n\n WARNING: All non-standard residue types will be converted into UNK. All\n non-standard atoms will be ignored.\n\n Args:\n pdb_str: The contents of the pdb file\n chain_id: If chain_id is specified (e.g. A), then only that chain\n is parsed. Otherwise all chains are parsed.\n\n Returns:\n A new `Protein` parsed from the pdb contents.\n \"\"\"\n pdb_fh = io.StringIO(pdb_str)\n parser = PDBParser(QUIET=True)\n structure = parser.get_structure('none', pdb_fh)\n models = list(structure.get_models())\n if len(models) != 1:\n raise ValueError(\n f'Only single model PDBs are supported. Found {len(models)} models.')\n model = models[0]\n\n atom_positions = []\n aatype = []\n atom_mask = []\n residue_index = []\n chain_ids = []\n b_factors = []\n\n for chain in model:\n if chain_id is not None and chain.id != chain_id:\n continue\n for res in chain:\n if res.id[2] != ' ':\n raise ValueError(\n f'PDB contains an insertion code at chain {chain.id} and residue '\n f'index {res.id[1]}. These are not supported.')\n res_shortname = residue_constants.restype_3to1.get(res.resname, 'X')\n restype_idx = residue_constants.restype_order.get(\n res_shortname, residue_constants.restype_num)\n pos = np.zeros((residue_constants.atom_type_num, 3))\n mask = np.zeros((residue_constants.atom_type_num,))\n res_b_factors = np.zeros((residue_constants.atom_type_num,))\n for atom in res:\n if atom.name not in residue_constants.atom_types:\n continue\n pos[residue_constants.atom_order[atom.name]] = atom.coord\n mask[residue_constants.atom_order[atom.name]] = 1.\n res_b_factors[residue_constants.atom_order[atom.name]] = atom.bfactor\n if np.sum(mask) < 0.5:\n # If no known atom positions are reported for the residue then skip it.\n continue\n aatype.append(restype_idx)\n atom_positions.append(pos)\n atom_mask.append(mask)\n residue_index.append(res.id[1])\n chain_ids.append(chain.id)\n b_factors.append(res_b_factors)\n\n # Chain IDs are usually characters so map these to ints.\n #print('chains_ids:',chain_ids)\n unique_chain_ids = np.unique(chain_ids)\n chain_id_mapping = {cid: n for n, cid in enumerate(unique_chain_ids)}\n chain_index = np.array([chain_id_mapping[cid] for cid in chain_ids])\n\n return Protein(\n atom_positions=np.array(atom_positions),\n atom_mask=np.array(atom_mask),\n aatype=np.array(aatype),\n residue_index=np.array(residue_index),\n chain_index=chain_index,\n b_factors=np.array(b_factors))\n\n\ndef _chain_end(atom_index, end_resname, chain_name, residue_index) -> str:\n chain_end = 'TER'\n return (f'{chain_end:<6}{atom_index:>5} {end_resname:>3} '\n f'{chain_name:>1}{residue_index:>4}')\n\n\ndef to_pdb(prot: Protein) -> str:\n \"\"\"Converts a `Protein` instance to a PDB string.\n\n Args:\n prot: The protein to convert to PDB.\n\n Returns: PDB string.\n \"\"\"\n restypes = residue_constants.restypes + ['X']\n res_1to3 = lambda r: residue_constants.restype_1to3.get(restypes[r], 'UNK')\n atom_types = residue_constants.atom_types\n\n pdb_lines = []\n\n atom_mask = prot.atom_mask\n aatype = prot.aatype\n atom_positions = prot.atom_positions\n residue_index = prot.residue_index.astype(np.int32)\n chain_index = prot.chain_index.astype(np.int32)\n b_factors = prot.b_factors\n\n if np.any(aatype > residue_constants.restype_num):\n raise ValueError('Invalid aatypes.')\n\n # Construct a mapping from chain integer indices to chain ID strings.\n chain_ids = {}\n \n #The multimer version chain_ids starts from 1, using enumerate ensures the PDB_CHAIN_IDS are picked in order/BW\n for i,j in enumerate(np.unique(chain_index)): # np.unique gives sorted output.\n if i >= PDB_MAX_CHAINS:\n raise ValueError(\n f'The PDB format supports at most {PDB_MAX_CHAINS} chains.')\n chain_ids[j] = PDB_CHAIN_IDS[i] \n\n pdb_lines.append('MODEL 1')\n atom_index = 1\n last_chain_index = chain_index[0]\n # Add all atom sites.\n for i in range(aatype.shape[0]):\n # Close the previous chain if in a multichain PDB.\n if last_chain_index != chain_index[i]:\n pdb_lines.append(_chain_end(\n atom_index, res_1to3(aatype[i - 1]), chain_ids[chain_index[i - 1]],\n residue_index[i - 1]))\n last_chain_index = chain_index[i]\n atom_index += 1 # Atom index increases at the TER symbol.\n\n res_name_3 = res_1to3(aatype[i])\n for atom_name, pos, mask, b_factor in zip(\n atom_types, atom_positions[i], atom_mask[i], b_factors[i]):\n if mask < 0.5:\n continue\n\n record_type = 'ATOM'\n name = atom_name if len(atom_name) == 4 else f' {atom_name}'\n alt_loc = ''\n insertion_code = ''\n occupancy = 1.00\n element = atom_name[0] # Protein supports only C, N, O, S, this works.\n charge = ''\n # PDB is a columnar format, every space matters here!\n atom_line = (f'{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}'\n f'{res_name_3:>3} {chain_ids[chain_index[i]]:>1}'\n f'{residue_index[i]:>4}{insertion_code:>1} '\n f'{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}'\n f'{occupancy:>6.2f}{b_factor:>6.2f} '\n f'{element:>2}{charge:>2}')\n pdb_lines.append(atom_line)\n atom_index += 1\n\n # Close the final chain.\n pdb_lines.append(_chain_end(atom_index, res_1to3(aatype[-1]),\n chain_ids[chain_index[-1]], residue_index[-1]))\n pdb_lines.append('ENDMDL')\n pdb_lines.append('END')\n\n # Pad all lines to 80 characters.\n pdb_lines = [line.ljust(80) for line in pdb_lines]\n return '\\n'.join(pdb_lines) + '\\n' # Add terminating newline.\n\n\ndef ideal_atom_mask(prot: Protein) -> np.ndarray:\n \"\"\"Computes an ideal atom mask.\n\n `Protein.atom_mask` typically is defined according to the atoms that are\n reported in the PDB. This function computes a mask according to heavy atoms\n that should be present in the given sequence of amino acids.\n\n Args:\n prot: `Protein` whose fields are `numpy.ndarray` objects.\n\n Returns:\n An ideal atom mask.\n \"\"\"\n return residue_constants.STANDARD_ATOM_MASK[prot.aatype]\n\n\ndef from_prediction(\n features: FeatureDict,\n result: ModelOutput,\n b_factors: Optional[np.ndarray] = None,\n remove_leading_feature_dimension: bool = True) -> Protein:\n \"\"\"Assembles a protein from a prediction.\n\n Args:\n features: Dictionary holding model inputs.\n result: Dictionary holding model outputs.\n b_factors: (Optional) B-factors to use for the protein.\n remove_leading_feature_dimension: Whether to remove the leading dimension\n of the `features` values.\n\n Returns:\n A protein instance.\n \"\"\"\n fold_output = result['structure_module']\n\n def _maybe_remove_leading_dim(arr: np.ndarray) -> np.ndarray:\n return arr[0] if remove_leading_feature_dimension else arr\n\n if 'asym_id' in features:\n chain_index = _maybe_remove_leading_dim(features['asym_id'])\n else:\n chain_index = np.zeros_like(_maybe_remove_leading_dim(features['aatype']))\n\n if b_factors is None:\n b_factors = np.zeros_like(fold_output['final_atom_mask'])\n\n return Protein(\n aatype=_maybe_remove_leading_dim(features['aatype']),\n atom_positions=fold_output['final_atom_positions'],\n atom_mask=fold_output['final_atom_mask'],\n residue_index=_maybe_remove_leading_dim(features['residue_index']) + 1,\n chain_index=chain_index,\n b_factors=b_factors)\n" ]
[ [ "numpy.unique", "numpy.zeros_like", "numpy.any", "numpy.array", "numpy.zeros", "numpy.sum" ] ]
blekhmanlab/hominid
[ "caa1c4b3cf0f0502296fb043864d1a4d9d33549e" ]
[ "hominid/box_bar_plot.py" ]
[ "\"\"\"\nRead a rvcf file with stability selection scores for taxa.\nSort the dataframe by rsq_median.\nSave box and bar plots for the top N SNPs.\n\nNote: R must have packages dplyr and ggplot2 installed.\n\nI installed rpy2 with conda, which installs R in the virtual environment directory.\nIn my case that is ~/miniconda3/envs/hve/lib/R. This takes care of everything needed to\nrun this script.\n\nconda install r-essentials\n\nThis installs R and packages such as ggplot2 and dplyr.\n\nWhen using Canopy or Anaconda python distributions it may happen that\nR and rpy2 disagree about where to find gfortran and cause this:\n\n version `GFORTRAN_1.4' not found (required by /usr/lib/liblapack.so.3)\n\nThe solution in Ubuntu and related distributions is to point at the\nsystem libgfortran with LD_PRELOAD like this:\n\n LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libgfortran.so.3.0.0 python box_bar_plot.py <command line arguments>\n\nusage:\n (16S)\n python box_bar_plot_lasso_lars_cv_C_stability_selection_features.py \\\n ~/lab/glowing-happiness/hominid/project/hmp/16S_laf_sadj/mesabi/lasso_lars_c_C/results/hmp_16S_laf_sadj_anterior_nares/selected_features_results_mesabi_lasso_lars_cv_C_hmp_16S_laf_sadj_0_anterior_nares.rvcf \\\n taxon table file path\n transform\n 10 <- maximum SNP count\n\n (MGS modules)\n python box_bar_plot_lasso_lars_cv_C_stability_selection_features.py \\\n ~/lab/glowing-happiness/hominid/project/hmp/MGS_humann_mpm_sadj/mesabi/lasso_lars_c_C/results/MGS_humann_mpm_sadj_anterior_nares/selected_features_results_mesabi_lasso_lars_cv_C_MGS_humann_mpm_sadj_0_anterior_nares.rvcf \\\n taxon table file path\n transform\n 10\n\n\"\"\"\nimport argparse\nimport os\nimport shutil\n\nimport pandas as pd\n\n# the import of readline is a work-around for a\n# compatibility issue between anaconda and rpy2\n# see https://github.com/ContinuumIO/anaconda-issues/issues/152\n##import readline\nimport rpy2.robjects\nfrom rpy2.robjects.packages import SignatureTranslatedAnonymousPackage\n\nimport rpy2.robjects.lib.ggplot2 as ggplot2\nfrom rpy2.robjects.packages import importr\nbase = importr('base')\ngrdevices = importr('grDevices')\n\nfrom hominid.hominid import read_taxon_file, align_snp_and_taxa\n\n\ndef get_taxon_abundance_box_plot():\n box_plot_fnc = \"\"\"\n require(\"dplyr\")\n require(\"ggplot2\")\n\n taxon_abundance_box_plot <- function(data, plot_file_path, title, xlabel, ylabel) {\n\n temp <- data[order(data$variant_allele_count),] #sort by variant_allele_count\n temp$genotype <- factor(temp$genotype,levels=unique(temp$genotype)) #use reordered genotypes as levels\n\n pdf(plot_file_path)\n\n ap <- ggplot(data=temp,\n aes(x=genotype,y=abundance)\n )\n ap <- ap + geom_boxplot()\n ap <- ap + ggtitle(title)\n ap <- ap + labs(x=xlabel, y=ylabel)\n ap <- ap + geom_jitter(position=position_jitter(w=0.1))\n\n print(ap)\n dev.off()\n }\n \"\"\"\n pck = SignatureTranslatedAnonymousPackage(box_plot_fnc, 'pck')\n return pck.taxon_abundance_box_plot\n\n\ndef direct_taxon_abundance_box_plot(data, plot_file_path, title, xlabel, ylabel):\n grdevices.pdf(file=plot_file_path)\n\n gp = ggplot2.ggplot(data)\n pp = gp \\\n + ggplot2.aes_string(x='genotype', y='abundance') \\\n + ggplot2.geom_boxplot() \\\n + ggplot2.ggtitle(title) \\\n + ggplot2.labs(x=xlabel, y=ylabel) \\\n + ggplot2.geom_jitter(position=ggplot2.position_jitter(w=0.1)) \\\n + ggplot2.geom_point()\n\n pp.plot()\n\n grdevices.dev_off()\n\n\ndef get_taxon_abundance_stacked_bar_plot():\n box_plot_fnc = \"\"\"\n require(\"dplyr\")\n require(\"ggplot2\")\n\n taxon_abundance_stacked_bar_plot <- function(data, plot_file_path, title, xlabel, ylabel) {\n\n temp <- data[order(data$variant_allele_count),] #sort by variant_allele_count\n temp$genotype <- factor(temp$genotype,levels=unique(temp$genotype)) #use reordered genotypes as levels\n\n #creates a new data frame with median abundance from each combo\n result <- temp %>%\n group_by(genotype, gene, taxon) %>%\n summarize(medianAbundance = median(abundance))\n #If you want the heights of the bars to represent values in the data,\n #use stat=\"identity\" and map a value to the y aesthetic.\n\n pdf(plot_file_path, width=8, height=4)\n\n ap <- ggplot(data=result, aes(x=genotype,y=medianAbundance,fill=taxon)) +\n geom_bar(stat='identity') +\n ggtitle(title)\n ap <- ap + labs(x=xlabel, y=ylabel)\n ap <- ap + theme(legend.direction = 'vertical', legend.position = 'bottom')\n ap <- ap + guides(fill = guide_legend(reverse = TRUE))\n print(ap)\n dev.off()\n }\n \"\"\"\n pck = SignatureTranslatedAnonymousPackage(box_plot_fnc, 'pck')\n return pck.taxon_abundance_stacked_bar_plot\n\n\n#def direct_abundance_stacked_bar_plot(data, plot_file_path, title, xlabel, ylabel):\n# pass\n\n\ndef box_bar_lasso_lars_cv_C_stability_selection_features(\n rvcf_input_file_path, taxon_table_file_path, transform, plot_output_dir_path, stability_cutoff, snp_count):\n print('plotting {} SNPs from {}'.format(snp_count, rvcf_input_file_path))\n\n if os.path.exists(plot_output_dir_path):\n # delete it\n print('deleting old plots')\n shutil.rmtree(plot_output_dir_path)\n os.makedirs(plot_output_dir_path)\n\n # read the rvcf file and sort by rsq_median\n df = pd.read_csv(rvcf_input_file_path, sep='\\t', dtype={'CHROM': str})\n\n sorted_rsq_best_medians_df = df.sort_values(by='rsq_median', ascending=False)\n\n taxon_table_df = read_taxon_file(taxon_table_file_path, transform=transform)\n\n # these are proxies for R functions\n taxon_abundance_box_plot = get_taxon_abundance_box_plot()\n taxon_abundance_stacked_bar_plot = get_taxon_abundance_stacked_bar_plot()\n\n for row_i in range(sorted_rsq_best_medians_df.shape[0]):\n if row_i >= snp_count:\n break\n else:\n # get a 1-row dataframe\n snp_df = sorted_rsq_best_medians_df.iloc[[row_i]]\n aligned_snp_df, aligned_taxa_df = align_snp_and_taxa(\n snp_df,\n taxon_table_df\n )\n # get the taxon stability selection scores\n # use the taxon table df index to get column names for snp_df\n taxon_scores_df = snp_df.loc[:, taxon_table_df.index].transpose()\n sorted_taxon_scores_df = taxon_scores_df.sort_values(\n by=taxon_scores_df.columns[0], ascending=False)\n # print all sorted taxon scores to verify they are sorted high to low\n ##print('sorted_taxon_scores_df:\\n{}'.format(sorted_taxon_scores_df))\n p_df_list = []\n summary_line = '{}\\t{}\\t'.format(snp_df.iloc[0].GENE, snp_df.iloc[0].ID)\n for i, (selected_taxon, selected_taxon_row) in enumerate(sorted_taxon_scores_df.iterrows()):\n # use selected_taxon_row.index[0] to index the first and only column\n print('selected_taxon_row:\\n{}'.format(selected_taxon_row))\n selected_taxon_score = selected_taxon_row.iloc[0]\n if selected_taxon_score >= stability_cutoff:\n # trim 'Root;' from the front of the taxon name\n if selected_taxon.startswith('Root;'):\n taxon_name = selected_taxon[5:]\n else:\n taxon_name = selected_taxon\n summary_line += '{}, '.format(taxon_name)\n # print a box plot\n r_pdf_file_path = \\\n os.path.join(\n plot_output_dir_path,\n 'best_taxa_{}_{}_{}_boxplot_{}.pdf'.format(\n row_i,\n snp_df.iloc[0].GENE,\n snp_df.iloc[0].ID,\n i\n )\n )\n gts = [\n snp_df.iloc[0].REF + snp_df.iloc[0].REF, # 0\n snp_df.iloc[0].REF + snp_df.iloc[0].ALT, # 1\n snp_df.iloc[0].ALT + snp_df.iloc[0].ALT # 2\n ]\n aligned_snp_value_list = aligned_snp_df.values.flatten().tolist()\n p_df = pd.DataFrame({\n 'chromosome': [snp_df.iloc[0].CHROM] * aligned_snp_df.shape[1],\n 'snp_id': [snp_df.iloc[0].ID] * aligned_snp_df.shape[1],\n 'gene': [snp_df.iloc[0].GENE] * aligned_snp_df.shape[1],\n 'taxon': [selected_taxon] * aligned_snp_df.shape[1],\n 'abundance': aligned_taxa_df[selected_taxon].values.tolist(),\n 'variant_allele_count': [str(int(v)) for v in aligned_snp_value_list],\n 'gt': [gts[int(v)] for v in aligned_snp_value_list]\n })\n p_df_list.append(p_df)\n r_df = rpy2.robjects.vectors.DataFrame({\n 'abundance': rpy2.robjects.FloatVector(aligned_taxa_df[selected_taxon].values.tolist()),\n 'variant_allele_count': rpy2.robjects.StrVector([str(int(v)) for v in aligned_snp_value_list]),\n 'genotype': rpy2.robjects.StrVector([gts[int(v)] for v in aligned_snp_value_list])\n })\n print(taxon_name)\n print('r_df:\\n'.format(r_df))\n taxon_abundance_box_plot(\n r_df,\n r_pdf_file_path,\n '{} (score: {:4.3f})'.format(snp_df.iloc[0].GENE, selected_taxon_score),\n '{} {}'.format(snp_df.iloc[0].GENE, snp_df.iloc[0].ID),\n selected_taxon\n )\n else:\n # the selected_taxon_score is below the cutoff or is nan\n break\n\n # write a summary line and\n print(summary_line[:-2])\n #summary_file.write(summary_line[:-2])\n #summary_file.write('\\n')\n # save a stacked bar plot\n if len(p_df_list) > 0:\n file_name = 'stacked_bar_plot_selected_taxa_{}_{}.pdf'.format(\n snp_df.iloc[0].GENE,\n snp_df.iloc[0].ID\n )\n stacked_bar_plot_file_path = os.path.join(plot_output_dir_path, file_name)\n p_df = pd.concat(p_df_list, axis=0)\n # at this point the index for p_df looks like\n # 0...76.0...76.0...76\n # replace the index\n p_df.index = range(p_df.shape[0])\n r_all_df = rpy2.robjects.vectors.DataFrame({\n 'abundance': rpy2.robjects.FloatVector(p_df['abundance'].values.tolist()),\n 'variant_allele_count': rpy2.robjects.StrVector([str(int(v)) for v in p_df['variant_allele_count'].values]),\n 'taxon': rpy2.robjects.StrVector(p_df['taxon']),\n 'gene': rpy2.robjects.StrVector(p_df['gene']),\n 'genotype': rpy2.robjects.StrVector(p_df['gt'])\n })\n stacked_bar_title = '{}\\n{}'.format(snp_df.iloc[0].GENE, snp_df.iloc[0].ID)\n taxon_abundance_stacked_bar_plot(\n r_all_df,\n stacked_bar_plot_file_path,\n stacked_bar_title,\n '{} {}'.format(snp_df.iloc[0].GENE, snp_df.iloc[0].ID),\n 'median abundance'\n )\n\n\ndef main():\n argparser = argparse.ArgumentParser()\n argparser.add_argument('rvcf_input_file_path')\n argparser.add_argument('taxon_table_file_path')\n argparser.add_argument('transform')\n argparser.add_argument('plot_output_dir_path')\n argparser.add_argument(\n 'stability_cutoff',\n type=float\n )\n argparser.add_argument(\n 'snp_count',\n type=int\n )\n args = argparser.parse_args()\n print(args)\n box_bar_lasso_lars_cv_C_stability_selection_features(**vars(args))\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "pandas.concat", "pandas.read_csv" ] ]
Jaswin09/Animefy
[ "5ea01be4866a77e8a25b5342606763a754f5c3f7" ]
[ "model.py" ]
[ "import cv2\nimport numpy as np\n\n'''def read_file(filename):\n img = cv2.imread(filename)\n cv2_imshow(img)\n return img'''\ndef color_quantization(img, k):\n# Transform the image\n data = np.float32(img).reshape((-1, 3))\n\n# Determine criteria\n criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 0.001)\n\n# Implementing K-Means\n ret, label, center = cv2.kmeans(data, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)\n center = np.uint8(center)\n result = center[label.flatten()]\n result = result.reshape(img.shape)\n return result\n\ndef edge_mask(img, line_size, blur_value):\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n gray_blur = cv2.medianBlur(gray, blur_value)\n edges = cv2.adaptiveThreshold(gray_blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, line_size, blur_value)\n return edges\n\n#uploaded = files.upload()\n\n#filename = next(iter(uploaded))\n\ndef filter_func(filename) :\n img = cv2.imread(filename)\n line_size = 5\n blur_value = 7\n\n edges = edge_mask(img, line_size, blur_value)\n #cv2.imshow(\"newolf\",edges)\n cv2.imwrite(\"blackwhite.jpg\",edges)\n blurred = cv2.bilateralFilter(img, d=7, sigmaColor=200,sigmaSpace=200)\n #cv2_imshow(\"newolf\",blurred)\n #cv2.imwrite(\"blackwhite.jpg\",blurred)\n\n total_color = 9\n\n blurred = color_quantization(blurred, total_color)\n #cv2_imshow(\"newolf\",blurred)\n\n cartoon = cv2.bitwise_and(blurred, blurred, mask=edges)\n #cv2.imshow(\"newolf\",cartoon)\n cv2.imwrite(\"toonify.jpg\",cartoon)\n" ]
[ [ "numpy.uint8", "numpy.float32" ] ]
collinwu/machine-learning-adventures
[ "c534f4157571cea8e015bc257caf5d5d500e692d" ]
[ "linear_regression_training/model/train_model.py" ]
[ "import pandas as pd\nfrom pathlib import Path\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.externals import joblib\n\nfilepath = Path.cwd() / \"machine-learning-adventures\" / \"linear_regression_training\" / \"data\" / \"house_data.csv\"\n\ndatafile = pd.read_csv(filepath)\n\nX = datafile[[\"sq_feet\", \"num_bedrooms\", \"num_bathrooms\"]]\ny = datafile[\"sale_price\"]\n" ]
[ [ "pandas.read_csv" ] ]
thematrixduo/MXGNet
[ "e48c34f74d7aeb1436931af553969ca666dad962" ]
[ "train_PGM.py" ]
[ "import os\nimport argparse\nimport itertools\n\nimport numpy as np\nimport math\nimport torch.optim as optim\nfrom torchvision import datasets,transforms\nimport torch.utils\nfrom model_PGM import Model\nfrom torch.utils.data import DataLoader\nimport torch.nn.utils\n\nfrom data_utility import ToTensor\n#For preprocessed data loading,\nfrom data_utility import dataset\nfrom radam import RAdam\n\n\nmodel_save_name = 'PGM_ori_best.pt'\noptimizer_save_name = 'PGM_ori_best_opt.pt'\n\ndef train(model,optimizer,trainloader,validloader,device,args):\n avg_loss = 0\n count = 0\n best_acc = 0\n for epoch in range(args.epochs):\n for (data,label,meta_target) in trainloader:\n\n data = data.view(-1,16,args.image_size,args.image_size)\n label = label.view(-1)\n meta_target = meta_target.view(-1,12)\n bs = data.size()[0]\n data = data.to(device)\n label = label.to(device)\n meta_target = meta_target.to(device)\n optimizer.zero_grad()\n loss,_ = model(data,label,meta_target)\n loss = torch.sum(loss)\n avg_loss += loss.cpu().data.numpy()\n loss.backward()\n optimizer.step()\n count += 1\n if count % 100 == 0:\n print('Epoch-{}; Count-{}; loss: {} '.format(epoch, count, avg_loss / 100))\n avg_loss = 0\n\n if epoch > 0:\n model.eval()\n total_correct = 0.0\n num_samples = 0\n for (data,label,meta_target) in validloader:\n data = data.view(-1,16,args.image_size,args.image_size)\n label = label.view(-1)\n num_samples+=label.size(0)\n meta_target = meta_target.view(-1,12)\n data = data.to(device)\n label = label.to(device)\n meta_target = meta_target.to(device)\n _,score_vec = model(data,label,meta_target)\n _,pred = torch.max(score_vec,1)\n c = (pred == label).squeeze() \n total_correct += torch.sum(c).item()\n accuracy = total_correct/num_samples\n print('Accuracy:',accuracy,total_correct,num_samples) \n model.train()\n\n if epoch > 0 and accuracy > best_acc and args.save_model:\n print('saving model')\n torch.save(model.state_dict(), os.path.join(args.model_save_path,model_save_name ))\n torch.save(optimizer.state_dict(), os.path.join(args.model_save_path,optimizer_save_name ))\n best_acc = accuracy\n\ndef main():\n parser = argparse.ArgumentParser(description='PyTorch MNIST Example')\n parser.add_argument('data', metavar='DIR',\n help='path to dataset')\n parser.add_argument('--batch-size', type=int, default=128, metavar='N',\n help='input batch size for training (default: 128)')\n parser.add_argument('--batch-size-val', type=int, default=64, metavar='N',\n help='input batch size for training (default: 64)')\n parser.add_argument('--epochs', type=int, default=1000, metavar='N',\n help='number of epochs to train (default: 1000)')\n parser.add_argument('--lr', type=float, default=1e-4, metavar='LR',\n help='learning rate (default: 1e-4)')\n parser.add_argument('--image-size', type=float, default=80, metavar='IMSIZE',\n help='input image size (default: 80)')\n parser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\n parser.add_argument('--multi-gpu', action='store_true', default=False,\n help='parallel training on multiple GPUs')\n parser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\n parser.add_argument('--save-model', action='store_true', default=False,\n help='For Saving the current Model')\n parser.add_argument('--model-save-path', default='', type=str, metavar='PATH',\n help='For Saving the current Model')\n parser.add_argument('--resume', default='', type=str, metavar='PATH',\n help='path to latest checkpoint (default: none)')\n args = parser.parse_args()\n\n\n torch.set_default_tensor_type('torch.FloatTensor')\n\n device = torch.device(\"cpu\" if args.no_cuda else \"cuda\")\n\n train_data = dataset(args.data, \"train\", args.image_size, transform=transforms.Compose([ToTensor()]),shuffle=True)\n valid_data = dataset(args.data, \"val\", args.image_size, transform=transforms.Compose([ToTensor()]))\n\n trainloader = DataLoader(train_data, batch_size=args.batch_size, shuffle=True, num_workers=8)\n validloader = DataLoader(valid_data, batch_size=args.batch_size_val, shuffle=False, num_workers=8)\n\n model = Model(args.image_size,args.image_size)\n\n optimizer = RAdam(model.parameters(),lr=args.lr,weight_decay = 1e-8)\n\n if not args.no_cuda:\n model.cuda()\n\n\n if torch.cuda.device_count() > 1 and args.multi_gpu:\n print(\"Let's use\", torch.cuda.device_count(), \"GPUs!\")\n model = torch.nn.DataParallel(model)\n\n if args.resume:\n model.load_state_dict(torch.load(os.path.join(args.resume,model_save_name )))\n optimizer.load_state_dict(torch.load(os.path.join(args.resume,optimizer_save_name )))\n\n train(model,optimizer,trainloader,validloader,device,args)\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "torch.utils.data.DataLoader" ] ]
diehlpk/muDIC
[ "b5d90aa62267b4bd0b88ae0a989cf09a51990654" ]
[ "muDIC/tests/test_dic/test_imageReader.py" ]
[ "from unittest import TestCase\n\nimport numpy as np\n\nfrom muDIC.IO import ImageStack\nfrom muDIC.IO.image_stack import ImageReader\n\n\ndef read_image_mocked(path, rotate=False):\n return np.zeros((100, 100))\n\n\ndef find_file_names_mocked(type=\".png\"):\n return ['file' + str(i).zfill(2) + type for i in range(100)]\n\n\nclass MockedImageStackFromFiles(ImageStack):\n def __init__(self, image_reader):\n super(MockedImageStackFromFiles, self).__init__(image_reader)\n\n # TODO: Use mocking instead of overwriting class methods\n def __read_image__(self, *args, **kwargs):\n return read_image_mocked(args, kwargs)\n\n def __find_file_names__(self, *args, **kwargs):\n return find_file_names_mocked(args, kwargs)\n\n\nclass MockerImageReader(ImageReader):\n def __init__(self):\n paths = find_file_names_mocked()\n super(MockerImageReader, self).__init__(paths)\n\n\nclass TestImageReader(TestCase):\n # Tests a an subclass of ImageReader where two methods have be overridden\n def setUp(self):\n path_to_folder = '/just/a/path/'\n image_reader = MockerImageReader()\n self.images = MockedImageStackFromFiles(image_reader)\n\n def test_get_active_frame_ids(self):\n # Check that the frame ids correspond to the images\n\n # Do several passes to check for side effects\n for i in range(5):\n # Get list of frame ids\n ids = self.images._active_img_ids_\n # Get list of frame ids from img names\n correct_images = [elm for ind, elm in enumerate(self.images.image_reader._image_paths_) if ind in ids]\n # Extract image ids from image names\n img_ids = [int((img.replace('file', '')).replace('.png', '')) for img in correct_images]\n\n # Check if all ids have a corresponding image\n self.assertEqual(ids, img_ids)\n\n # Remove some images and repeat\n self.images.skip_images([2, 7, 17, 92])\n\n def test_skip_images(self):\n skipped_frames = []\n\n # Try removing the frames individually\n for frame in range(0, 99, 3):\n skipped_frames.append(frame)\n self.images.skip_images(skipped_frames)\n ids = self.images._active_img_ids_\n img_ids = self.images._active_img_ids_ # [int((img.replace('file', '')).replace('.png', '')) for img in self.images._active_img_ids_]\n self.assertEqual(ids, img_ids)\n\n # Exception when index is out of bounds\n self.assertRaises(ValueError, self.images.skip_images, [101])\n self.assertRaises(ValueError, self.images.skip_images, [-1])\n" ]
[ [ "numpy.zeros" ] ]
emreakoz/capstone_app_TDI
[ "22bcc0ec701fbfdf71aaee18b0e07d0d28cec733" ]
[ "emotion_predictor.py" ]
[ "from network import network\nfrom PIL import Image\nimport numpy as np\nimport os\nimport shutil\nimport glob\n\ndef image_filtering(image_name):\n height, width = 128, 128\n im = np.empty(shape=(1,128,128,3))\n img = Image.open(image_name)\n img = img.resize((height, width), Image.ANTIALIAS)\n im[0,:,:,:] = np.array(img)[:,:,:3]\n \n return im\n\ndef move_image(image_path, root):\n shutil.copy(image_path, root+'static')\n os.remove(image_path)\n pass\n\ndef retrieve_image():\n root = '/app/'\n# root = '/Users/emre/apps/capstone_app/'\n \n if glob.glob(root+'*.jpg'):\n image_path = glob.glob(root+'*.jpg')[0]\n elif glob.glob(root+'*.png'):\n image_path = glob.glob(root+'*.png')[0]\n elif glob.glob(root+'*.jpeg'):\n image_path = glob.glob(root+'*.jpeg')[0]\n elif glob.glob(root+'*.eps'):\n image_path = glob.glob(root+'*.eps')[0]\n \n return root, image_path\n \ndef emotion_predictor():\n root, image_path = retrieve_image()\n im = image_filtering(image_path)\n \n model = network()\n model.load_weights('./model_weights_v1.h5') #load weights\n probs = list(model.predict(im)[0])\n emotion_probs = probs.copy()\n move_image(image_path, root)\n \n emotions_dict = {0:'neutral', 1:'happy', 2:'sad', 3:'surprised', 4:'fearful', \n 5:'disgusted', 6:'angry', 7:'contempt'}\n \n emotions_dict_ = {0:'neutral', 1:'happiness', 2:'sadness', 3:'surprise', 4:'fear', \n 5:'disgust', 6:'anger', 7:'contempt'}\n \n top1_emotion, probs[probs.index(max(probs))] = probs.index(max(probs)), 0\n top2_emotion, probs[probs.index(max(probs))] = probs.index(max(probs)), 0\n top3_emotion = probs.index(max(probs))\n \n emotion1 = emotions_dict[top1_emotion]\n emotion2 = emotions_dict_[top2_emotion]\n emotion3 = emotions_dict_[top3_emotion]\n \n return emotion1,emotion2,emotion3\n\ndef demographics_input_creator(ranking,age,gender,bq):\n mean,sd = 4608, 3911 ##numbers based on 600 marathon runners\n \n d = {'M':0,'F':1, '18-39': 0, '40-44': 1, '45-49': 2, '50-54': 3, '55-59': 4,\n '60-64': 5, '65-69': 6, '70+': 7, 'YES':0, 'NO':1}\n \n genders, bq, ages = [], [], []\n genders.append(keras.utils.to_categorical(d[gender], 2))\n ages.append(keras.utils.to_categorical(d[age], 8))\n bq.append(keras.utils.to_categorical(d[bq], 2))\n norm_ranking = (ranking-mean)/sd\n \n demographic_inputs = [list(ages)+list(genders)+list(bq)+[norm_ranking]]\n \n return demographic_inputs\n\ndef marathon_emotion_predictor(ranking,age,gender,bq):\n root, image_path = retrieve_image()\n im = image_filtering(image_path)\n demographic_inputs = demographics_input_creator(ranking,age,gender,bq)\n \n model = bilinear_network()\n model.load_weights('./bilinear_weights.h5') #load weights\n probs = list(model.predict([demographic_inputs,im])[0])\n emotion_probs = probs.copy()\n move_image(image_path, root)\n \n emotions_dict = {0:'neutral', 1:'happy', 2:'sad', 3:'surprised', 4:'fearful', \n 5:'disgusted', 6:'angry', 7:'contempt'}\n \n emotions_dict_ = {0:'neutral', 1:'happiness', 2:'sadness', 3:'surprise', 4:'fear', \n 5:'disgust', 6:'anger', 7:'contempt'}\n\n top1_emotion, probs[probs.index(max(probs))] = probs.index(max(probs)), 0\n top2_emotion, probs[probs.index(max(probs))] = probs.index(max(probs)), 0\n top3_emotion = probs.index(max(probs))\n \n printout1 = 'You look {} in this picture!'.format(\n emotions_dict[top1_emotion])\n printout2 = 'The other two probable emotions are {} and {}.'.format(\n emotions_dict_[top2_emotion], emotions_dict_[top3_emotion])\n \n return printout1, printout2\n\nif __name__ == '__main__':\n result = emotion_predictor()\n" ]
[ [ "numpy.array", "numpy.empty" ] ]
TeamOfProfGuo/DANet
[ "65f7cda4599dbdb1e44a755eb6b2a723ec244322" ]
[ "experiments/acdnet_att3/train_check.py" ]
[ "###########################################################################\n# Created by: Hang Zhang\n# Email: [email protected]\n# Copyright (c) 2017\n###########################################################################\n\nimport os, sys\nBASE_DIR = os.path.dirname(os.path.dirname(os.getcwd()))\nsys.path.append(BASE_DIR)\nimport copy\nimport yaml\nimport logging\nimport argparse\nimport numpy as np\nfrom tqdm import tqdm\nfrom addict import Dict\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils import data\nfrom tensorboardX import SummaryWriter\nimport torchvision.transforms as transform\nfrom torch.nn.parallel.scatter_gather import gather\n\nimport encoding.utils as utils\nfrom encoding.nn import SegmentationLosses, SyncBatchNorm\nfrom encoding.parallel import DataParallelModel, DataParallelCriterion\nfrom encoding.datasets import get_dataset\nfrom encoding.models import get_segmentation_model\n\nBASE_DIR = '.'\nCONFIG_PATH = 'experiments/acdnet/results/config.yaml'\nSMY_PATH = os.path.dirname(CONFIG_PATH)\nGPUS = [0,1]\n\n\n# ===================== setup ======================\n\n# configuration\nargs = Dict(yaml.safe_load(open(CONFIG_PATH)))\nargs.cuda = (args.use_cuda and torch.cuda.is_available())\ntorch.manual_seed(args.seed)\nargs.batch_size = 2\n\n# ================= trainer init ======================\n# data transforms\ninput_transform = transform.Compose([\n transform.ToTensor(), # convert RGB [0,255] to FloatTensor in range [0, 1]\n transform.Normalize([.485, .456, .406], [.229, .224, .225])]) # mean and std based on imageNet\ndep_transform = transform.Compose([\n transform.ToTensor(),\n transform.Normalize(mean=[0.2798], std=[0.1387]) # mean and std for depth\n])\n# dataset\ndata_kwargs = {'transform': input_transform, 'dep_transform':dep_transform,\n 'base_size': args.base_size, 'crop_size': args.crop_size}\ntrainset = get_dataset(args.dataset, split=args.train_split, mode='train', **data_kwargs)\ntestset = get_dataset(args.dataset, split='val', mode='val', **data_kwargs)\n\n# dataloader\nkwargs = {'num_workers': args.workers, 'pin_memory': True} if args.cuda else {}\ntrainloader = data.DataLoader(trainset, batch_size=args.batch_size, drop_last=True, shuffle=True, **kwargs)\nvalloader = data.DataLoader(testset, batch_size=args.batch_size, drop_last=False, shuffle=False, **kwargs)\nnclass = trainset.num_class\n\n# model\n\nmodel = get_segmentation_model(args.model, dataset=args.dataset, backbone=args.backbone, pretrained=True,\n root = './encoding/models/pretrain',n_features=256, with_CRP=False,\n with_att=True, att_type='AG3'\n # multi_grid=args.multi_grid, multi_dilation=args.multi_dilation, os=args.os\n )\n\nprint(model)\n\n# optimizer using different LR\nbase_ids = list(map(id, model.base.parameters()))\nbase_dep_ids = list(map(id, model.dep_base.parameters()))\nbase_params = filter(lambda p: id(p) in base_ids + base_dep_ids, model.parameters())\nother_params = filter(lambda p: id(p) not in base_ids + base_dep_ids, model.parameters())\noptimizer = torch.optim.SGD([{'params': base_params, 'lr': args.lr},\n {'params': other_params, 'lr': args.lr * 10}],\n lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay)\n\n\n# criterions\ncriterion = SegmentationLosses(se_loss=args.se_loss,\n aux=args.aux,\n nclass=nclass,\n se_weight=args.se_weight,\n aux_weight=args.aux_weight)\n\nscheduler = utils.LR_Scheduler_Head(args.lr_scheduler, args.lr, args.epochs, len(trainloader), warmup_epochs=1)\nbest_pred = 0.0\n\n# using cuda\ndevice = torch.device(\"cuda:0\" if args.cuda else \"cpu\")\nif args.cuda:\n if torch.cuda.device_count() > 1:\n print(\"Let's use\", torch.cuda.device_count(),\n \"GPUs!\") # dim = 0 [30, xxx] -> [10, ...], [10, ...], [10, ...] on 3 GPUs\n model = nn.DataParallel(model, device_ids=GPUS)\nmodel = model.to(device)\n\n\n\n\n# ==================== train =====================\ntrain_loss = 0.0\nepoch = 1\nmodel.train()\nfor i, (image, dep, target) in enumerate(trainloader):\n print('1 batch')\n break\n\nscheduler(optimizer, i, epoch, best_pred)\n\noptimizer.zero_grad()\n\n\n# check memory usage\nimport torch.autograd.profiler as profiler\nwith profiler.profile(profile_memory=True, record_shapes=True) as prof:\n outputs = model(image, dep)\nprint(prof.key_averages().table(sort_by=\"self_cpu_memory_usage\", row_limit=10))\n# check CPU/GPU usage\n# with profiler.profile(record_shapes=True) as prof:\n# with profiler.record_function(\"model_inference\"):\n# outputs = model(image)\n#\n# print(prof.key_averages().table(sort_by=\"cpu_time_total\", row_limit=10))\n\n\n\nloss = criterion(outputs, target)\nloss.backward()\noptimizer.step()\n\ntrain_loss += loss.item()\n" ]
[ [ "torch.manual_seed", "torch.utils.data.DataLoader", "torch.nn.DataParallel", "torch.cuda.is_available", "torch.optim.SGD", "torch.device", "torch.cuda.device_count", "torch.autograd.profiler.profile" ] ]
matthewdmorse/SRMspinanalysis
[ "4f1161a2fd418347caf9e61ae83b40869f8157b0" ]
[ "SRMspinanalysis/solver.py" ]
[ "import numpy as np\nfrom scipy.interpolate import interp1d\nfrom scipy.integrate import odeint\n\ndef compute_moments(design_params, thrust_motor_1, thrust_motor_2):\n \"\"\"Computes moment vector given thrust information from each motor and\n specific design parameters.\n\n Args:\n design_params (np.array()): Array of design parameters.\n [r1, r2, d1, d2, Ixx, Iyy, Izz] where r1 and r2 are the radial locations of\n the solid rocket motors (m), d1 and d2 are the longitudinal locations of the two\n motors (m), and Ixx, Iyy, and Izz are the interia values (kg-m^2).\n thrust_motor_1 (float): Thrust from motor 1 (N).\n thrust_motor_2 (float): Thrust from motor 2 (N).\n\n Returns:\n moments (np.array()): Moment vector in the x, y, and z directions (N-m).\n \n \"\"\"\n r1, r2, d1, d2, Ixx, Iyy, Izz = design_params\n if (design_params >= 0).all():\n Mx = 0.0;\n My = thrust_motor_1*d1 - thrust_motor_2*d2\n Mz = thrust_motor_1*r1 + thrust_motor_2*r2\n moments = np.array([Mx, My, Mz])\n return moments\n else:\n raise ValueError('All design parameters should be positive values.')\n\ndef interpolate_thrust_data(t, motor_time_data, motor_thrust_data):\n \"\"\"Performs a linear interpolation on motor thrust data and extracts the value\n at a desired time.\n\n Args:\n t (float): Desired time (s) at which to compute thrust.\n motor_time_data (np.array()): Time data from a specific motor (s).\n motor_thrust_data (np.array()): Thrust data from a specific motor (N).\n\n Returns:\n (float): Thrust at the specified time t.\n\n \"\"\"\n if t < np.min(motor_time_data) or t > np.max(motor_time_data):\n return 0.0\n else:\n interp_thrust = interp1d(motor_time_data, motor_thrust_data)\n return interp_thrust(t).item()\n\ndef euler_eom(f, t, design_params, SRM1, SRM2):\n \"\"\"Numerically computes the time derivatives of the specified function variables.\n To be used for numerical integration.\n\n Args:\n f (np.array()): Array of variables to be numerically solved.\n [wx, wy, wz, psi, theta, phi] where wx, wy, wz are the body angles of the launch\n vehicle (rad) and psi, theta, and phi are the Eulerian angles (rad).\n t (float): Time (s) to numerically solve equations of motion.\n design_params (np.array()): Array of design parameters.\n [r1, r2, d1, d2, Ixx, Iyy, Izz] where r1 and r2 are the radial locations of\n the solid rocket motors (m), d1 and d2 are the longitudinal locations of the two\n motors (m), and Ixx, Iyy, and Izz are the interia values (kg-m^2).\n SRM1 (SolidRocketMotor()): First solid rocket motor organized into a class.\n SRM2 (SolidRocketMotor()): Second solid rocket motor organized into a class.\n\n Returns:\n (np.array()): Array of the time derivatives of the function variables f.\n\n \"\"\"\n wx, wy, wz, psi, theta, phi = f\n r1, r2, d1, d2, Ixx, Iyy, Izz = design_params\n thrust_motor_1 = interpolate_thrust_data(t, SRM1.motor_time_data, SRM1.motor_thrust_data)\n thrust_motor_2 = interpolate_thrust_data(t, SRM2.motor_time_data, SRM2.motor_thrust_data)\n moments = compute_moments(design_params, thrust_motor_1, thrust_motor_2)\n Mx, My, Mz = moments\n # Differential equations of motion\n wx_dot = (Mx - (Izz - Iyy) * wy * wz) / Ixx\n wy_dot = (My - (Ixx - Izz) * wz * wx) / Iyy\n wz_dot = (Mz - (Iyy - Ixx) * wx * wy) / Izz\n psi_dot = (wy * np.sin(phi) + wz * np.cos(phi)) * 1.0 / np.cos(theta)\n theta_dot = wy * np.cos(phi) - wz * np.sin(phi)\n phi_dot = wx + (wy * np.sin(phi) + wz * np.cos(phi)) * np.tan(theta)\n return np.array([wx_dot, wy_dot, wz_dot, psi_dot, theta_dot, phi_dot])\n\ndef integrate_eom(initial_conditions, t_span, design_params, SRM1, SRM2):\n \"\"\"Numerically integrates the zero gravity equations of motion.\n\n Args:\n initial_conditions (np.array()): Array of initial conditions. Typically set\n to an array of zeros.\n t_span (np.array()): Time vector (s) over which to integrate the equations \n of motions.\n design_params (np.array()): Array of design parameters.\n [r1, r2, d1, d2, Ixx, Iyy, Izz] where r1 and r2 are the radial locations of\n the solid rocket motors (m), d1 and d2 are the longitudinal locations of the two\n motors (m), and Ixx, Iyy, and Izz are the interia values (kg-m^2).\n SRM1 (SolidRocketMotor()): First solid rocket motor organized into a class.\n SRM2 (SolidRocketMotor()): Second solid rocket motor organized into a class.\n\n Returns:\n (np.array()): Numerical solutions for wx, wy, wz, psi, theta, and phi.\n\n \"\"\"\n return odeint(euler_eom, initial_conditions, t_span, args=(design_params, SRM1, SRM2))\n\ndef compute_nutation_angle(theta, phi):\n \"\"\"Computes nutation angle of launch vehicle in degrees.\n\n Args:\n theta (np.array()): Array of Euler angle theta values (rad).\n phi (np.array()): Array of Euler angle phi values (rad).\n\n Returns:\n (np.array()): Array of nutation angle values (rad).\n\n \"\"\"\n nutation_angle = np.arccos(np.multiply(np.cos(theta),np.cos(phi)))\n return nutation_angle * (180.0 / np.pi)\n \ndef compute_precession_angle(theta, psi):\n \"\"\"Computes precession angle of launch vehicle in degrees.\n\n Args:\n theta (np.array()): Array of Euler angle theta values (rad).\n psi (np.array()): Array of Euler angle psi values (rad).\n\n Returns:\n (np.array()): Array of precession angle values (rad).\n\n \"\"\"\n precession_angle = np.arccos(np.multiply(np.cos(theta),np.cos(psi)))\n return precession_angle * (180.0 / np.pi)" ]
[ [ "numpy.min", "numpy.cos", "scipy.integrate.odeint", "numpy.sin", "numpy.max", "numpy.tan", "scipy.interpolate.interp1d", "numpy.array" ] ]
mlds-lab/mFlow
[ "b206fd1034aa525469f396238f5c765fc2bcd91f" ]
[ "mFlow/Blocks/imputer.py" ]
[ "\nimport sys, os\nfrom mFlow.Workflow.compute_graph import node\n\nfrom sklearn.impute import SimpleImputer\nimport pandas as pd\nimport numpy as np\n\n\n\ndef Imputer(*args, **kwargs):\n return node(function = __Imputer, args=args, kwargs=kwargs, name=\"Imputer\")\n\ndef __Imputer(df, method=\"mean\", show=False):\n \n model = SimpleImputer(missing_values=np.nan, strategy=method)\n\n df = df[\"dataframe\"]\n\n features = list(set(df.columns) - {'target'})\n numeric = df[features].values\n h,w = numeric.shape\n if(show): print(\" Imputer: Running on matrix of size %dx%d\"%(h,w))\n if np.any(np.isnan(numeric)):\n model.fit(numeric)\n imp = model.transform(numeric)\n \n df1 = pd.DataFrame(data=imp, columns=features, index=df.index)\n if 'target' in df.columns:\n df1['target'] = df['target']\n return({\"dataframe\":df1})\n\n else:\n if(show): print(\" Imputer: No missing values\")\n return({\"dataframe\":df})\n\n" ]
[ [ "numpy.isnan", "sklearn.impute.SimpleImputer", "pandas.DataFrame" ] ]
rhyswhitley/savanna_iav
[ "4eadf29a4e9c05d0b14d3b9c973eb8db3ea7edba", "4eadf29a4e9c05d0b14d3b9c973eb8db3ea7edba" ]
[ "src/setup_model/create_validation_ncdf.py", "src/data_preproc/pickleit/pickle_inputs.py" ]
[ "#!/usr/bin/env python2\n\nimport pandas as pd\nimport pickle\nimport os\n\ndef main():\n\n tower_data = pd.read_csv(FILEPATH, index_col=[0], parse_dates=True)\n\n tower_fluxes = tower_data.ix[:, [\"Fe\", \"Fe_Con\", \"GPP_Con\", \"Fre_Con\", \"Fc\", \"Fc_ustar\"]]\n\n with open(SAVEPATH, 'wb') as handle:\n pickle.dump(tower_fluxes, handle)\n\nif __name__ == \"__main__\":\n\n FILEPATH = os.path.expanduser(\"~/Dropbox/Dingo12/Advanced_processed_data_HowardSprings_v12.csv\")\n SAVEPATH = os.path.expanduser(\"~/Savanna/Data/HowardSprings_IAV/tower_fluxes_valid.pkl\")\n\n main()\n", "#!/usr/bin/env python\n\nimport os\nimport re\nimport netCDF4 as nc\nimport numpy as np\nimport pandas as pd\nimport pickle\n\ndef get_value(nc_obj, label):\n return nc_obj.variables[label][:].flatten()\n\ndef get_dataframe(nc_path):\n \"\"\"\n A quick function to transform a netcdf file into a pandas dataframe that\n can be used for analysis and plotting. Attributes are extracted using\n in built netCDF4 library functions. Time is arbitrary and needs to be\n set by the user.\n \"\"\"\n print(\"> pickling contents in object at {0}\".format(nc_path))\n # make a connection to the netCDF file\n ncdf_con = nc.Dataset(nc_path, 'r', format=\"NETCDF4\")\n # number of rows, equivalent to time-steps\n time_len = len(ncdf_con.dimensions['time'])\n # extract time information\n time_sec = ncdf_con.variables['time']\n sec_orig = re.search(r'\\d+.*', str(time_sec.units)).group(0)\n # the header values for each measurements; excludes time and space components\n nc_allkeys = ncdf_con.variables.keys()\n # only want time-varying inputs\n data_values = [key for key in nc_allkeys \\\n if re.search(\"^((?!x|y|time|latitude|longitude).)*$\", key)]\n\n # create a new dataframe from the netCDF file\n nc_dataframe = pd.DataFrame({label: get_value(ncdf_con, label) \\\n for label in data_values}, \\\n index=pd.date_range(sec_orig, \\\n periods=time_len, freq=\"30min\"))\n return nc_dataframe\n\ndef main():\n\n # Retrieve dataframes of tree and grass productivity from ncdf files\n input_df = get_dataframe(DIRPATH)\n\n # pickle the leaf scale outputs (see if it's quicker to load)\n pickle.dump(input_df, open(PKLPATH+\"hourly/tower_inputs.pkl\", \"wb\"))\n\n return None\n\nif __name__ == '__main__':\n\n DIRPATH = os.path.expanduser(\"~/Savanna/Data/HowardSprings_IAV/ncdf/spa_hws_inputs.nc\")\n PKLPATH = os.path.expanduser(\"~/Savanna/Data/HowardSprings_IAV/pickled/\")\n\n main()\n" ]
[ [ "pandas.read_csv" ], [ "pandas.date_range" ] ]
jlparkI/outlier_robust_polyfit
[ "59ef64c5ed7c92856435eaae748f38ca0a649ea4" ]
[ "setup.py" ]
[ "from setuptools import Extension, setup\nimport numpy as np\n\nwith open(\"README.md\", \"r\") as fhandle:\n long_description = fhandle.read()\n\nsetup(\n name=\"RobustPolyfit\",\n version=\"0.0.8.1\",\n author=\"Jonathan Parkinson\",\n description=\"Outlier-robust regression for polynomials 1 <= degree <= 3\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/jlparki/outlier_robust_polyfit\",\n ext_modules=[Extension(\"RobustPolyfit\", [\"src/RobustPolyfit.c\"])],\n include_dirs=[np.get_include()],\n install_requires=[\"numpy\", \"scipy\", \"cython\"]\n)\n\n" ]
[ [ "numpy.get_include" ] ]
ehsteve/sunpy
[ "cd9859392d58cf86d6ea96cc8f4c065bce7fcc7b" ]
[ "sunpy/coordinates/ephemeris.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nEphemeris calculations using SunPy coordinate frames\n\"\"\"\nimport numpy as np\n\nfrom astropy.coordinates import (SkyCoord, get_body_barycentric,\n ICRS, HeliocentricEclipticIAU76)\nfrom astropy.coordinates.representation import CartesianRepresentation\nfrom astropy.constants import c as speed_of_light\nfrom astropy.time import Time\nimport astropy.units as u\n\nfrom sunpy import log\nfrom sunpy.time import parse_time\nfrom sunpy.time.time import _variables_for_parse_time_docstring\nfrom sunpy.util.decorators import add_common_docstring\n\nfrom .frames import HeliographicStonyhurst\n\n__author__ = \"Albert Y. Shih\"\n__email__ = \"[email protected]\"\n\n__all__ = ['get_body_heliographic_stonyhurst', 'get_earth',\n 'get_horizons_coord']\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef get_body_heliographic_stonyhurst(body, time='now', observer=None):\n \"\"\"\n Return a `~sunpy.coordinates.frames.HeliographicStonyhurst` frame for the location of a\n solar-system body at a specified time. The location can be corrected for light travel time\n to an observer.\n\n Parameters\n ----------\n body : `str`\n The solar-system body for which to calculate positions\n time : {parse_time_types}\n Time to use in a parse_time-compatible format\n observer : `~astropy.coordinates.SkyCoord`\n If None, the returned coordinate is the instantaneous or \"true\" location.\n If not None, the returned coordinate is the astrometric location (i.e., accounts for light\n travel time to the specified observer)\n\n Returns\n -------\n out : `~sunpy.coordinates.frames.HeliographicStonyhurst`\n Location of the solar-system body in the `~sunpy.coordinates.HeliographicStonyhurst` frame\n\n Notes\n -----\n There is no correction for aberration due to observer motion. For a body close to the Sun in\n angular direction relative to the observer, the correction can be negligible because the\n apparent location of the body will shift in tandem with the Sun.\n \"\"\"\n obstime = parse_time(time)\n\n if observer is None:\n body_icrs = get_body_barycentric(body, obstime)\n else:\n observer_icrs = SkyCoord(observer).icrs.cartesian\n\n # This implementation is modeled after Astropy's `_get_apparent_body_position`\n light_travel_time = 0.*u.s\n emitted_time = obstime\n delta_light_travel_time = 1.*u.s # placeholder value\n while np.any(np.fabs(delta_light_travel_time) > 1.0e-8*u.s):\n body_icrs = get_body_barycentric(body, emitted_time)\n distance = (body_icrs - observer_icrs).norm()\n delta_light_travel_time = light_travel_time - distance / speed_of_light\n light_travel_time = distance / speed_of_light\n emitted_time = obstime - light_travel_time\n\n if light_travel_time.isscalar:\n ltt_string = f\"{light_travel_time.to_value('s'):.2f}\"\n else:\n ltt_string = f\"{light_travel_time.to_value('s')}\"\n log.info(f\"Apparent body location accounts for {ltt_string} seconds of light travel time\")\n\n body_hgs = ICRS(body_icrs).transform_to(HeliographicStonyhurst(obstime=obstime))\n\n return body_hgs\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef get_earth(time='now'):\n \"\"\"\n Return a `~astropy.coordinates.SkyCoord` for the location of the Earth at a specified time in\n the `~sunpy.coordinates.frames.HeliographicStonyhurst` frame. The longitude will be 0 by definition.\n\n Parameters\n ----------\n time : {parse_time_types}\n Time to use in a parse_time-compatible format\n\n Returns\n -------\n out : `~astropy.coordinates.SkyCoord`\n Location of the Earth in the `~sunpy.coordinates.frames.HeliographicStonyhurst` frame\n \"\"\"\n earth = get_body_heliographic_stonyhurst('earth', time=time)\n\n # Explicitly set the longitude to 0\n earth = SkyCoord(0*u.deg, earth.lat, earth.radius, frame=earth)\n\n return earth\n\n\n@add_common_docstring(**_variables_for_parse_time_docstring())\ndef get_horizons_coord(body, time='now', id_type='majorbody'):\n \"\"\"\n Queries JPL HORIZONS and returns a `~astropy.coordinates.SkyCoord` for the location of a\n solar-system body at a specified time. This location is the instantaneous or \"true\" location,\n and is not corrected for light travel time or observer motion.\n\n .. note::\n This function requires the Astroquery package to be installed and\n requires an Internet connection.\n\n Parameters\n ----------\n body : `str`\n The solar-system body for which to calculate positions. One can also use the search form\n linked below to find valid names or ID numbers.\n id_type : `str`\n If 'majorbody', search by name for planets, satellites, or other major bodies.\n If 'smallbody', search by name for asteroids or comets.\n If 'id', search by ID number.\n time : {parse_time_types}\n Time to use in a parse_time-compatible format\n\n Returns\n -------\n `~astropy.coordinates.SkyCoord`\n Location of the solar-system body\n\n Notes\n -----\n Be aware that there can be discrepancies between the coordinates returned by JPL HORIZONS,\n the coordinates reported in mission data files, and the coordinates returned by\n `~sunpy.coordinates.get_body_heliographic_stonyhurst`.\n\n References\n ----------\n * `JPL HORIZONS <https://ssd.jpl.nasa.gov/?horizons>`_\n * `JPL HORIZONS form to search bodies <https://ssd.jpl.nasa.gov/horizons.cgi?s_target=1#top>`_\n * `Astroquery <https://astroquery.readthedocs.io/en/latest/>`_\n\n Examples\n --------\n >>> from sunpy.coordinates import get_horizons_coord\n\n Query the location of Venus\n\n >>> get_horizons_coord('Venus barycenter', '2001-02-03 04:05:06') # doctest: +REMOTE_DATA\n INFO: Obtained JPL HORIZONS location for Venus Barycenter (2) [sunpy.coordinates.ephemeris]\n <SkyCoord (HeliographicStonyhurst: obstime=2001-02-03T04:05:06.000): (lon, lat, radius) in (deg, deg, AU)\n (-33.93155836, -1.64998443, 0.71915147)>\n\n Query the location of the SDO spacecraft\n\n >>> get_horizons_coord('SDO', '2011-11-11 11:11:11') # doctest: +REMOTE_DATA\n INFO: Obtained JPL HORIZONS location for Solar Dynamics Observatory (spac [sunpy.coordinates.ephemeris]\n <SkyCoord (HeliographicStonyhurst: obstime=2011-11-11T11:11:11.000): (lon, lat, radius) in (deg, deg, AU)\n (0.01019118, 3.29640728, 0.99011042)>\n\n Query the location of the SOHO spacecraft via its ID number (-21)\n\n >>> get_horizons_coord(-21, '2004-05-06 11:22:33', 'id') # doctest: +REMOTE_DATA\n INFO: Obtained JPL HORIZONS location for SOHO (spacecraft) (-21) [sunpy.coordinates.ephemeris]\n <SkyCoord (HeliographicStonyhurst: obstime=2004-05-06T11:22:33.000): (lon, lat, radius) in (deg, deg, AU)\n (0.25234902, -3.55863633, 0.99923086)>\n \"\"\"\n obstime = parse_time(time)\n array_time = np.reshape(obstime, (-1,)) # Convert to an array, even if scalar\n\n # Import here so that astroquery is not a module-level dependency\n from astroquery.jplhorizons import Horizons\n query = Horizons(id=body, id_type=id_type,\n location='500@10', # Heliocentric (mean ecliptic)\n epochs=array_time.tdb.jd.tolist()) # Time must be provided in JD TDB\n try:\n result = query.vectors()\n except Exception: # Catch and re-raise all exceptions, and also provide query URL if generated\n if query.uri is not None:\n log.error(f\"See the raw output from the JPL HORIZONS query at {query.uri}\")\n raise\n log.info(f\"Obtained JPL HORIZONS location for {result[0]['targetname']}\")\n log.debug(f\"See the raw output from the JPL HORIZONS query at {query.uri}\")\n\n # JPL HORIZONS results are sorted by observation time, so this sorting needs to be undone.\n # Calling argsort() on an array returns the sequence of indices of the unsorted list to put the\n # list in order. Calling argsort() again on the output of argsort() reverses the mapping:\n # the output is the sequence of indices of the sorted list to put that list back in the\n # original unsorted order.\n unsorted_indices = obstime.argsort().argsort()\n result = result[unsorted_indices]\n\n vector = CartesianRepresentation(result['x'], result['y'], result['z'])\n coord = SkyCoord(vector, frame=HeliocentricEclipticIAU76, obstime=obstime)\n\n return coord.transform_to(HeliographicStonyhurst).reshape(obstime.shape)\n" ]
[ [ "numpy.reshape", "numpy.fabs" ] ]
brunojacobs/ulsdpb
[ "7beff2e5f086d352258cd128430ec16ebfde7d53" ]
[ "expfam/wishart.py" ]
[ "# External modules\nimport numpy as np\n\n# Own modules\nfrom expfam.misc import log_det, log_mvar_gamma, mvar_digamma\n\n\n#\n# Parameter mappings\n#\n\n\ndef dim_from_concatenated_vector(v):\n \"\"\"Returns the value of K for a (1 + K*K)-vector.\"\"\"\n return int(np.sqrt(v.shape[0] - 1))\n\n\ndef concatenated_vector_to_scalar_matrix(v):\n \"\"\"Split a (1 + K*K)-vector into a scalar and a (K, K)-matrix.\"\"\"\n k = dim_from_concatenated_vector(v)\n scalar = v[0]\n matrix = np.reshape(v[1:], (k, k))\n return scalar, matrix\n\n\ndef map_from_n_v_to_eta(n, v):\n \"\"\"Map parameters from (n, v)-space to eta-space.\"\"\"\n return np.hstack((0.5 * n, -0.5 * np.ravel(np.linalg.inv(v))))\n\n\ndef map_from_eta_to_n_v(eta):\n \"\"\"Map parameters from eta-space to (n, v)-space.\"\"\"\n eta_0, eta_1 = concatenated_vector_to_scalar_matrix(eta)\n n = 2 * eta_0\n v = np.linalg.inv(-2 * eta_1)\n return n, v\n\n\n#\n# Exponential family identities\n#\n\n\ndef log_h(x):\n k = x.shape[0]\n return -0.5 * (k + 1) * log_det(x)\n\n\ndef t(x):\n return np.hstack((log_det(x), np.ravel(x)))\n\n\ndef a(eta):\n eta_0, eta_1 = concatenated_vector_to_scalar_matrix(eta)\n k = eta_1.shape[0]\n return log_mvar_gamma(k, eta_0) - eta_0 * log_det(-eta_1)\n\n\n#\n# Expected values\n#\n\n\ndef ev_t(eta):\n eta_0, eta_1 = concatenated_vector_to_scalar_matrix(eta)\n k = eta_1.shape[0]\n ev_t_0 = mvar_digamma(dim=k, arg=eta_0) - log_det(-eta_1)\n ev_t_1 = eta_0 * np.ravel(np.linalg.inv(-eta_1))\n return np.hstack((ev_t_0, ev_t_1))\n\n\ndef split_ev_t(eta):\n eta_0, eta_1 = concatenated_vector_to_scalar_matrix(eta)\n k = eta_1.shape[0]\n ev_t_0 = mvar_digamma(dim=k, arg=eta_0) - log_det(-eta_1)\n ev_t_1 = eta_0 * np.linalg.inv(-eta_1)\n return ev_t_0, ev_t_1\n\n\ndef ev_log_det_x(eta):\n eta_0, eta_1 = concatenated_vector_to_scalar_matrix(eta)\n k = eta_1.shape[0]\n return mvar_digamma(dim=k, arg=eta_0) - log_det(-eta_1)\n\n\ndef ev_x(eta):\n eta_0, eta_1 = concatenated_vector_to_scalar_matrix(eta)\n ev_t_1 = eta_0 * np.linalg.inv(-eta_1)\n return ev_t_1\n\n\ndef ev_inv_x(eta):\n n, v = map_from_eta_to_n_v(eta=eta)\n mean_inv_x = np.linalg.inv(v) / (n - v.shape[0] - 1)\n return mean_inv_x\n\n\ndef kl_divergence(eta_q, eta_p):\n \"\"\"KL-divergence{ q(x | eta_q) || p(x | eta_p) }.\"\"\"\n return ev_t(eta_q) @ (eta_q - eta_p) - a(eta_q) + a(eta_p)\n" ]
[ [ "numpy.hstack", "numpy.sqrt", "numpy.reshape", "numpy.linalg.inv", "numpy.ravel" ] ]
gioxc88/scipy-dash
[ "f89abda475438ed28bedd4d0d877e0fc9c272b70" ]
[ "app/utils.py" ]
[ "from functools import wraps\n\nimport numpy as np\nimport pandas as pd\n\n\ndef dash_kwarg(inputs):\n def accept_func(func):\n @wraps(func)\n def wrapper(*args):\n input_names = [item.component_id for item in inputs]\n kwargs_dict = dict(zip(input_names, args))\n return func(**kwargs_dict)\n\n return wrapper\n\n return accept_func\n\n\ndef skewness(dist):\n try:\n result = (dist.moment(3) -\n 3 * dist.moment(2) * dist.moment(1) +\n 2 * dist.moment(1) ** 3) / dist.std() ** 3\n except:\n result = np.nan\n return result\n\n\ndef kurtosis(dist):\n try:\n result = (dist.moment(4) +\n dist.moment(1) ** 4 +\n 6 * dist.moment(1) ** 2 * dist.moment(2) -\n 4 * dist.moment(3) * dist.moment(1) -\n 4 * dist.moment(1) ** 4) / dist.std() ** 4\n except:\n result = np.nan\n return result\n\n\ndef dist_summary(dist, name):\n mean = dist.mean()\n std = dist.std()\n var = dist.var()\n skew = skewness(dist)\n kurt = kurtosis(dist)\n return pd.Series({'name': name,\n 'mean': mean,\n 'std': std,\n 'variance': var,\n 'skewness': skew,\n 'kurtosis': kurt})\n\n\ndef dist_summary_dict(dist, name):\n mean = dist.mean()\n std = dist.std()\n var = dist.vat()\n skew = skewness(dist)\n kurt = kurtosis(dist)\n" ]
[ [ "pandas.Series" ] ]
kaeldai/sonata
[ "9f5d95748d0a83ca231d955f77f5a0257c58ce1d" ]
[ "examples/300_cells/build_network.py" ]
[ "import os\nimport numpy as np\n\nfrom bmtk.builder import NetworkBuilder\nfrom bmtk.builder.bionet import SWCReader\nfrom bmtk.utils.io.spike_trains import PoissonSpikesGenerator\nfrom bmtk.builder.auxi.node_params import positions_columinar, xiter_random\n\nbuild_recurrent_edges = True\n\nprint('Building internal network')\n# List of non-virtual cell models\ncell_models = [\n {\n 'model_name': 'Scnn1a', 'ei': 'e',\n 'morphology': 'Scnn1a_473845048_m',\n 'model_template': 'nml:Cell_472363762.cell.nml'\n },\n {\n 'model_name': 'Rorb', 'ei': 'e',\n 'morphology': 'Rorb_325404214_m',\n 'model_template': 'nml:Cell_473863510.cell.nml'\n },\n {\n 'model_name': 'Nr5a1', 'ei': 'e',\n 'morphology': 'Nr5a1_471087815_m',\n 'model_template': 'nml:Cell_473863035.cell.nml'\n },\n {\n 'model_name': 'PV1', 'ei': 'i',\n 'morphology': 'Pvalb_470522102_m',\n 'model_template': 'nml:Cell_472912177.cell.nml'\n },\n {\n 'model_name': 'PV2', 'ei': 'i',\n 'morphology': 'Pvalb_469628681_m',\n 'model_template': 'nml:Cell_473862421.cell.nml'\n }\n]\n\nmorphologies = {p['model_name']: SWCReader(os.path.join('../shared_components/morphologies',\n '{}.swc'.format(p['morphology'])))\n for p in cell_models}\ndef build_edges(src, trg, sections=['basal', 'apical'], dist_range=[50.0, 150.0]):\n \"\"\"Function used to randomly assign a synaptic location based on the section (soma, basal, apical) and an\n arc-length dist_range from the soma. This function should be passed into the network and called during the build\n process.\n\n :param src: source cell (dict)\n :param trg: target cell (dict)\n :param sections: list of target cell sections to synapse onto\n :param dist_range: range (distance from soma center) to place\n :return:\n \"\"\"\n # Get morphology and soma center for the target cell\n swc_reader = morphologies[trg['model_name']]\n target_coords = [trg['x'], trg['y'], trg['z']]\n\n sec_ids, sec_xs = swc_reader.choose_sections(sections, dist_range) # randomly choose sec_ids\n coords = swc_reader.get_coord(sec_ids, sec_xs, soma_center=target_coords) # get coords of sec_ids\n dist = swc_reader.get_dist(sec_ids)\n swctype = swc_reader.get_type(sec_ids)\n return sec_ids, sec_xs, coords[0][0], coords[0][1], coords[0][2], dist[0], swctype[0]\n\n\n# Build a network of 300 biophysical cells to simulate\ninternal = NetworkBuilder(\"internal\")\nfor i, model_props in enumerate(cell_models):\n n_cells = 80 if model_props['ei'] == 'e' else 30 # 80% excitatory, 20% inhib\n\n # Randomly get positions uniformly distributed in a column\n positions = positions_columinar(N=n_cells, center=[0, 10.0, 0], max_radius=50.0, height=200.0)\n\n internal.add_nodes(N=n_cells,\n x=positions[:, 0], y=positions[:, 1], z=positions[:, 2],\n rotation_angle_yaxis=xiter_random(N=n_cells, min_x=0.0, max_x=2 * np.pi), # randomly rotate y axis\n model_type='biophysical',\n model_processing='aibs_perisomatic',\n **model_props)\n\nif build_recurrent_edges:\n def n_connections(src, trg, prob=0.5, min_syns=2, max_syns=7):\n return 0 if np.random.uniform() > prob else np.random.randint(min_syns, max_syns)\n\n # exc --> exc connections\n cm = internal.add_edges(source={'ei': 'e'}, target={'ei': 'e'},\n connection_rule=n_connections,\n connection_params={'prob': 0.2},\n #connection_rule=lambda *_: np.random.randint(0, 7),\n dynamics_params='AMPA_ExcToExc.json',\n model_template='Exp2Syn',\n delay=2.0)\n cm.add_properties('syn_weight', rule=6.0e-05, dtypes=np.float)\n cm.add_properties(['sec_id', 'sec_x', 'pos_x', 'pos_y', 'pos_z', 'dist', 'type'],\n rule=build_edges,\n rule_params={'sections': ['basal', 'apical'], 'dist_range': [30.0, 150.0]},\n dtypes=[np.int32, np.float, np.float, np.float, np.float, np.float, np.uint8])\n\n # exc --> inh connections\n cm = internal.add_edges(source={'ei': 'e'}, target={'ei': 'i'},\n connection_rule=n_connections,\n dynamics_params='AMPA_ExcToInh.json',\n model_template='Exp2Syn',\n delay=2.0)\n cm.add_properties('syn_weight', rule=0.0006, dtypes=np.float)\n cm.add_properties(['sec_id', 'sec_x', 'pos_x', 'pos_y', 'pos_z', 'dist', 'type'],\n rule=build_edges,\n rule_params={'sections': ['somatic', 'basal'], 'dist_range': [0.0, 1.0e+20]},\n dtypes=[np.int32, np.float, np.float, np.float, np.float, np.float, np.uint8])\n\n # inh --> exc connections\n cm = internal.add_edges(source={'ei': 'i'}, target={'ei': 'i'},\n connection_rule=n_connections,\n #connection_rule=lambda *_: np.random.randint(0, 4),\n dynamics_params='GABA_InhToExc.json',\n model_template='Exp2Syn',\n delay=2.0)\n cm.add_properties('syn_weight', rule=0.002, dtypes=np.float)\n cm.add_properties(['sec_id', 'sec_x', 'pos_x', 'pos_y', 'pos_z', 'dist', 'type'],\n rule=build_edges,\n rule_params={'sections': ['somatic', 'basal', 'apical'], 'dist_range': [0.0, 50.0]},\n dtypes=[np.int32, np.float, np.float, np.float, np.float, np.float, np.uint8])\n\n # inh --> inh connections\n cm = internal.add_edges(source={'ei': 'i'}, target={'ei': 'i'},\n connection_rule=n_connections,\n dynamics_params='GABA_InhToInh.json',\n model_template='Exp2Syn',\n delay=2.0)\n cm.add_properties('syn_weight', rule=0.00015, dtypes=np.float)\n cm.add_properties(['sec_id', 'sec_x', 'pos_x', 'pos_y', 'pos_z', 'dist', 'type'],\n rule=build_edges,\n rule_params={'sections': ['somatic', 'basal'], 'dist_range': [0.0, 1.0e+20]},\n dtypes=[np.int32, np.float, np.float, np.float, np.float, np.float, np.uint8])\n\n\ninternal.build()\n\nprint('Saving internal')\ninternal.save(output_dir='network')\n\n\nprint('Building external connections')\nexternal = NetworkBuilder(\"external\")\nexternal.add_nodes(N=100, model_type='virtual', ei='e')\ncm = external.add_edges(target=internal.nodes(ei='e'), source=external.nodes(),\n connection_rule=lambda *_: np.random.randint(0, 5),\n dynamics_params='AMPA_ExcToExc.json',\n model_template='Exp2Syn',\n delay=2.0)\ncm.add_properties('syn_weight', rule=2.1e-4, dtypes=np.float)\ncm.add_properties(['sec_id', 'sec_x', 'pos_x', 'pos_y', 'pos_z', 'dist', 'type'],\n rule=build_edges,\n dtypes=[np.int32, np.float, np.float, np.float, np.float, np.float, np.uint8])\n\ncm = external.add_edges(target=internal.nodes(ei='i'), source=external.nodes(),\n connection_rule=lambda *_: np.random.randint(0, 5),\n dynamics_params='AMPA_ExcToInh.json',\n model_template='Exp2Syn',\n delay=2.0)\ncm.add_properties('syn_weight', rule=0.0015, dtypes=np.float)\ncm.add_properties(['sec_id', 'sec_x', 'pos_x', 'pos_y', 'pos_z', 'dist', 'type'],\n rule=build_edges,\n dtypes=[np.int32, np.float, np.float, np.float, np.float, np.float, np.uint8])\n\n\nexternal.build()\n\nprint('Saving external')\nexternal.save(output_dir='network')\n\n\n" ]
[ [ "numpy.random.uniform", "numpy.random.randint" ] ]